Compare commits
277 Commits
feat/bot-a
...
renovate/p
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c043c408f1 | ||
| 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 | |||
| 398d4113c8 | |||
| 32c101934d | |||
| 48e00bada4 | |||
| bc69136133 | |||
| a96939684b | |||
| ed1608b8e3 | |||
| f4f653614d | |||
| 5fca354c58 | |||
| b4ad29853a | |||
| cf2f0ac86d | |||
| f57dec65e0 | |||
| 4c7ddeeb72 | |||
| 2a4a1adcd8 | |||
| 107982dbec | |||
| a75d9e3795 | |||
| 5336541010 | |||
| dd71b822ed | |||
| d343335b8e | |||
| 892cb7ab87 | |||
| b274903dc1 | |||
| b1c20a374a | |||
| 0b6b23c42d | |||
| 008db9e2c8 | |||
| 24bfcff68a | |||
| dc2b01ae21 | |||
| ef4563cc7c | |||
| 936b853536 | |||
| 60387773bf | |||
| eac101764b | |||
| 5f43567d89 | |||
|
|
bf86bafbe8 | ||
|
|
8f2516cabe | ||
|
|
d2cd99d3d4 | ||
|
|
c8e3b63cc5 | ||
| 60e01d8207 | |||
| 9e0ca29a2c | |||
| ae4d88a9e0 | |||
| 5735074af9 | |||
| 899e8f1054 | |||
| acd8e0d980 | |||
| cb10ee1855 | |||
| b0eb5d4430 | |||
| d8b9803019 | |||
| 2ceb813a98 | |||
| 6222f9dafe | |||
| c7bb9aef72 | |||
| 7456e80473 | |||
| a0cabbfa63 | |||
| 2f8ac7d343 | |||
| 0157eff9f3 | |||
| ebcb062b6a | |||
| fdc8e0f33c | |||
| eeb44dfae7 | |||
|
|
0e9f0a54dd | ||
|
|
5d81d32276 | ||
|
|
fe21d19250 | ||
| eac736b9fb | |||
| 381f4fc523 | |||
| 7d350cfc04 | |||
| 2dfbab5d0e | |||
| 4eef997d63 | |||
| 7574b94933 | |||
| 6c26ca9d2f | |||
| a1727b9a3d | |||
| f486c3b28e | |||
| 8e86be97d1 | |||
| 099b321b79 | |||
| 6fdadbec28 | |||
| 92cde437af | |||
| 28cbe4e8ed | |||
| 09d099d0ee | |||
| 5c99fee95d | |||
| df845b5601 | |||
| d4a6516157 | |||
| 17bbba7df3 | |||
|
|
1e27c7e77a | ||
|
|
80595d6299 | ||
|
|
aa9d0c1ca5 | ||
|
|
45894fc900 | ||
| ddbdf3caf9 | |||
| 80a8e670e1 | |||
| 3e5824093e | |||
| 75d6e648f9 | |||
|
|
1fadaa3600 | ||
|
|
7262b0e5c2 | ||
|
|
70832c7de8 | ||
|
|
61972da255 | ||
| 221aff0050 | |||
| 5b6addac9a | |||
| 5add3b0e5d | |||
| b623de5bdd | |||
| cc15a06ffb | |||
| c0f3e9d52e | |||
| a22dcf0746 | |||
|
|
b4d3cd5bb8 | ||
|
|
d5c02889de | ||
| c0657cc1ce | |||
| d97add9659 | |||
| 8f07dbadf3 | |||
| 21ab8a5e4f | |||
| 689c410828 | |||
| 593baa6505 | |||
| 786a2afb6c | |||
| 75f25eb8fe | |||
| 0e500037c4 | |||
| b49318f9e6 | |||
| 927d7d1bda | |||
| d1f5cc7a6d | |||
| 0afc54f0bf | |||
| 0581cc6a61 | |||
| 18025ced9d | |||
| 044221f147 | |||
| 0cabbd8720 | |||
| 5fdb6921d9 | |||
| 312ad480a2 | |||
| a37554d205 | |||
| 5244275264 | |||
| 5275e8cb2a | |||
| 1ff51fad61 | |||
| 440eb407dd | |||
| 4ab1756230 | |||
| f9d11476bf | |||
| 8e8c58e195 | |||
| 6fcbeaa2a7 | |||
| caef4e428a | |||
| cf49fea907 | |||
| 7683f765b0 | |||
| 4d91f15a43 | |||
| 3b49f8d25a | |||
| c99ace0ef5 | |||
| a834b63ac8 | |||
| 09871d3fae | |||
| 2a0a7abe1a | |||
| 2a15a6367a | |||
| 6fad756bd2 | |||
| 0bb44960b4 | |||
| ac2276b112 | |||
| 1adb9be6cc | |||
| a9625f3505 | |||
| 3611e23869 | |||
| f8aa1454ff | |||
| 6e8539a8d1 | |||
| 592524eedb | |||
| 989462e639 | |||
| a7e9115587 | |||
| 934f589b5f | |||
| 27a6838d9f | |||
| 75085630be | |||
| 642270ee91 | |||
| f543061672 | |||
| 3a89f07a6f | |||
| fb40d87736 | |||
| 34d7afd03d | |||
| 495027ca7e | |||
| 55df22341e |
98
.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,13 +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/
|
||||
|
||||
export SLACK_TOKEN=${{ secrets.SLACK_TOKEN }}
|
||||
|
||||
./slack-import-emojis-bin default
|
||||
|
||||
cp emojis.json apps/web/
|
||||
@@ -63,41 +62,7 @@ jobs:
|
||||
secrets: |
|
||||
TURBO_TOKEN=${{ secrets.TURBO_TOKEN }}
|
||||
TURBO_TEAM=${{ secrets.TURBO_TEAM }}
|
||||
db:
|
||||
name: Push db 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-db
|
||||
tags: latest
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./packages/db/Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
platforms: linux/amd64
|
||||
secrets: |
|
||||
TURBO_TOKEN=${{ secrets.TURBO_TOKEN }}
|
||||
TURBO_TEAM=${{ secrets.TURBO_TEAM }}
|
||||
SENTRY_AUTH_TOKEN=${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
chat:
|
||||
name: Push chat module to Docker Hub
|
||||
runs-on: ubuntu-latest
|
||||
@@ -133,22 +98,43 @@ jobs:
|
||||
secrets: |
|
||||
TURBO_TOKEN=${{ secrets.TURBO_TOKEN }}
|
||||
TURBO_TEAM=${{ secrets.TURBO_TEAM }}
|
||||
deploy:
|
||||
name: Deploy to server
|
||||
mediamtx:
|
||||
name: Push MediaMTX image to Docker Hub
|
||||
runs-on: ubuntu-latest
|
||||
needs: [frontend, db, chat]
|
||||
steps:
|
||||
# source https://github.com/taciturnaxolotl/cachet/blob/main/.github/workflows/deploy.yaml
|
||||
- name: Deploy with Docker
|
||||
uses: appleboy/ssh-action@v1
|
||||
- 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:
|
||||
host: hackclub.app
|
||||
username: srizan
|
||||
key: ${{ secrets.SSH_KEY }}
|
||||
port: 22
|
||||
script: |
|
||||
cd ~/compose/hctv
|
||||
docker compose pull
|
||||
docker compose up -d --remove-orphans
|
||||
# for some reason, without the restart, the rtmp container stops working
|
||||
docker compose restart
|
||||
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, 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
|
||||
|
||||
7
.gitignore
vendored
@@ -28,6 +28,7 @@ yarn-error.log*
|
||||
# local env files
|
||||
.env*.local
|
||||
.env*
|
||||
!.env.example
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
@@ -47,4 +48,8 @@ packages/db/generated/client
|
||||
slack-import-emojis/target
|
||||
**/*/emojis.json
|
||||
|
||||
.idea
|
||||
.idea
|
||||
|
||||
/apps/docs/src/content/docs/typedoc-sdk
|
||||
|
||||
.codex
|
||||
343
AGENTS.md
Normal file
@@ -0,0 +1,343 @@
|
||||
# Agent Guidelines for tv
|
||||
|
||||
This document provides essential information for AI coding agents working on the HackClub.tv codebase.
|
||||
|
||||
## Project Overview
|
||||
|
||||
HackClub.tv is a live streaming platform built with Next.js 16, Prisma, and Turbo monorepo architecture.
|
||||
|
||||
- **Monorepo**: Turborepo with pnpm workspaces
|
||||
- **Apps**: web (Next.js), chat (Hono), docs
|
||||
- **Packages**: db (Prisma), auth (Lucia), hono-ws, sdk
|
||||
- **Package Manager**: pnpm 10.6.5
|
||||
|
||||
## Build, Lint, and Test Commands
|
||||
|
||||
### Root Level Commands
|
||||
|
||||
```bash
|
||||
pnpm install # Install all dependencies
|
||||
pnpm build # Build all apps and packages (uses Turbo)
|
||||
pnpm dev # Start all apps in dev mode (uses Turbo)
|
||||
pnpm lint # Lint all apps (uses Turbo)
|
||||
```
|
||||
|
||||
### Database Commands
|
||||
|
||||
```bash
|
||||
pnpm db:migrate # Run Prisma migrations in dev
|
||||
pnpm prisma # Run any Prisma command in db package
|
||||
```
|
||||
|
||||
### App-Specific Commands
|
||||
|
||||
```bash
|
||||
# Web app (Next.js)
|
||||
pnpm --filter=@hctv/web dev # Start Next.js dev server
|
||||
pnpm --filter=@hctv/web build # Build Next.js app
|
||||
pnpm --filter=@hctv/web lint # Lint web app
|
||||
pnpm --filter=@hctv/web check-types # Type check (tsc --noEmit)
|
||||
pnpm --filter=@hctv/web ui:add # Add shadcn components
|
||||
|
||||
# Chat app (Hono)
|
||||
pnpm --filter=@hctv/chat dev # Start chat server with watch
|
||||
pnpm --filter=@hctv/chat build # Build chat server
|
||||
|
||||
# DB package (Prisma)
|
||||
pnpm --filter=@hctv/db db:generate # Generate Prisma client
|
||||
pnpm --filter=@hctv/db db:migrate # Run migrations
|
||||
pnpm --filter=@hctv/db build # Generate client and build
|
||||
```
|
||||
|
||||
### Running Single Tests
|
||||
|
||||
This project does not currently have a test suite configured. When adding tests:
|
||||
|
||||
- Use Vitest or Jest for unit tests
|
||||
- Use Playwright for E2E tests (recommended for Next.js)
|
||||
- Follow the pattern: `pnpm test -- <test-file-path>`
|
||||
|
||||
### Docker Commands
|
||||
|
||||
```bash
|
||||
pnpm docker:web # Build web app Docker image
|
||||
pnpm docker:chat # Build chat app Docker image
|
||||
pnpm r:rtmp # Restart RTMP server
|
||||
```
|
||||
|
||||
## Code Style Guidelines
|
||||
|
||||
### Formatting
|
||||
|
||||
- **Formatter**: Prettier (`.prettierrc.json`)
|
||||
- **Indentation**: 2 spaces (no tabs)
|
||||
- **Line Width**: 100 characters
|
||||
- **Quotes**: Single quotes
|
||||
- **Semicolons**: Required
|
||||
- **Trailing Commas**: ES5 style
|
||||
- **Linter**: ESLint with Next.js rules (`next/core-web-vitals`)
|
||||
|
||||
### Import Organization
|
||||
|
||||
Imports should be ordered as follows (no blank lines between groups):
|
||||
|
||||
1. React/Next.js core imports
|
||||
2. Third-party libraries
|
||||
3. Internal components (`@/components`)
|
||||
4. Internal utilities/libs (`@/lib`)
|
||||
5. Package imports (`@hctv/*`)
|
||||
6. Type imports (use `import type` keyword)
|
||||
7. Relative imports
|
||||
|
||||
```typescript
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Send } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
import type { User, Channel } from '@hctv/db';
|
||||
import { helper } from './utils';
|
||||
```
|
||||
|
||||
### TypeScript Usage
|
||||
|
||||
- **Strict mode**: Enabled
|
||||
- **Type over interface**: Use `type` for unions/intersections, `interface` for object shapes
|
||||
- **No implicit any**: Always type your variables
|
||||
- **Type imports**: Use `import type` for type-only imports
|
||||
- **Prisma types**: Import from `@hctv/db` and use type composition
|
||||
|
||||
```typescript
|
||||
// Interfaces for props and object shapes
|
||||
interface ChatMessage {
|
||||
user?: User;
|
||||
message: string;
|
||||
type: 'message' | 'systemMsg';
|
||||
}
|
||||
|
||||
// Type aliases for complex types
|
||||
type FormFieldConfig = {
|
||||
name: string;
|
||||
label?: string;
|
||||
};
|
||||
|
||||
// Prisma type composition
|
||||
type StreamWithChannel = StreamInfo & { channel: Channel };
|
||||
```
|
||||
|
||||
### Naming Conventions
|
||||
|
||||
**Files:**
|
||||
|
||||
- React components: `PascalCase.tsx` (e.g., `ChatPanel.tsx`)
|
||||
- Utilities/helpers: `camelCase.ts` (e.g., `validate.ts`)
|
||||
- Next.js pages: `page.tsx`, `route.ts`, `layout.tsx`
|
||||
- Client components: `page.client.tsx`
|
||||
|
||||
**Variables & Functions:**
|
||||
|
||||
- Components: `PascalCase`
|
||||
- Functions: `camelCase`
|
||||
- Constants: `SCREAMING_SNAKE_CASE`
|
||||
- Booleans: Use `is`, `has`, `should` prefixes
|
||||
- Refs: `Ref` suffix (e.g., `socketRef`)
|
||||
|
||||
```typescript
|
||||
const MESSAGE_HISTORY_SIZE = 15;
|
||||
const isFollowing = await checkFollowing();
|
||||
const socketRef = useRef<WebSocket | null>(null);
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
**API Routes:**
|
||||
|
||||
- Return `Response` objects with appropriate status codes
|
||||
- Use descriptive error messages
|
||||
- Status codes: 400 (bad request), 401 (unauthorized), 403 (forbidden), 404 (not found)
|
||||
|
||||
```typescript
|
||||
if (!user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
```
|
||||
|
||||
**Server Actions:**
|
||||
|
||||
- Return objects with `success` boolean and `error` or `data` fields
|
||||
- Use `zodVerify` helper for validation
|
||||
|
||||
```typescript
|
||||
const zod = await zodVerify(schema, formData);
|
||||
if (!zod.success) {
|
||||
return { success: false, error: zod.error };
|
||||
}
|
||||
return { success: true, data: result };
|
||||
```
|
||||
|
||||
**Client-side:**
|
||||
|
||||
- Use try-catch for async operations
|
||||
- Use toast notifications (sonner) for user feedback
|
||||
- Log errors with `console.error`
|
||||
|
||||
### Async Patterns
|
||||
|
||||
- **Prefer**: async/await over Promise chains
|
||||
- **Parallel operations**: Use `Promise.all()`
|
||||
- **No .then() chaining**: Except in utility functions like fetchers
|
||||
|
||||
```typescript
|
||||
// Standard async/await
|
||||
const data = await prisma.model.findMany();
|
||||
|
||||
// Parallel operations
|
||||
const [channelA, channelB] = await Promise.all([
|
||||
prisma.channel.findUnique({ where: { id: 'a' } }),
|
||||
prisma.channel.findUnique({ where: { id: 'b' } }),
|
||||
]);
|
||||
```
|
||||
|
||||
## React Component Patterns
|
||||
|
||||
### Component Structure
|
||||
|
||||
1. Directive (`'use client'` or `'use server'`)
|
||||
2. Imports
|
||||
3. Component function
|
||||
4. Helper functions (if needed)
|
||||
5. Type/interface definitions (at bottom)
|
||||
|
||||
```typescript
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
export default function ChatPanel(props: Props) {
|
||||
const [message, setMessage] = useState('');
|
||||
|
||||
return <div>{/* JSX */}</div>;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
username: string;
|
||||
}
|
||||
```
|
||||
|
||||
### Server vs Client Components
|
||||
|
||||
- **Server components**: Default (no directive), use for data fetching
|
||||
- **Client components**: Add `'use client'`, use for interactivity
|
||||
- Fetch data in server components, pass to client components as props
|
||||
|
||||
## Database Patterns (Prisma)
|
||||
|
||||
### Imports
|
||||
|
||||
```typescript
|
||||
import { prisma } from '@hctv/db';
|
||||
import type { User, Channel, StreamInfo } from '@hctv/db';
|
||||
```
|
||||
|
||||
### Common Queries
|
||||
|
||||
```typescript
|
||||
// FindUnique with relations
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { name: channelName },
|
||||
include: { owner: true, streamInfo: true },
|
||||
});
|
||||
|
||||
// FindMany with dynamic filters
|
||||
const where: Prisma.StreamInfoWhereInput = {};
|
||||
if (isLive) where.isLive = true;
|
||||
const streams = await prisma.streamInfo.findMany({ where });
|
||||
|
||||
// Create with relations
|
||||
await prisma.channel.create({
|
||||
data: {
|
||||
name: channelName,
|
||||
ownerId: user.id,
|
||||
personalFor: { connect: { id: user.id } },
|
||||
},
|
||||
});
|
||||
|
||||
// Update
|
||||
await prisma.streamInfo.update({
|
||||
where: { username },
|
||||
data: { title: newTitle },
|
||||
});
|
||||
|
||||
// Upsert
|
||||
await prisma.streamKey.upsert({
|
||||
create: { key: newKey, channelId },
|
||||
update: { key: newKey },
|
||||
where: { channelId },
|
||||
});
|
||||
```
|
||||
|
||||
### Redis Usage
|
||||
|
||||
```typescript
|
||||
import { getRedisConnection } from '@hctv/db';
|
||||
|
||||
const redis = getRedisConnection();
|
||||
await redis.set('key', 'value');
|
||||
await redis.get('key');
|
||||
await redis.setex('key', 30, 'value'); // with expiry
|
||||
```
|
||||
|
||||
## API Route Patterns
|
||||
|
||||
### Next.js App Router
|
||||
|
||||
```typescript
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const param = searchParams.get('param');
|
||||
|
||||
const data = await prisma.model.findMany();
|
||||
return Response.json(data);
|
||||
}
|
||||
```
|
||||
|
||||
### Server Actions
|
||||
|
||||
```typescript
|
||||
'use server';
|
||||
|
||||
export async function createChannel(prev: any, formData: FormData) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
const zod = await zodVerify(createChannelSchema, formData);
|
||||
if (!zod.success) {
|
||||
return zod;
|
||||
}
|
||||
|
||||
// ... processing
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
```
|
||||
|
||||
## Important Notes
|
||||
|
||||
- **Turbo caching**: Build outputs are cached. Use `--force` to bypass cache
|
||||
- **Environment variables**: Use `NEXT_PUBLIC_` prefix for client-side vars
|
||||
- **Styling**: Tailwind CSS with shadcn/ui components, use `cn()` for conditional classes
|
||||
- **Data fetching**: SWR for client-side, direct Prisma for server components
|
||||
- **Validation**: Zod schemas for form and API validation
|
||||
- **Cache invalidation**: Use `revalidatePath()` after mutations
|
||||
10
README.md
@@ -1,7 +1,11 @@
|
||||
# hackclub.tv
|
||||
|
||||
This is the source code for [hackclub.tv (hctv.srizan.dev)](https://hctv.srizan.dev), a livestreaming website for hackclubbers.
|
||||
This is the source code for [hackclub.tv](https://hackclub.tv), a livestreaming website for Hack Clubbers.
|
||||
|
||||
Development has been ongoing for a few months, and the site is now live! There are some half-baked features, but I'm all ears for feedback.
|
||||
The development setup guide can be read at <https://docs.hackclub.tv/guides/dev/>
|
||||
|
||||
Join [#hctv](https://hackclub.slack.com/archives/C08HGLXGXAB) on the HC Slack for discussion and updates!
|
||||
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,10 +1,13 @@
|
||||
FROM node:lts-alpine AS base
|
||||
ENV PNPM_HOME="/pnpm"
|
||||
ENV PATH="$PNPM_HOME/bin:$PATH"
|
||||
RUN corepack enable
|
||||
|
||||
FROM base AS builder
|
||||
RUN apk update
|
||||
RUN apk add --no-cache libc6-compat
|
||||
WORKDIR /app
|
||||
RUN yarn global add turbo@^2
|
||||
RUN pnpm add -g turbo@^2
|
||||
COPY . .
|
||||
|
||||
RUN turbo prune @hctv/chat --docker
|
||||
@@ -16,10 +19,10 @@ WORKDIR /app
|
||||
|
||||
# First install the dependencies
|
||||
COPY --from=builder /app/out/json/ .
|
||||
RUN yarn install --frozen-lockfile
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
COPY --from=builder /app/out/full/ .
|
||||
RUN --mount=type=secret,id=TURBO_TOKEN --mount=type=secret,id=TURBO_TEAM TURBO_TOKEN=$(cat /run/secrets/TURBO_TOKEN) TURBO_TEAM=$(cat /run/secrets/TURBO_TEAM) yarn turbo run build --concurrency=1
|
||||
RUN --mount=type=secret,id=TURBO_TOKEN --mount=type=secret,id=TURBO_TEAM TURBO_TOKEN=$(cat /run/secrets/TURBO_TOKEN) TURBO_TEAM=$(cat /run/secrets/TURBO_TEAM) pnpm turbo run build --concurrency=1
|
||||
|
||||
FROM base AS runner
|
||||
WORKDIR /app
|
||||
@@ -41,4 +44,4 @@ WORKDIR /app/apps/chat
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
ENTRYPOINT ["node", "dist/index.js"]
|
||||
ENTRYPOINT ["node", "dist/index.js"]
|
||||
|
||||
@@ -7,18 +7,19 @@
|
||||
"build": "tsc --build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hctv/auth": "*",
|
||||
"@hctv/db": "*",
|
||||
"@hctv/hono-ws": "*",
|
||||
"@hono/node-server": "^1.14.0",
|
||||
"@hono/node-ws": "^1.1.0",
|
||||
"@leeoniya/ufuzzy": "^1.0.18",
|
||||
"@hctv/auth": "workspace:*",
|
||||
"@hctv/db": "workspace:*",
|
||||
"@hctv/hono-ws": "workspace:*",
|
||||
"@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"
|
||||
}
|
||||
}
|
||||
|
||||
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.`,
|
||||
});
|
||||
}
|
||||
@@ -2,24 +2,44 @@
|
||||
import { defineConfig } from 'astro/config';
|
||||
import starlight from '@astrojs/starlight';
|
||||
import mermaid from 'astro-mermaid';
|
||||
import catppuccin from "@catppuccin/starlight";
|
||||
import catppuccin from '@catppuccin/starlight';
|
||||
import starlightTypeDoc, { typeDocSidebarGroup } from 'starlight-typedoc';
|
||||
|
||||
// https://astro.build/config
|
||||
export default defineConfig({
|
||||
integrations: [
|
||||
integrations: [
|
||||
mermaid({
|
||||
theme: 'base',
|
||||
autoTheme: true
|
||||
autoTheme: true,
|
||||
}),
|
||||
starlight({
|
||||
title: 'hctv docs',
|
||||
social: [{ icon: 'github', label: 'GitHub', href: 'https://github.com/SrIzan10/hctv' }],
|
||||
starlight({
|
||||
title: 'hctv docs',
|
||||
social: [{ icon: 'github', label: 'GitHub', href: 'https://github.com/SrIzan10/hctv' }],
|
||||
plugins: [
|
||||
catppuccin({
|
||||
dark: { flavor: "mocha", accent: "blue" },
|
||||
light: { flavor: "latte", accent: "blue" }
|
||||
dark: { flavor: 'mocha', accent: 'blue' },
|
||||
light: { flavor: 'latte', accent: 'blue' },
|
||||
}),
|
||||
]
|
||||
}),
|
||||
],
|
||||
starlightTypeDoc({
|
||||
entryPoints: ['../../packages/sdk/src/index.ts'],
|
||||
tsconfig: '../../packages/sdk/tsconfig.json',
|
||||
output: 'typedoc-sdk',
|
||||
sidebar: {
|
||||
label: 'SDK Reference',
|
||||
},
|
||||
}),
|
||||
],
|
||||
sidebar: [
|
||||
{
|
||||
label: 'API',
|
||||
autogenerate: { directory: 'api' },
|
||||
},
|
||||
{
|
||||
label: 'Guides',
|
||||
autogenerate: { directory: 'guides' },
|
||||
},
|
||||
typeDocSidebarGroup,
|
||||
],
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
@@ -10,11 +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.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 |
@@ -9,71 +9,251 @@ The chat system is powered by a websocket server. Please read the entire page be
|
||||
|
||||
## Connection and messages
|
||||
|
||||
The websocket server is located at `wss://hctv.srizan.dev/api/chat/ws/:username`, where `:username` is the channel you want to connect to.
|
||||
The websocket server is located at `wss://hackclub.tv/api/chat/ws/:username`, where `:username` is the channel you want to connect to.
|
||||
|
||||
You'll need to provide authentication, which can be done by providing an `auth_session` cookie, just like the REST API.
|
||||
|
||||
You'll need to provide authentication, which can be done by providing an `auth_session` cookie, just like the REST API.
|
||||
<Aside type="tip">
|
||||
Bot accounts are now supported. You can choose to connect as a bot by providing a bot account's API key on the Authentication header: `Bearer hctvb_xxxxxxx`
|
||||
Bot accounts are now supported. You can choose to connect as a bot by providing a bot account's API key in one of two ways:
|
||||
- Using the `Authorization` header: `Bearer hctvb_xxxxxxx`
|
||||
- Using the `?botAuth=hctvb_xxxxxxx` query parameter
|
||||
|
||||
**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 5 seconds. This is because of Cloudflare limitations.
|
||||
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:
|
||||
- `message`: a chat message.
|
||||
- sent by client:
|
||||
|
||||
- `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",
|
||||
"content": "Hello, world!"
|
||||
"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!",
|
||||
"message": "Hello, world!"
|
||||
}
|
||||
```
|
||||
- `ping`: a ping message to keep the connection alive.
|
||||
- sent by client:
|
||||
```json
|
||||
{
|
||||
"type": "ping"
|
||||
}
|
||||
```
|
||||
- received by client:
|
||||
```json
|
||||
{
|
||||
"type": "ping"
|
||||
}
|
||||
```
|
||||
- `history`: a message containing the chat history. This is sent upon connection.
|
||||
- received by client:
|
||||
|
||||
`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*
|
||||
_diagram source: devin deepwiki_
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "Emoji Processing Pipeline"
|
||||
@@ -110,21 +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",
|
||||
@@ -133,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",
|
||||
|
||||
@@ -9,7 +9,7 @@ since this is beta software, the API is subject to change. additionally, many en
|
||||
|
||||
## Base url
|
||||
|
||||
base url for all endpoints is `https://hctv.srizan.dev/api`.
|
||||
base url for all endpoints is `https://hackclub.tv/api`.
|
||||
|
||||
## Authentication
|
||||
|
||||
|
||||
@@ -3,10 +3,6 @@ title: RTMP
|
||||
description: RTMP related endpoint group
|
||||
---
|
||||
|
||||
## GET `/rtmp/hls/:path`
|
||||
gets HLS segments, the backbone of hctv livestreaming. **authentication required**.
|
||||
not really sure why you would need this? but check the browser console when playing a stream for an insight on how it's used.
|
||||
|
||||
## POST `/rtmp/streamKey`
|
||||
regenerates your stream key. **authentication required**.
|
||||
body parameters (json):
|
||||
|
||||
54
apps/docs/src/content/docs/guides/dev.mdx
Normal file
@@ -0,0 +1,54 @@
|
||||
---
|
||||
title: Development Setup
|
||||
description: Instructions to set up a local development environment for hackclub.tv
|
||||
---
|
||||
|
||||
Follow these steps to run hackclub.tv locally:
|
||||
|
||||
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 linked to you.
|
||||
name: hctv notifier dev
|
||||
features:
|
||||
bot_user:
|
||||
# Same here.
|
||||
display_name: hctv notifier dev
|
||||
always_online: false
|
||||
oauth_config:
|
||||
scopes:
|
||||
bot:
|
||||
- chat:write
|
||||
- users:read
|
||||
- channels:join
|
||||
settings:
|
||||
org_deploy_enabled: false
|
||||
socket_mode_enabled: false
|
||||
token_rotation_enabled: false
|
||||
```
|
||||
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 `rtmp://hackclub.app:45913/live`
|
||||
- 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"]
|
||||
}
|
||||
|
||||
34
apps/web/.env.example
Normal file
@@ -0,0 +1,34 @@
|
||||
DATABASE_URL=postgresql://postgres:skbiditoilet@localhost:5555/postgres
|
||||
|
||||
# make a slack app here: https://api.slack.com/apps
|
||||
SLACK_NOTIFIER_TOKEN=<make a bot for this, check app manifest below>
|
||||
|
||||
# invite your bot to the channel you created. below is #hctv-dev, so use that if you want!
|
||||
NOTIFICATION_CHANNEL_ID=C08M3MGE6PJ
|
||||
|
||||
REDIS_URL=redis://localhost:6379
|
||||
|
||||
# get from https://uploadthing.com/
|
||||
UPLOADTHING_TOKEN=<get from uploadthing>
|
||||
|
||||
# enable oauth mode on your hca account and make an app: https://auth.hackclub.com/identity/edit
|
||||
HCID_CLIENT=<auth.hackclub.com client>
|
||||
HCID_SECRET=<auth.hackclub.com secret>
|
||||
# make sure to put this as one of the redirect uri
|
||||
HCID_REDIRECT_URI=http://localhost:3000/auth/hackclub/callback
|
||||
|
||||
# mediamtx settings
|
||||
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
|
||||
|
||||
# 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
|
||||
|
||||
# generate with `openssl rand -base64 20`
|
||||
MEDIAMTX_PUBLISH_KEY=
|
||||
MEDIAMTX_API_KEY=
|
||||
@@ -1,13 +1,16 @@
|
||||
FROM node:lts-alpine AS base
|
||||
FROM node:22-slim AS base
|
||||
ENV PNPM_HOME="/pnpm"
|
||||
ENV PATH="$PNPM_HOME/bin:$PATH"
|
||||
RUN corepack enable
|
||||
|
||||
FROM base AS builder
|
||||
RUN apk update
|
||||
RUN apk add --no-cache libc6-compat git
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
git \
|
||||
ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
# Replace <your-major-version> with the major version installed in your repository. For example:
|
||||
# RUN yarn global add turbo@^2
|
||||
RUN yarn global add turbo@^2
|
||||
RUN pnpm add -g turbo@^2
|
||||
COPY . .
|
||||
|
||||
# Get the git commit hash before pruning (since .git might be removed)
|
||||
@@ -19,42 +22,76 @@ RUN turbo prune @hctv/web --docker
|
||||
|
||||
# Add lockfile and package.json's of isolated subworkspace
|
||||
FROM base AS installer
|
||||
RUN apk update
|
||||
RUN apk add --no-cache libc6-compat git vips vips-dev python3 make g++
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
git \
|
||||
curl \
|
||||
libvips-dev \
|
||||
python3 \
|
||||
make \
|
||||
g++ \
|
||||
ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
# Get the commit hash from the builder stage
|
||||
COPY --from=builder /tmp/commit_hash /tmp/commit_hash
|
||||
# Read commit hash and set as build arg
|
||||
ARG COMMIT_HASH_FILE=/tmp/commit_hash
|
||||
RUN COMMIT_HASH=$(cat /tmp/commit_hash 2>/dev/null || echo "unknown") && \
|
||||
echo "COMMIT_HASH=$COMMIT_HASH" > /tmp/build_env
|
||||
WORKDIR /app
|
||||
|
||||
# First install the dependencies (as they change less often)
|
||||
COPY --from=builder /app/out/json/ .
|
||||
RUN yarn install --frozen-lockfile
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
RUN cd apps/web && yarn add sharp --platform=linuxmusl --arch=x64
|
||||
# Install a standalone Prisma CLI for runtime migrations (no pnpm symlinks).
|
||||
RUN mkdir -p /opt/prisma-cli && cd /opt/prisma-cli && npm init -y && npm install prisma@6.5.0
|
||||
|
||||
COPY --from=builder /app/out/full/ .
|
||||
RUN --mount=type=secret,id=TURBO_TOKEN --mount=type=secret,id=TURBO_TEAM \
|
||||
. /tmp/build_env && \
|
||||
export commit=$COMMIT_HASH && \
|
||||
TURBO_TOKEN=$(cat /run/secrets/TURBO_TOKEN) TURBO_TEAM=$(cat /run/secrets/TURBO_TEAM) yarn turbo run build --env-mode=loose
|
||||
|
||||
# Generate latest emojis.json during image build.
|
||||
RUN ARCH=$(dpkg --print-architecture) && \
|
||||
if [ "$ARCH" = "amd64" ]; then EMOJI_ARCH="x86_64"; \
|
||||
elif [ "$ARCH" = "arm64" ]; then EMOJI_ARCH="aarch64"; \
|
||||
else EMOJI_ARCH=""; fi && \
|
||||
RELEASE_JSON=$(curl -fsSL https://api.github.com/repos/srizan10/hctv/releases/latest || true) && \
|
||||
RELEASE_URL=$(printf '%s' "$RELEASE_JSON" | grep "browser_download_url.*slack-import-emojis-linux-${EMOJI_ARCH}" | cut -d '"' -f 4 || true) && \
|
||||
if [ -n "$RELEASE_URL" ] && \
|
||||
curl -fsSL -o /tmp/slack-import-emojis-bin "$RELEASE_URL" && \
|
||||
chmod +x /tmp/slack-import-emojis-bin && \
|
||||
/tmp/slack-import-emojis-bin default; then \
|
||||
cp /app/emojis.json /app/apps/web/emojis.json; \
|
||||
else \
|
||||
cp /app/apps/web/src/lib/instrumentation/emojis.json /app/apps/web/emojis.json; \
|
||||
fi
|
||||
|
||||
RUN --mount=type=secret,id=TURBO_TOKEN --mount=type=secret,id=TURBO_TEAM --mount=type=secret,id=SENTRY_AUTH_TOKEN \
|
||||
COMMIT=$(cat /tmp/commit_hash 2>/dev/null || echo "unknown") && \
|
||||
TURBO_TOKEN=$(cat /run/secrets/TURBO_TOKEN) TURBO_TEAM=$(cat /run/secrets/TURBO_TEAM) \
|
||||
SENTRY_AUTH_TOKEN=$(cat /run/secrets/SENTRY_AUTH_TOKEN) \
|
||||
commit=$COMMIT pnpm turbo run build --env-mode=loose
|
||||
|
||||
FROM base AS runner
|
||||
WORKDIR /app
|
||||
|
||||
RUN apk add --no-cache ffmpeg vips vips-dev
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ffmpeg \
|
||||
libvips42 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Don't run production as root
|
||||
RUN addgroup --system --gid 1001 nodejs
|
||||
RUN adduser --system --uid 1001 nextjs
|
||||
RUN groupadd --system --gid 1001 nodejs
|
||||
RUN useradd --system --uid 1001 nextjs --create-home
|
||||
|
||||
# Ensure home directory and cache directories have proper permissions
|
||||
RUN mkdir -p /home/nextjs/.cache && \
|
||||
chown -R nextjs:nodejs /home/nextjs
|
||||
|
||||
# Get the commit hash from the installer stage and create a startup script
|
||||
COPY --from=installer /tmp/commit_hash /tmp/commit_hash
|
||||
RUN COMMIT_VALUE=$(cat /tmp/commit_hash 2>/dev/null || echo "unknown") && \
|
||||
echo "#!/bin/sh" > /usr/local/bin/start.sh && \
|
||||
echo "set -e" >> /usr/local/bin/start.sh && \
|
||||
echo "export COREPACK_ENABLE_DOWNLOAD_PROMPT=0" >> /usr/local/bin/start.sh && \
|
||||
echo "export HOME=/home/nextjs" >> /usr/local/bin/start.sh && \
|
||||
echo "echo 'Running database migrations...'" >> /usr/local/bin/start.sh && \
|
||||
echo "node /opt/prisma-cli/node_modules/prisma/build/index.js migrate deploy --schema /app/packages/db/prisma/schema.prisma" >> /usr/local/bin/start.sh && \
|
||||
echo "cd /app" >> /usr/local/bin/start.sh && \
|
||||
echo "export commit=$COMMIT_VALUE" >> /usr/local/bin/start.sh && \
|
||||
echo "echo 'Starting Next.js application...'" >> /usr/local/bin/start.sh && \
|
||||
echo "exec node apps/web/server.js" >> /usr/local/bin/start.sh && \
|
||||
chmod +x /usr/local/bin/start.sh
|
||||
|
||||
@@ -65,6 +102,10 @@ USER nextjs
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/apps/web/.next/standalone ./
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/apps/web/.next/static ./apps/web/.next/static
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/apps/web/public ./apps/web/public
|
||||
COPY --chown=nextjs:nodejs apps/web/emojis.json .
|
||||
|
||||
CMD ["/usr/local/bin/start.sh"]
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/apps/web/emojis.json ./emojis.json
|
||||
|
||||
# Copy Prisma schema and migrations for prisma migrate deploy
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/packages/db/prisma ./packages/db/prisma
|
||||
COPY --from=installer --chown=nextjs:nodejs /opt/prisma-cli /opt/prisma-cli
|
||||
|
||||
CMD ["/usr/local/bin/start.sh"]
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
@@ -56,6 +59,9 @@ const nextConfig = {
|
||||
},
|
||||
];
|
||||
},
|
||||
logging: {
|
||||
incomingRequests: false,
|
||||
},
|
||||
};
|
||||
|
||||
export default withSentryConfig(nextConfig, {
|
||||
@@ -66,6 +72,9 @@ export default withSentryConfig(nextConfig, {
|
||||
|
||||
project: "hctv",
|
||||
|
||||
// Auth token for uploading source maps
|
||||
authToken: process.env.SENTRY_AUTH_TOKEN,
|
||||
|
||||
// Only print logs for uploading source maps in CI
|
||||
silent: !process.env.CI,
|
||||
|
||||
@@ -75,6 +84,9 @@ export default withSentryConfig(nextConfig, {
|
||||
// Upload a larger set of source maps for prettier stack traces (increases build time)
|
||||
widenClientFileUpload: true,
|
||||
|
||||
// Hides source maps from generated client bundles
|
||||
hideSourceMaps: true,
|
||||
|
||||
// Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers.
|
||||
// This can increase your server load as well as your hosting bill.
|
||||
// Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client-
|
||||
|
||||
@@ -1,92 +1,99 @@
|
||||
{
|
||||
"name": "@hctv/web",
|
||||
"version": "0.3.0",
|
||||
"version": "0.5.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dd": "docker compose --file ../../dev/docker-compose.yml up -d",
|
||||
"dev": "next dev --turbo",
|
||||
"dev": "next dev --turbo -H 0.0.0.0",
|
||||
"donly": "docker compose --file ../../dev/docker-compose.yml up",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"ui:add": "shadcn add",
|
||||
"check-types": "tsc --noEmit",
|
||||
"openapi": "next-openapi-gen"
|
||||
"genMtxTypes": "bunx openapi-typescript https://github.com/bluenviron/mediamtx/raw/refs/tags/v1.15.5/api/openapi.yaml -o ./src/lib/types/mediamtx.d.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hctv/auth": "*",
|
||||
"@hctv/db": "*",
|
||||
"@hookform/resolvers": "^3.9.1",
|
||||
"@hctv/auth": "workspace:*",
|
||||
"@hctv/db": "workspace:*",
|
||||
"@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",
|
||||
"@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-slot": "^1.1.1",
|
||||
"@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",
|
||||
"@omit/react-confirm-dialog": "^2.0.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.15",
|
||||
"@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.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",
|
||||
"hls-video-element": "^1.5.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.11",
|
||||
"hls.js": "^1.6.16",
|
||||
"lucia": "^3.2.2",
|
||||
"lucide-react": "^0.473.0",
|
||||
"media-chrome": "^4.8.0",
|
||||
"next": "^15.6.0-canary.34",
|
||||
"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",
|
||||
"react-dom": "19",
|
||||
"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,16 +1,49 @@
|
||||
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: { channel: true },
|
||||
include: {
|
||||
channel: {
|
||||
include: {
|
||||
restriction: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!streamInfo) {
|
||||
return <div>Stream not found</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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
1587
apps/web/src/app/(ui)/(protected)/admin/page.client.tsx
Normal file
17
apps/web/src/app/(ui)/(protected)/admin/page.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { redirect } from 'next/navigation';
|
||||
import AdminPanelClient from './page.client';
|
||||
|
||||
export default async function AdminPage() {
|
||||
const { user } = await validateRequest();
|
||||
|
||||
if (!user) {
|
||||
redirect('/auth/hackclub');
|
||||
}
|
||||
|
||||
if (!user.isAdmin) {
|
||||
redirect('/');
|
||||
}
|
||||
|
||||
return <AdminPanelClient currentUser={user} />;
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { format, formatDistanceToNow } from 'date-fns';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
ArrowLeft,
|
||||
Gavel,
|
||||
Flag,
|
||||
User,
|
||||
MessageSquare,
|
||||
Clock,
|
||||
ShieldAlert,
|
||||
ShieldOff,
|
||||
ShieldCheck,
|
||||
Trash2,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
AlertTriangle,
|
||||
Timer,
|
||||
Ban,
|
||||
Unlock,
|
||||
Info,
|
||||
} from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
type ReportModerationAction =
|
||||
| 'review'
|
||||
| 'dismiss'
|
||||
| 'delete_reported_message'
|
||||
| 'timeout_10m'
|
||||
| 'timeout_1h'
|
||||
| 'ban_chat'
|
||||
| 'lift_chat_ban'
|
||||
| 'ban_platform'
|
||||
| 'unban_platform';
|
||||
|
||||
type ActionSeverity = 'info' | 'moderate' | 'severe';
|
||||
|
||||
interface ActionOption {
|
||||
value: ReportModerationAction;
|
||||
label: string;
|
||||
description: string;
|
||||
severity: ActionSeverity;
|
||||
requiresNote?: boolean;
|
||||
icon: React.ReactNode;
|
||||
}
|
||||
|
||||
const ACTION_OPTIONS: ActionOption[] = [
|
||||
{
|
||||
value: 'review',
|
||||
label: 'Mark as reviewed',
|
||||
description: 'Acknowledge the report without further action.',
|
||||
severity: 'info',
|
||||
icon: <CheckCircle2 className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'dismiss',
|
||||
label: 'Dismiss',
|
||||
description: 'Close this report as unfounded or resolved.',
|
||||
severity: 'info',
|
||||
icon: <XCircle className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'delete_reported_message',
|
||||
label: 'Delete message',
|
||||
description: 'Remove the reported message from the chat.',
|
||||
severity: 'moderate',
|
||||
requiresNote: true,
|
||||
icon: <Trash2 className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'timeout_10m',
|
||||
label: 'Timeout 10 minutes',
|
||||
description: 'Prevent user from chatting for 10 minutes.',
|
||||
severity: 'moderate',
|
||||
requiresNote: true,
|
||||
icon: <Timer className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'timeout_1h',
|
||||
label: 'Timeout 1 hour',
|
||||
description: 'Prevent user from chatting for 1 hour.',
|
||||
severity: 'moderate',
|
||||
requiresNote: true,
|
||||
icon: <Timer className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'ban_chat',
|
||||
label: 'Ban from chat',
|
||||
description: 'Permanently ban user from chat.',
|
||||
severity: 'severe',
|
||||
requiresNote: true,
|
||||
icon: <Ban className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'lift_chat_ban',
|
||||
label: 'Lift chat ban',
|
||||
description: 'Restore chat access for this user.',
|
||||
severity: 'info',
|
||||
requiresNote: true,
|
||||
icon: <Unlock className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'ban_platform',
|
||||
label: 'Ban from platform',
|
||||
description: 'Permanently ban user from the entire platform.',
|
||||
severity: 'severe',
|
||||
requiresNote: true,
|
||||
icon: <ShieldOff className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'unban_platform',
|
||||
label: 'Unban from platform',
|
||||
description: 'Restore platform access for this user.',
|
||||
severity: 'info',
|
||||
requiresNote: true,
|
||||
icon: <ShieldCheck className="h-4 w-4" />,
|
||||
},
|
||||
];
|
||||
|
||||
const SEVERITY_STYLES: Record<
|
||||
ActionSeverity,
|
||||
{ card: string; selected: string; icon: string; ring: string }
|
||||
> = {
|
||||
info: {
|
||||
card: 'border-border hover:border-muted-foreground/40 hover:bg-muted/30',
|
||||
selected: 'border-primary bg-primary/5',
|
||||
icon: 'text-muted-foreground',
|
||||
ring: 'ring-primary/30',
|
||||
},
|
||||
moderate: {
|
||||
card: 'border-border hover:border-amber-500/40 hover:bg-amber-500/5',
|
||||
selected: 'border-amber-500 bg-amber-500/5',
|
||||
icon: 'text-amber-500',
|
||||
ring: 'ring-amber-500/30',
|
||||
},
|
||||
severe: {
|
||||
card: 'border-border hover:border-destructive/40 hover:bg-destructive/5',
|
||||
selected: 'border-destructive bg-destructive/5',
|
||||
icon: 'text-destructive',
|
||||
ring: 'ring-destructive/30',
|
||||
},
|
||||
};
|
||||
|
||||
const STATUS_CONFIG = {
|
||||
OPEN: { label: 'Open', variant: 'destructive' as const, icon: <Flag className="h-3 w-3" /> },
|
||||
REVIEWED: {
|
||||
label: 'Reviewed',
|
||||
variant: 'secondary' as const,
|
||||
icon: <CheckCircle2 className="h-3 w-3" />,
|
||||
},
|
||||
DISMISSED: {
|
||||
label: 'Dismissed',
|
||||
variant: 'outline' as const,
|
||||
icon: <XCircle className="h-3 w-3" />,
|
||||
},
|
||||
};
|
||||
|
||||
const ACTION_LABELS: Record<NonNullable<ChatReportCase['lastAction']>, string> = {
|
||||
REVIEW: 'Marked as reviewed',
|
||||
DISMISS: 'Dismissed',
|
||||
DELETE_REPORTED_MESSAGE: 'Message deleted',
|
||||
TIMEOUT_10M: 'User timed out (10m)',
|
||||
TIMEOUT_1H: 'User timed out (1h)',
|
||||
BAN_CHAT: 'Chat banned',
|
||||
LIFT_CHAT_BAN: 'Chat ban lifted',
|
||||
BAN_PLATFORM: 'Platform banned',
|
||||
UNBAN_PLATFORM: 'Platform ban lifted',
|
||||
};
|
||||
|
||||
function InfoRow({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{label}
|
||||
</span>
|
||||
<span className="text-sm">{children}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SectionLabel({ icon, children }: { icon: React.ReactNode; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<span className="text-muted-foreground">{icon}</span>
|
||||
<span className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
|
||||
{children}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ReportCasePageClient({ report }: ReportCasePageClientProps) {
|
||||
const router = useRouter();
|
||||
const [selectedAction, setSelectedAction] = useState<ReportModerationAction>('review');
|
||||
const [note, setNote] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const selectedMeta = ACTION_OPTIONS.find((o) => o.value === selectedAction)!;
|
||||
const requiresNote = Boolean(selectedMeta?.requiresNote);
|
||||
const isSevere = selectedMeta?.severity === 'severe';
|
||||
|
||||
const statusConfig = STATUS_CONFIG[report.status];
|
||||
|
||||
const submitAction = async () => {
|
||||
if (requiresNote && note.trim().length < 10) {
|
||||
toast.error('Please include at least 10 characters for enforcement context.');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const res = await fetch('/api/admin/reports', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
reportId: report.id,
|
||||
action: selectedAction,
|
||||
note: note.trim() || undefined,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
toast.error(errorText || 'Failed to apply action');
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success('Report action applied');
|
||||
setNote('');
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast.error('Failed to apply action');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const actionGroups: Array<{ label: string; actions: ActionOption[] }> = [
|
||||
{
|
||||
label: 'Informational',
|
||||
actions: ACTION_OPTIONS.filter((a) => a.severity === 'info'),
|
||||
},
|
||||
{
|
||||
label: 'Moderation',
|
||||
actions: ACTION_OPTIONS.filter((a) => a.severity === 'moderate'),
|
||||
},
|
||||
{
|
||||
label: 'Severe',
|
||||
actions: ACTION_OPTIONS.filter((a) => a.severity === 'severe'),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="container max-w-5xl mx-auto py-8 px-4">
|
||||
<div className="flex items-start justify-between gap-4 mb-8">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Report Case</h1>
|
||||
<Badge
|
||||
variant={statusConfig.variant}
|
||||
className="flex items-center gap-1.5 text-xs px-2 py-0.5"
|
||||
>
|
||||
{statusConfig.icon}
|
||||
{statusConfig.label}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground font-mono">{report.id}</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => router.push(`/admin?tab=reports&reportId=${report.id}`)}
|
||||
className="shrink-0 gap-1.5"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Back to reports
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-5 gap-6">
|
||||
<div className="md:col-span-3 space-y-5">
|
||||
{report.reportedMessage ? (
|
||||
<div className="rounded-lg border border-border bg-muted/20 overflow-hidden">
|
||||
<div className="px-4 py-3 border-b border-border bg-muted/30 flex items-center gap-2">
|
||||
<MessageSquare className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||
Reported message
|
||||
</span>
|
||||
</div>
|
||||
<div className="px-4 py-4">
|
||||
<p className="text-sm leading-relaxed break-words">{report.reportedMessage}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border border-dashed border-border px-4 py-5 flex items-center gap-3 text-muted-foreground">
|
||||
<Info className="h-4 w-4 shrink-0" />
|
||||
<span className="text-sm">No message content was captured with this report.</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-lg border border-border overflow-hidden">
|
||||
<div className="px-4 py-3 border-b border-border bg-muted/20">
|
||||
<SectionLabel icon={<User className="h-3.5 w-3.5" />}>Parties</SectionLabel>
|
||||
</div>
|
||||
<div className="px-4 py-4 grid grid-cols-2 gap-x-6 gap-y-4">
|
||||
<InfoRow label="Reporter">
|
||||
<span className="font-medium">{report.reporter}</span>
|
||||
</InfoRow>
|
||||
<InfoRow label="Target">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<span className="font-medium">{report.target}</span>
|
||||
{report.targetIsAdmin && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] py-0 px-1.5 text-amber-500 border-amber-500/40"
|
||||
>
|
||||
Admin
|
||||
</Badge>
|
||||
)}
|
||||
{report.targetIsPlatformBanned && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] py-0 px-1.5 text-destructive border-destructive/40"
|
||||
>
|
||||
Platform banned
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</InfoRow>
|
||||
<InfoRow label="Channel">
|
||||
<span className="font-mono text-xs bg-muted px-1.5 py-0.5 rounded">
|
||||
{report.channelName}
|
||||
</span>
|
||||
</InfoRow>
|
||||
<InfoRow label="Reason">
|
||||
<span>{report.reason}</span>
|
||||
</InfoRow>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-border overflow-hidden">
|
||||
<div className="px-4 py-3 border-b border-border bg-muted/20">
|
||||
<SectionLabel icon={<Clock className="h-3.5 w-3.5" />}>Timeline</SectionLabel>
|
||||
</div>
|
||||
<div className="px-4 py-4 space-y-4">
|
||||
<InfoRow label="Filed">
|
||||
<span>
|
||||
{format(new Date(report.createdAt), 'PPP p')}{' '}
|
||||
<span className="text-muted-foreground text-xs">
|
||||
({formatDistanceToNow(new Date(report.createdAt), { addSuffix: true })})
|
||||
</span>
|
||||
</span>
|
||||
</InfoRow>
|
||||
{report.handledAt ? (
|
||||
<InfoRow label="Last handled">
|
||||
<span>
|
||||
{format(new Date(report.handledAt), 'PPP p')}{' '}
|
||||
<span className="text-muted-foreground text-xs">
|
||||
({formatDistanceToNow(new Date(report.handledAt), { addSuffix: true })})
|
||||
</span>
|
||||
</span>
|
||||
</InfoRow>
|
||||
) : null}
|
||||
<InfoRow label="Last action">
|
||||
{report.lastAction ? (
|
||||
<span className="font-medium">{ACTION_LABELS[report.lastAction]}</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">None</span>
|
||||
)}
|
||||
</InfoRow>
|
||||
<InfoRow label="Handled by">
|
||||
{report.handledBy ? (
|
||||
<span className="font-medium">{report.handledBy}</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">—</span>
|
||||
)}
|
||||
</InfoRow>
|
||||
{report.handlingNote ? (
|
||||
<div className="pt-1">
|
||||
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground block mb-1.5">
|
||||
Last note
|
||||
</span>
|
||||
<p className="text-sm bg-muted/40 rounded-md px-3 py-2.5 leading-relaxed border border-border">
|
||||
{report.handlingNote}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{report.targetIsAdmin && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3">
|
||||
<AlertTriangle className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
|
||||
<div className="text-sm text-amber-700 dark:text-amber-400 leading-snug">
|
||||
<span className="font-semibold">Caution:</span> The reported user is a platform
|
||||
admin. Enforcement actions will still apply.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="md:col-span-2">
|
||||
<div className="rounded-lg border border-border overflow-hidden sticky top-6">
|
||||
<div className="px-4 py-3 border-b border-border bg-muted/20 flex items-center gap-2">
|
||||
<Gavel className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||
Enforcement
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="px-4 py-4 space-y-5">
|
||||
{/* Action selector */}
|
||||
<div className="space-y-3">
|
||||
{actionGroups.map((group) => (
|
||||
<div key={group.label}>
|
||||
<p className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground mb-2">
|
||||
{group.label}
|
||||
</p>
|
||||
<div className="space-y-1.5">
|
||||
{group.actions.map((action) => {
|
||||
const isSelected = selectedAction === action.value;
|
||||
const styles = SEVERITY_STYLES[action.severity];
|
||||
return (
|
||||
<button
|
||||
key={action.value}
|
||||
type="button"
|
||||
onClick={() => setSelectedAction(action.value)}
|
||||
className={cn(
|
||||
'w-full flex items-start gap-3 rounded-md border px-3 py-2.5 text-left transition-all cursor-pointer',
|
||||
isSelected ? `${styles.selected} ring-1 ${styles.ring}` : styles.card
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'mt-0.5 shrink-0',
|
||||
isSelected ? styles.icon : 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{action.icon}
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<p
|
||||
className={cn(
|
||||
'text-sm font-medium leading-tight',
|
||||
isSelected && action.severity === 'severe' && 'text-destructive',
|
||||
isSelected &&
|
||||
action.severity === 'moderate' &&
|
||||
'text-amber-600 dark:text-amber-400'
|
||||
)}
|
||||
>
|
||||
{action.label}
|
||||
</p>
|
||||
<p className="text-[11px] text-muted-foreground mt-0.5 leading-snug">
|
||||
{action.description}
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="note" className="text-xs">
|
||||
Moderator note
|
||||
{requiresNote ? (
|
||||
<span className="text-destructive ml-1">*</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground ml-1">(optional)</span>
|
||||
)}
|
||||
</Label>
|
||||
<Textarea
|
||||
id="note"
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
placeholder="Explain why this action is being taken."
|
||||
rows={3}
|
||||
className="text-sm resize-none"
|
||||
/>
|
||||
{requiresNote && (
|
||||
<p className="text-[11px] text-muted-foreground">Min. 10 characters required.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isSevere && (
|
||||
<div className="flex items-start gap-2.5 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2.5">
|
||||
<ShieldAlert className="h-4 w-4 text-destructive shrink-0 mt-0.5" />
|
||||
<p className="text-[12px] text-destructive leading-snug">
|
||||
This is a severe action may often not be easily undone. Double-check before
|
||||
applying.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
onClick={submitAction}
|
||||
disabled={isSubmitting}
|
||||
variant={isSevere ? 'destructive' : 'default'}
|
||||
className="w-full gap-2"
|
||||
size="sm"
|
||||
>
|
||||
<Gavel className="h-3.5 w-3.5" />
|
||||
{isSubmitting ? 'Applying…' : 'Apply action'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Types ───────────────────────────────────────────────────────────────────
|
||||
|
||||
interface ReportCasePageClientProps {
|
||||
report: ChatReportCase;
|
||||
}
|
||||
|
||||
interface ChatReportCase {
|
||||
id: string;
|
||||
status: 'OPEN' | 'REVIEWED' | 'DISMISSED';
|
||||
reason: string;
|
||||
reportedMessage: string | null;
|
||||
reportedMessageId: string | null;
|
||||
targetUsername: string | null;
|
||||
channelName: string;
|
||||
createdAt: string;
|
||||
handledAt: string | null;
|
||||
handlingNote: string | null;
|
||||
lastAction:
|
||||
| 'REVIEW'
|
||||
| 'DISMISS'
|
||||
| 'DELETE_REPORTED_MESSAGE'
|
||||
| 'TIMEOUT_10M'
|
||||
| 'TIMEOUT_1H'
|
||||
| 'BAN_CHAT'
|
||||
| 'LIFT_CHAT_BAN'
|
||||
| 'BAN_PLATFORM'
|
||||
| 'UNBAN_PLATFORM'
|
||||
| null;
|
||||
reporter: string;
|
||||
target: string;
|
||||
targetUserId: string | null;
|
||||
targetIsAdmin: boolean;
|
||||
targetIsPlatformBanned: boolean;
|
||||
handledBy: string | null;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { notFound, redirect } from 'next/navigation';
|
||||
import ReportCasePageClient from './page.client';
|
||||
|
||||
export default async function ReportCasePage({ params }: ReportCasePageProps) {
|
||||
const { reportId } = await params;
|
||||
const { user } = await validateRequest();
|
||||
|
||||
if (!user) {
|
||||
redirect('/auth/hackclub');
|
||||
}
|
||||
|
||||
if (!user.isAdmin) {
|
||||
redirect('/');
|
||||
}
|
||||
|
||||
const report = await prisma.chatUserReport.findUnique({
|
||||
where: {
|
||||
id: reportId,
|
||||
},
|
||||
include: {
|
||||
channel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
reporter: {
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
targetUser: {
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
ban: true,
|
||||
},
|
||||
},
|
||||
handledBy: {
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!report) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return (
|
||||
<ReportCasePageClient
|
||||
report={{
|
||||
id: report.id,
|
||||
status: report.status,
|
||||
reason: report.reason,
|
||||
reportedMessage: report.reportedMessage,
|
||||
reportedMessageId: report.reportedMessageId,
|
||||
targetUsername: report.targetUsername,
|
||||
channelName: report.channel.name,
|
||||
createdAt: report.createdAt.toISOString(),
|
||||
handledAt: report.handledAt?.toISOString() ?? null,
|
||||
handlingNote: report.handlingNote,
|
||||
lastAction: report.lastAction,
|
||||
reporter: report.reporter.personalChannel?.name ?? report.reporter.slack_id,
|
||||
target:
|
||||
report.targetUser?.personalChannel?.name ??
|
||||
report.targetUsername ??
|
||||
report.targetUserId ??
|
||||
'unknown',
|
||||
targetUserId: report.targetUserId,
|
||||
targetIsAdmin: Boolean(report.targetUser?.isAdmin),
|
||||
targetIsPlatformBanned: Boolean(report.targetUser?.ban),
|
||||
handledBy: report.handledBy?.personalChannel?.name ?? report.handledBy?.slack_id ?? null,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface ReportCasePageProps {
|
||||
params: Promise<{
|
||||
reportId: string;
|
||||
}>;
|
||||
}
|
||||
189
apps/web/src/app/(ui)/(protected)/api/admin/audit/route.ts
Normal file
@@ -0,0 +1,189 @@
|
||||
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) {
|
||||
return new Response('Forbidden', { status: 403 });
|
||||
}
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const take = Math.min(Math.max(Number(searchParams.get('take') ?? 100), 10), 250);
|
||||
|
||||
const [adminLogs, chatLogs] = await Promise.all([
|
||||
prisma.adminAuditLog.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take,
|
||||
include: {
|
||||
actor: {
|
||||
select: {
|
||||
id: true,
|
||||
isAdmin: true,
|
||||
slack_id: true,
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.chatModerationEvent.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take,
|
||||
include: {
|
||||
channel: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
moderator: {
|
||||
select: {
|
||||
id: true,
|
||||
isAdmin: true,
|
||||
slack_id: true,
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
targetUser: {
|
||||
select: {
|
||||
id: true,
|
||||
isAdmin: true,
|
||||
slack_id: true,
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const targetUserIds = [
|
||||
...new Set(adminLogs.map((log) => log.targetUserId).filter(Boolean)),
|
||||
] as string[];
|
||||
const targetUsers =
|
||||
targetUserIds.length > 0
|
||||
? await prisma.user.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: targetUserIds,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
: [];
|
||||
const targetUserMap = new Map(
|
||||
targetUsers.map((targetUser) => [
|
||||
targetUser.id,
|
||||
targetUser.personalChannel?.name ?? targetUser.slack_id,
|
||||
])
|
||||
);
|
||||
const targetUserAdminMap = new Map(
|
||||
targetUsers.map((targetUser) => [targetUser.id, targetUser.isAdmin])
|
||||
);
|
||||
|
||||
const actorIds = [
|
||||
...new Set([
|
||||
...adminLogs.map((log) => log.actorId),
|
||||
...chatLogs.map((log) => log.moderatorId),
|
||||
...chatLogs.map((log) => log.targetUserId).filter(Boolean),
|
||||
...targetUserIds,
|
||||
]),
|
||||
] as string[];
|
||||
|
||||
const modRoleUsers =
|
||||
actorIds.length > 0
|
||||
? await prisma.user.findMany({
|
||||
where: {
|
||||
id: { in: actorIds },
|
||||
OR: [
|
||||
{ ownedChannels: { some: {} } },
|
||||
{ managedChannels: { some: {} } },
|
||||
{ chatModeratedChannels: { some: {} } },
|
||||
],
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
})
|
||||
: [];
|
||||
const channelModSet = new Set(modRoleUsers.map((user) => user.id));
|
||||
|
||||
const normalizedAdminLogs = adminLogs.map((log) => ({
|
||||
id: log.id,
|
||||
source: 'platform' as const,
|
||||
action: log.action,
|
||||
createdAt: log.createdAt,
|
||||
actor: log.actor.personalChannel?.name ?? log.actor.slack_id,
|
||||
target:
|
||||
log.targetChannel ??
|
||||
(log.targetUserId ? (targetUserMap.get(log.targetUserId) ?? log.targetUserId) : null),
|
||||
reason: log.reason,
|
||||
details: log.details,
|
||||
deletedMessageContent: getDeletedMessageContent(log.details),
|
||||
actorMeta: {
|
||||
isPlatformAdmin: log.actor.isAdmin,
|
||||
isChannelModerator: channelModSet.has(log.actorId),
|
||||
},
|
||||
targetMeta: log.targetUserId
|
||||
? {
|
||||
isPlatformAdmin: Boolean(targetUserAdminMap.get(log.targetUserId)),
|
||||
isChannelModerator: channelModSet.has(log.targetUserId),
|
||||
}
|
||||
: null,
|
||||
}));
|
||||
|
||||
const normalizedChatLogs = chatLogs.map((log) => ({
|
||||
id: log.id,
|
||||
source: 'chat' as const,
|
||||
action: log.action,
|
||||
createdAt: log.createdAt,
|
||||
actor: log.moderator.personalChannel?.name ?? log.moderator.slack_id,
|
||||
target: log.targetUser?.personalChannel?.name ?? log.channel.name,
|
||||
reason: log.reason,
|
||||
details: log.details,
|
||||
deletedMessageContent: getDeletedMessageContent(log.details),
|
||||
channelName: log.channel.name,
|
||||
actorMeta: {
|
||||
isPlatformAdmin: log.moderator.isAdmin,
|
||||
isChannelModerator: true,
|
||||
},
|
||||
targetMeta: log.targetUser
|
||||
? {
|
||||
isPlatformAdmin: log.targetUser.isAdmin,
|
||||
isChannelModerator: channelModSet.has(log.targetUser.id),
|
||||
}
|
||||
: null,
|
||||
}));
|
||||
|
||||
const logs = [...normalizedAdminLogs, ...normalizedChatLogs]
|
||||
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
|
||||
.slice(0, take);
|
||||
|
||||
return Response.json(logs);
|
||||
}
|
||||
142
apps/web/src/app/(ui)/(protected)/api/admin/channels/route.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { AdminAuditAction, prisma } from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user?.isAdmin) {
|
||||
return new Response('Forbidden', { status: 403 });
|
||||
}
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const search = searchParams.get('search') || '';
|
||||
|
||||
const channels = await prisma.channel.findMany({
|
||||
where: search
|
||||
? {
|
||||
OR: [
|
||||
{ name: { contains: search, mode: 'insensitive' } },
|
||||
{ description: { contains: search, mode: 'insensitive' } },
|
||||
],
|
||||
}
|
||||
: undefined,
|
||||
include: {
|
||||
restriction: true,
|
||||
owner: {
|
||||
select: {
|
||||
id: true,
|
||||
slack_id: true,
|
||||
pfpUrl: true,
|
||||
personalChannel: { select: { name: true } },
|
||||
},
|
||||
},
|
||||
personalFor: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
take: 50,
|
||||
});
|
||||
return Response.json(channels);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user?.isAdmin) {
|
||||
return new Response('Forbidden', { status: 403 });
|
||||
}
|
||||
|
||||
let body: {
|
||||
channelId: string;
|
||||
action: 'restrict' | 'unrestrict';
|
||||
reason?: string;
|
||||
expiresAt?: string;
|
||||
};
|
||||
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return new Response('Invalid JSON body', { status: 400 });
|
||||
}
|
||||
|
||||
const { channelId, action, reason, expiresAt } = body;
|
||||
|
||||
if (!channelId || !action) {
|
||||
return new Response('Missing required fields', { status: 400 });
|
||||
}
|
||||
|
||||
let expiresAtDate: Date | null = null;
|
||||
if (expiresAt !== undefined && expiresAt !== null && expiresAt !== '') {
|
||||
expiresAtDate = new Date(expiresAt);
|
||||
if (isNaN(expiresAtDate.getTime())) {
|
||||
return new Response('Invalid expiresAt date', { status: 400 });
|
||||
}
|
||||
if (expiresAtDate <= new Date()) {
|
||||
return new Response('expiresAt must be a future date', { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({ where: { id: channelId } });
|
||||
if (!channel) {
|
||||
return new Response('Channel not found', { status: 404 });
|
||||
}
|
||||
|
||||
if (action === 'restrict') {
|
||||
if (!reason) {
|
||||
return new Response('Reason is required for restricting', { status: 400 });
|
||||
}
|
||||
|
||||
await prisma.channelRestriction.upsert({
|
||||
where: { channelId },
|
||||
update: {
|
||||
reason,
|
||||
restrictedBy: user.id,
|
||||
expiresAt: expiresAtDate,
|
||||
},
|
||||
create: {
|
||||
channelId,
|
||||
reason,
|
||||
restrictedBy: user.id,
|
||||
expiresAt: expiresAtDate,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.CHANNEL_RESTRICTED,
|
||||
actorId: user.id,
|
||||
targetChannel: channel.name,
|
||||
reason,
|
||||
details: {
|
||||
channelId,
|
||||
expiresAt: expiresAtDate?.toISOString() ?? null,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({ success: true, message: 'Channel restricted' });
|
||||
}
|
||||
|
||||
if (action === 'unrestrict') {
|
||||
const deleted = await prisma.channelRestriction.deleteMany({ where: { channelId } });
|
||||
if (deleted.count === 0) {
|
||||
return new Response('Channel does not have an active restriction', { status: 400 });
|
||||
}
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.CHANNEL_UNRESTRICTED,
|
||||
actorId: user.id,
|
||||
targetChannel: channel.name,
|
||||
details: {
|
||||
channelId,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({ success: true, message: 'Channel unrestricted' });
|
||||
}
|
||||
|
||||
return new Response('Invalid action', { status: 400 });
|
||||
}
|
||||
531
apps/web/src/app/(ui)/(protected)/api/admin/reports/route.ts
Normal file
@@ -0,0 +1,531 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import {
|
||||
AdminAuditAction,
|
||||
ChatModerationAction,
|
||||
ChatReportAction,
|
||||
ChatReportStatus,
|
||||
getRedisConnection,
|
||||
prisma,
|
||||
} from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
const redis = getRedisConnection();
|
||||
const REPORT_ALREADY_HANDLED_ERROR = 'REPORT_ALREADY_HANDLED';
|
||||
const NO_ACTIVE_CHAT_BAN_ERROR = 'NO_ACTIVE_CHAT_BAN';
|
||||
const NO_ACTIVE_PLATFORM_BAN_ERROR = 'NO_ACTIVE_PLATFORM_BAN';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user?.isAdmin) {
|
||||
return new Response('Forbidden', { status: 403 });
|
||||
}
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const take = Math.min(Math.max(Number(searchParams.get('take') ?? 100), 10), 250);
|
||||
const reportId = searchParams.get('reportId')?.trim();
|
||||
|
||||
const reports = await prisma.chatUserReport.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take,
|
||||
include: {
|
||||
channel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
reporter: {
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
targetUser: {
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
handledBy: {
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const normalizedReports = reports.map((report) => ({
|
||||
id: report.id,
|
||||
status: report.status,
|
||||
reason: report.reason,
|
||||
reportedMessage: report.reportedMessage,
|
||||
reportedMessageId: report.reportedMessageId,
|
||||
targetUsername: report.targetUsername,
|
||||
channelName: report.channel.name,
|
||||
createdAt: report.createdAt,
|
||||
handledAt: report.handledAt,
|
||||
handlingNote: report.handlingNote,
|
||||
lastAction: report.lastAction,
|
||||
reporter: report.reporter.personalChannel?.name ?? report.reporter.slack_id,
|
||||
handledBy: report.handledBy?.personalChannel?.name ?? report.handledBy?.slack_id ?? null,
|
||||
target:
|
||||
report.targetUser?.personalChannel?.name ??
|
||||
report.targetUsername ??
|
||||
report.targetUserId ??
|
||||
'unknown',
|
||||
}));
|
||||
|
||||
return Response.json({
|
||||
reports: normalizedReports,
|
||||
reportId,
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user?.isAdmin) {
|
||||
return new Response('Forbidden', { status: 403 });
|
||||
}
|
||||
|
||||
let body: {
|
||||
reportId?: string;
|
||||
action?:
|
||||
| 'review'
|
||||
| 'dismiss'
|
||||
| 'delete_reported_message'
|
||||
| 'timeout_10m'
|
||||
| 'timeout_1h'
|
||||
| 'ban_chat'
|
||||
| 'lift_chat_ban'
|
||||
| 'ban_platform'
|
||||
| 'unban_platform';
|
||||
note?: string;
|
||||
};
|
||||
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return new Response('Invalid JSON body', { status: 400 });
|
||||
}
|
||||
|
||||
const reportId = body.reportId?.trim();
|
||||
const action = body.action;
|
||||
const note = body.note?.trim() || null;
|
||||
|
||||
if (!reportId || !action) {
|
||||
return new Response('Missing required fields', { status: 400 });
|
||||
}
|
||||
|
||||
const report = await prisma.chatUserReport.findUnique({
|
||||
where: { id: reportId },
|
||||
include: {
|
||||
channel: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
targetUser: {
|
||||
select: {
|
||||
id: true,
|
||||
isAdmin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!report) {
|
||||
return new Response('Report not found', { status: 404 });
|
||||
}
|
||||
|
||||
const targetUserId = report.targetUserId ?? report.targetUser?.id ?? null;
|
||||
const isTargetAdmin = Boolean(report.targetUser?.isAdmin);
|
||||
|
||||
if (
|
||||
(action === 'ban_platform' ||
|
||||
action === 'ban_chat' ||
|
||||
action === 'timeout_10m' ||
|
||||
action === 'timeout_1h') &&
|
||||
isTargetAdmin
|
||||
) {
|
||||
return new Response('Cannot enforce this action on an admin user', { status: 400 });
|
||||
}
|
||||
|
||||
const reportPatchBase = {
|
||||
handledById: user.id,
|
||||
handledAt: new Date(),
|
||||
handlingNote: note,
|
||||
};
|
||||
|
||||
if (action === 'review') {
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const claimed = await tx.chatUserReport.updateMany({
|
||||
where: { id: reportId, status: ChatReportStatus.OPEN },
|
||||
data: {
|
||||
...reportPatchBase,
|
||||
status: ChatReportStatus.REVIEWED,
|
||||
lastAction: ChatReportAction.REVIEW,
|
||||
},
|
||||
});
|
||||
if (claimed.count === 0) {
|
||||
throw new Error(REPORT_ALREADY_HANDLED_ERROR);
|
||||
}
|
||||
|
||||
await tx.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.REPORT_REVIEWED,
|
||||
actorId: user.id,
|
||||
targetUserId,
|
||||
targetChannel: report.channel.name,
|
||||
reason: note,
|
||||
details: {
|
||||
reportId,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === REPORT_ALREADY_HANDLED_ERROR) {
|
||||
return new Response('Report has already been handled', { status: 409 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
|
||||
if (action === 'dismiss') {
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const claimed = await tx.chatUserReport.updateMany({
|
||||
where: { id: reportId, status: ChatReportStatus.OPEN },
|
||||
data: {
|
||||
...reportPatchBase,
|
||||
status: ChatReportStatus.DISMISSED,
|
||||
lastAction: ChatReportAction.DISMISS,
|
||||
},
|
||||
});
|
||||
if (claimed.count === 0) {
|
||||
throw new Error(REPORT_ALREADY_HANDLED_ERROR);
|
||||
}
|
||||
|
||||
await tx.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.REPORT_DISMISSED,
|
||||
actorId: user.id,
|
||||
targetUserId,
|
||||
targetChannel: report.channel.name,
|
||||
reason: note,
|
||||
details: {
|
||||
reportId,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === REPORT_ALREADY_HANDLED_ERROR) {
|
||||
return new Response('Report has already been handled', { status: 409 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
|
||||
if (action === 'delete_reported_message') {
|
||||
if (!report.reportedMessageId) {
|
||||
return new Response('No reported message id available for this report', { status: 400 });
|
||||
}
|
||||
|
||||
const channelKey = `chat:history:${report.channel.name}`;
|
||||
const history = await redis.zrange(channelKey, 0, -1);
|
||||
let deleted = false;
|
||||
|
||||
for (const entry of history) {
|
||||
try {
|
||||
const parsed = JSON.parse(entry) as { msgId?: string };
|
||||
if (parsed.msgId === report.reportedMessageId) {
|
||||
await redis.zrem(channelKey, entry);
|
||||
deleted = true;
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (!deleted) {
|
||||
return new Response('Reported message was not found in chat history', { status: 404 });
|
||||
}
|
||||
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const claimed = await tx.chatUserReport.updateMany({
|
||||
where: { id: reportId, status: ChatReportStatus.OPEN },
|
||||
data: {
|
||||
...reportPatchBase,
|
||||
status: ChatReportStatus.REVIEWED,
|
||||
lastAction: ChatReportAction.DELETE_REPORTED_MESSAGE,
|
||||
},
|
||||
});
|
||||
if (claimed.count === 0) {
|
||||
throw new Error(REPORT_ALREADY_HANDLED_ERROR);
|
||||
}
|
||||
|
||||
await tx.chatModerationEvent.create({
|
||||
data: {
|
||||
action: ChatModerationAction.MESSAGE_DELETED,
|
||||
channelId: report.channel.id,
|
||||
moderatorId: user.id,
|
||||
targetUserId,
|
||||
reason: note ?? 'Message deleted from report review',
|
||||
details: {
|
||||
reportId,
|
||||
msgId: report.reportedMessageId,
|
||||
messageContent: report.reportedMessage,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.REPORT_ENFORCEMENT,
|
||||
actorId: user.id,
|
||||
targetUserId,
|
||||
targetChannel: report.channel.name,
|
||||
reason: note,
|
||||
details: {
|
||||
reportId,
|
||||
enforcement: 'DELETE_REPORTED_MESSAGE',
|
||||
msgId: report.reportedMessageId,
|
||||
messageContent: report.reportedMessage,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === REPORT_ALREADY_HANDLED_ERROR) {
|
||||
return new Response('Report has already been handled', { status: 409 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
|
||||
if (!targetUserId) {
|
||||
return new Response('Report target is unavailable', { status: 400 });
|
||||
}
|
||||
|
||||
if (
|
||||
action === 'timeout_10m' ||
|
||||
action === 'timeout_1h' ||
|
||||
action === 'ban_chat' ||
|
||||
action === 'lift_chat_ban'
|
||||
) {
|
||||
const timeoutSeconds = action === 'timeout_10m' ? 600 : action === 'timeout_1h' ? 3600 : null;
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const claimed = await tx.chatUserReport.updateMany({
|
||||
where: { id: reportId, status: ChatReportStatus.OPEN },
|
||||
data: {
|
||||
...reportPatchBase,
|
||||
status: ChatReportStatus.REVIEWED,
|
||||
lastAction:
|
||||
action === 'timeout_10m'
|
||||
? ChatReportAction.TIMEOUT_10M
|
||||
: action === 'timeout_1h'
|
||||
? ChatReportAction.TIMEOUT_1H
|
||||
: action === 'ban_chat'
|
||||
? ChatReportAction.BAN_CHAT
|
||||
: ChatReportAction.LIFT_CHAT_BAN,
|
||||
},
|
||||
});
|
||||
if (claimed.count === 0) {
|
||||
throw new Error(REPORT_ALREADY_HANDLED_ERROR);
|
||||
}
|
||||
|
||||
if (action === 'lift_chat_ban') {
|
||||
const deleted = await tx.chatUserBan.deleteMany({
|
||||
where: {
|
||||
channelId: report.channel.id,
|
||||
userId: targetUserId,
|
||||
},
|
||||
});
|
||||
if (deleted.count === 0) {
|
||||
throw new Error(NO_ACTIVE_CHAT_BAN_ERROR);
|
||||
}
|
||||
} else {
|
||||
await tx.chatUserBan.upsert({
|
||||
where: {
|
||||
channelId_userId: {
|
||||
channelId: report.channel.id,
|
||||
userId: targetUserId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
channelId: report.channel.id,
|
||||
userId: targetUserId,
|
||||
bannedById: user.id,
|
||||
reason: note ?? report.reason,
|
||||
expiresAt: timeoutSeconds ? new Date(Date.now() + timeoutSeconds * 1000) : null,
|
||||
},
|
||||
update: {
|
||||
bannedById: user.id,
|
||||
reason: note ?? report.reason,
|
||||
expiresAt: timeoutSeconds ? new Date(Date.now() + timeoutSeconds * 1000) : null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
await tx.chatModerationEvent.create({
|
||||
data: {
|
||||
action:
|
||||
action === 'lift_chat_ban'
|
||||
? ChatModerationAction.USER_UNBANNED
|
||||
: action === 'ban_chat'
|
||||
? ChatModerationAction.USER_BANNED
|
||||
: ChatModerationAction.USER_TIMEOUT,
|
||||
channelId: report.channel.id,
|
||||
moderatorId: user.id,
|
||||
targetUserId,
|
||||
reason: note ?? report.reason,
|
||||
details:
|
||||
timeoutSeconds === null
|
||||
? ({ reportId } as any)
|
||||
: ({ reportId, durationSeconds: timeoutSeconds } as any),
|
||||
},
|
||||
});
|
||||
|
||||
await tx.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.REPORT_ENFORCEMENT,
|
||||
actorId: user.id,
|
||||
targetUserId,
|
||||
targetChannel: report.channel.name,
|
||||
reason: note,
|
||||
details: {
|
||||
reportId,
|
||||
enforcement:
|
||||
action === 'timeout_10m'
|
||||
? 'TIMEOUT_10M'
|
||||
: action === 'timeout_1h'
|
||||
? 'TIMEOUT_1H'
|
||||
: action === 'ban_chat'
|
||||
? 'BAN_CHAT'
|
||||
: 'LIFT_CHAT_BAN',
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === REPORT_ALREADY_HANDLED_ERROR) {
|
||||
return new Response('Report has already been handled', { status: 409 });
|
||||
}
|
||||
if (error instanceof Error && error.message === NO_ACTIVE_CHAT_BAN_ERROR) {
|
||||
return new Response('User does not have an active chat ban for this channel', {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
|
||||
if (action === 'ban_platform' || action === 'unban_platform') {
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const claimed = await tx.chatUserReport.updateMany({
|
||||
where: { id: reportId, status: ChatReportStatus.OPEN },
|
||||
data: {
|
||||
...reportPatchBase,
|
||||
status: ChatReportStatus.REVIEWED,
|
||||
lastAction:
|
||||
action === 'ban_platform'
|
||||
? ChatReportAction.BAN_PLATFORM
|
||||
: ChatReportAction.UNBAN_PLATFORM,
|
||||
},
|
||||
});
|
||||
if (claimed.count === 0) {
|
||||
throw new Error(REPORT_ALREADY_HANDLED_ERROR);
|
||||
}
|
||||
|
||||
if (action === 'ban_platform') {
|
||||
await tx.userBan.upsert({
|
||||
where: { userId: targetUserId },
|
||||
update: {
|
||||
reason: note ?? report.reason,
|
||||
bannedBy: user.id,
|
||||
expiresAt: null,
|
||||
},
|
||||
create: {
|
||||
userId: targetUserId,
|
||||
reason: note ?? report.reason,
|
||||
bannedBy: user.id,
|
||||
expiresAt: null,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const deleted = await tx.userBan.deleteMany({ where: { userId: targetUserId } });
|
||||
if (deleted.count === 0) {
|
||||
throw new Error(NO_ACTIVE_PLATFORM_BAN_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
await tx.adminAuditLog.create({
|
||||
data: {
|
||||
action:
|
||||
action === 'ban_platform'
|
||||
? AdminAuditAction.USER_BANNED
|
||||
: AdminAuditAction.USER_UNBANNED,
|
||||
actorId: user.id,
|
||||
targetUserId,
|
||||
targetChannel: report.channel.name,
|
||||
reason: note,
|
||||
details: {
|
||||
reportId,
|
||||
source: 'CHAT_REPORT',
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.REPORT_ENFORCEMENT,
|
||||
actorId: user.id,
|
||||
targetUserId,
|
||||
targetChannel: report.channel.name,
|
||||
reason: note,
|
||||
details: {
|
||||
reportId,
|
||||
enforcement: action === 'ban_platform' ? 'BAN_PLATFORM' : 'UNBAN_PLATFORM',
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === REPORT_ALREADY_HANDLED_ERROR) {
|
||||
return new Response('Report has already been handled', { status: 409 });
|
||||
}
|
||||
if (error instanceof Error && error.message === NO_ACTIVE_PLATFORM_BAN_ERROR) {
|
||||
return new Response('User does not have an active platform ban', { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
|
||||
return new Response('Invalid action', { status: 400 });
|
||||
}
|
||||
247
apps/web/src/app/(ui)/(protected)/api/admin/users/route.ts
Normal file
@@ -0,0 +1,247 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { AdminAuditAction, getRedisConnection, prisma } from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user?.isAdmin) {
|
||||
return new Response('Forbidden', { status: 403 });
|
||||
}
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const search = searchParams.get('search') || '';
|
||||
|
||||
const users = await prisma.user.findMany({
|
||||
where: search
|
||||
? {
|
||||
OR: [
|
||||
{ slack_id: { contains: search, mode: 'insensitive' } },
|
||||
{ email: { contains: search, mode: 'insensitive' } },
|
||||
{ personalChannel: { name: { contains: search, mode: 'insensitive' } } },
|
||||
],
|
||||
hasOnboarded: true,
|
||||
}
|
||||
: undefined,
|
||||
select: {
|
||||
id: true,
|
||||
slack_id: true,
|
||||
email: true,
|
||||
pfpUrl: true,
|
||||
isAdmin: true,
|
||||
bypassVerification: true,
|
||||
ban: true,
|
||||
personalChannel: { select: { name: true } },
|
||||
},
|
||||
take: 50,
|
||||
});
|
||||
return Response.json(users);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { user, session } = await validateRequest();
|
||||
if (!user?.isAdmin) {
|
||||
return new Response('Forbidden', { status: 403 });
|
||||
}
|
||||
|
||||
let body: {
|
||||
userId?: string;
|
||||
action: 'ban' | 'unban' | 'promote' | 'demote' | 'logout_others' | 'toggle_bypass_verification';
|
||||
reason?: string;
|
||||
expiresAt?: string;
|
||||
};
|
||||
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return new Response('Invalid JSON body', { status: 400 });
|
||||
}
|
||||
|
||||
const { userId, action, reason, expiresAt } = body;
|
||||
|
||||
if (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 });
|
||||
}
|
||||
|
||||
let expiresAtDate: Date | null = null;
|
||||
if (expiresAt !== undefined && expiresAt !== null && expiresAt !== '') {
|
||||
expiresAtDate = new Date(expiresAt);
|
||||
if (isNaN(expiresAtDate.getTime())) {
|
||||
return new Response('Invalid expiresAt date', { status: 400 });
|
||||
}
|
||||
if (expiresAtDate <= new Date()) {
|
||||
return new Response('expiresAt must be a future date', { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
const targetUser = await prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!targetUser) {
|
||||
return new Response('User not found', { status: 404 });
|
||||
}
|
||||
|
||||
if (action === 'ban') {
|
||||
if (targetUser.isAdmin) {
|
||||
return new Response('Cannot ban an admin', { status: 400 });
|
||||
}
|
||||
|
||||
if (!reason) {
|
||||
return new Response('Reason is required for banning', { status: 400 });
|
||||
}
|
||||
|
||||
await prisma.userBan.upsert({
|
||||
where: { userId },
|
||||
update: {
|
||||
reason,
|
||||
bannedBy: user.id,
|
||||
expiresAt: expiresAtDate,
|
||||
},
|
||||
create: {
|
||||
userId,
|
||||
reason,
|
||||
bannedBy: user.id,
|
||||
expiresAt: expiresAtDate,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.USER_BANNED,
|
||||
actorId: user.id,
|
||||
targetUserId: userId,
|
||||
reason,
|
||||
details: {
|
||||
expiresAt: expiresAtDate?.toISOString() ?? null,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({ success: true, message: 'User banned' });
|
||||
}
|
||||
|
||||
if (action === 'unban') {
|
||||
const deleted = await prisma.userBan.deleteMany({ where: { userId } });
|
||||
if (deleted.count === 0) {
|
||||
return new Response('User does not have an active platform ban', { status: 400 });
|
||||
}
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.USER_UNBANNED,
|
||||
actorId: user.id,
|
||||
targetUserId: userId,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({ success: true, message: 'User unbanned' });
|
||||
}
|
||||
|
||||
if (action === 'promote') {
|
||||
if (targetUser.isAdmin) {
|
||||
return new Response('User is already an admin', { status: 400 });
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { isAdmin: true },
|
||||
});
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.USER_PROMOTED,
|
||||
actorId: user.id,
|
||||
targetUserId: userId,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({ success: true, message: 'User promoted to admin' });
|
||||
}
|
||||
|
||||
if (action === 'demote') {
|
||||
if (!targetUser.isAdmin) {
|
||||
return new Response('User is not an admin', { status: 400 });
|
||||
}
|
||||
|
||||
if (targetUser.id === user.id) {
|
||||
return new Response('Cannot demote yourself', { status: 400 });
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { isAdmin: false },
|
||||
});
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.USER_DEMOTED,
|
||||
actorId: user.id,
|
||||
targetUserId: userId,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({ success: true, message: 'User demoted from admin' });
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
116
apps/web/src/app/(ui)/(protected)/api/mediamtx/publish/route.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
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));
|
||||
}
|
||||
const parsed = schema.safeParse(body);
|
||||
|
||||
if (!parsed.success) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.error('Invalid MediaMTX auth request:', parsed.error.flatten());
|
||||
}
|
||||
|
||||
return finish('invalid request', 400, 'invalid_request');
|
||||
}
|
||||
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 finish('invalid stream key', 403, 'invalid_stream_key');
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { name: path },
|
||||
include: {
|
||||
restriction: true,
|
||||
owner: {
|
||||
include: { ban: true },
|
||||
},
|
||||
streamInfo: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (channel?.restriction) {
|
||||
const isExpired =
|
||||
channel.restriction.expiresAt && new Date(channel.restriction.expiresAt) < new Date();
|
||||
if (!isExpired) {
|
||||
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();
|
||||
if (!isExpired) {
|
||||
return finish('user banned', 403, 'user_banned');
|
||||
}
|
||||
}
|
||||
|
||||
if (channel?.streamInfo[0].isLive) {
|
||||
return finish('stream already live', 403, 'stream_already_live');
|
||||
}
|
||||
|
||||
return finish('youre in yay', 200, 'authorized_publish');
|
||||
}
|
||||
}
|
||||
if (parsedAction === 'read' && parsedProtocol === 'hls') {
|
||||
if (password === process.env.MEDIAMTX_PUBLISH_KEY) {
|
||||
return finish('authorized (hls read key for thumbs)', 200, 'authorized_thumbnail');
|
||||
}
|
||||
const sessionExists = await redis.exists(`sessions:${password}`);
|
||||
if (!sessionExists) {
|
||||
return finish('unauthorized', 401, 'unauthorized_session');
|
||||
}
|
||||
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 finish('uhh', 401, 'unauthorized');
|
||||
}
|
||||
|
||||
const emptyableString = z
|
||||
.string()
|
||||
.nullish()
|
||||
.transform((value) => value ?? '');
|
||||
|
||||
const schema = z.object({
|
||||
user: emptyableString,
|
||||
password: emptyableString,
|
||||
token: emptyableString,
|
||||
ip: emptyableString,
|
||||
action: z.enum(['publish', 'read', 'playback', 'api', 'metrics', 'pprof']),
|
||||
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,39 +0,0 @@
|
||||
import fsP from 'fs/promises';
|
||||
import fs from 'fs';
|
||||
import { getRedisConnection } from '@hctv/db';
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
export async function GET(request: Request, { params }: { params: Promise<{ path: string }> }) {
|
||||
const { path } = await params;
|
||||
const c = await cookies();
|
||||
|
||||
const sessionCookie = c.get('auth_session')?.value;
|
||||
if (!sessionCookie) {
|
||||
return new Response("Unauthorized", { status: 401 });
|
||||
}
|
||||
const sessionExists = await getRedisConnection().exists(`sessions:${sessionCookie}`);
|
||||
if (sessionExists === 0) {
|
||||
return new Response("Unauthorized", { status: 401 });
|
||||
}
|
||||
|
||||
if (path.includes('..')) {
|
||||
return new Response("nuh uh", { status: 403 });
|
||||
}
|
||||
|
||||
const basePath = '/dev/shm/hls';
|
||||
const filePath = `${basePath}/${path}`;
|
||||
const exists = fs.existsSync(filePath);
|
||||
|
||||
if (!exists) {
|
||||
return new Response("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
const file = await fsP.readFile(filePath);
|
||||
return new Response(file, {
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': 'GET',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -15,7 +15,14 @@ export async function POST(request: NextRequest) {
|
||||
key: streamKey,
|
||||
},
|
||||
include: {
|
||||
channel: true,
|
||||
channel: {
|
||||
include: {
|
||||
restriction: true,
|
||||
owner: {
|
||||
include: { ban: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -24,6 +31,23 @@ export async function POST(request: NextRequest) {
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
|
||||
if (key.channel.restriction) {
|
||||
const isExpired = key.channel.restriction.expiresAt &&
|
||||
new Date(key.channel.restriction.expiresAt) < new Date();
|
||||
if (!isExpired) {
|
||||
return new Response('channel restricted', { status: 403 });
|
||||
}
|
||||
}
|
||||
|
||||
if (key.channel.owner?.ban) {
|
||||
const isExpired = key.channel.owner.ban.expiresAt &&
|
||||
new Date(key.channel.owner.ban.expiresAt) < new Date();
|
||||
if (!isExpired) {
|
||||
return new Response('user banned', { status: 403 });
|
||||
}
|
||||
}
|
||||
|
||||
return new Response('', {
|
||||
status: 302,
|
||||
headers: {
|
||||
|
||||
@@ -1,56 +1,106 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { regenerateStreamKey } from '@/lib/db/streamKey';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
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 dbUpdate = await prisma.streamKey.upsert({
|
||||
create: {
|
||||
key: crypto.randomUUID(),
|
||||
channelId: channelInfo.id
|
||||
},
|
||||
update: {
|
||||
key: crypto.randomUUID()
|
||||
},
|
||||
where: {
|
||||
channelId: channelInfo.id
|
||||
}
|
||||
})
|
||||
return { channel: { id: channel.id } };
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ key: dbUpdate.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}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma, getRedisConnection } from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
const RATE_LIMIT_WINDOW_SECONDS = 10 * 60;
|
||||
const RATE_LIMIT_MAX_REPORTS = 5;
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
let body: {
|
||||
channelName?: string;
|
||||
targetUserId?: string;
|
||||
targetUsername?: string;
|
||||
msgId?: string;
|
||||
message?: string;
|
||||
reason?: string;
|
||||
};
|
||||
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return new Response('Invalid JSON body', { status: 400 });
|
||||
}
|
||||
|
||||
const channelName = body.channelName?.trim();
|
||||
const targetUserId = body.targetUserId?.trim();
|
||||
const reason = body.reason?.trim();
|
||||
|
||||
if (!channelName || !targetUserId || !reason) {
|
||||
return new Response('Missing required fields', { status: 400 });
|
||||
}
|
||||
|
||||
if (targetUserId === user.id) {
|
||||
return new Response('You cannot report yourself', { status: 400 });
|
||||
}
|
||||
|
||||
if (reason.length < 10 || reason.length > 1000) {
|
||||
return new Response('Reason must be between 10 and 1000 characters', { status: 400 });
|
||||
}
|
||||
|
||||
const redis = getRedisConnection();
|
||||
const rateLimitKey = `report_rl:${user.id}`;
|
||||
const currentCount = await redis.incr(rateLimitKey);
|
||||
if (currentCount === 1) {
|
||||
await redis.expire(rateLimitKey, RATE_LIMIT_WINDOW_SECONDS);
|
||||
}
|
||||
if (currentCount > RATE_LIMIT_MAX_REPORTS) {
|
||||
return new Response('Too many reports submitted. Please wait before submitting more.', {
|
||||
status: 429,
|
||||
});
|
||||
}
|
||||
|
||||
const [channel, targetUser] = await Promise.all([
|
||||
prisma.channel.findUnique({
|
||||
where: { name: channelName },
|
||||
select: { id: true },
|
||||
}),
|
||||
prisma.user.findUnique({
|
||||
where: { id: targetUserId },
|
||||
select: { id: true, personalChannel: { select: { name: true } } },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!channel) {
|
||||
return new Response('Channel not found', { status: 404 });
|
||||
}
|
||||
|
||||
if (!targetUser) {
|
||||
return new Response('Target user not found', { status: 404 });
|
||||
}
|
||||
|
||||
const msgId = body.msgId?.trim() || null;
|
||||
const duplicateCheck = await prisma.chatUserReport.findFirst({
|
||||
where: {
|
||||
channelId: channel.id,
|
||||
reporterId: user.id,
|
||||
targetUserId: targetUser.id,
|
||||
reportedMessageId: msgId,
|
||||
status: 'OPEN',
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (duplicateCheck) {
|
||||
return new Response('You have already submitted an open report for this message.', {
|
||||
status: 409,
|
||||
});
|
||||
}
|
||||
|
||||
await prisma.chatUserReport.create({
|
||||
data: {
|
||||
channelId: channel.id,
|
||||
reporterId: user.id,
|
||||
targetUserId: targetUser.id,
|
||||
targetUsername: body.targetUsername?.trim() || targetUser.personalChannel?.name || null,
|
||||
reportedMessageId: msgId,
|
||||
reportedMessage: body.message?.trim().slice(0, 1000) || null,
|
||||
reason,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
@@ -9,6 +9,7 @@ export async function GET(request: NextRequest) {
|
||||
const shouldGetOwned = searchParams.get('owned') === 'true';
|
||||
const allPersonalChannels = searchParams.get('personal') === 'true';
|
||||
const isLive = searchParams.get('live') === 'true';
|
||||
const username = searchParams.get('username');
|
||||
const { user } = await validateRequest();
|
||||
|
||||
if ((shouldGetOwned || allPersonalChannels) && !user) {
|
||||
@@ -18,15 +19,20 @@ export async function GET(request: NextRequest) {
|
||||
const where: Prisma.StreamInfoWhereInput = {};
|
||||
const channelConditions: Prisma.ChannelWhereInput[] = [];
|
||||
|
||||
if (username) {
|
||||
where.username = username;
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -35,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({
|
||||
@@ -46,10 +51,42 @@ export async function GET(request: NextRequest) {
|
||||
channel: {
|
||||
include: {
|
||||
personalFor: true,
|
||||
}
|
||||
restriction: {
|
||||
select: {
|
||||
id: true,
|
||||
expiresAt: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
db.forEach((obj) => {
|
||||
if (obj.channel.personalFor) {
|
||||
// @ts-ignore
|
||||
delete obj.channel.personalFor.email;
|
||||
}
|
||||
// @ts-ignore
|
||||
delete obj.channel.obsChatGrantToken;
|
||||
|
||||
if (obj.channel.restriction) {
|
||||
const isExpired =
|
||||
obj.channel.restriction.expiresAt &&
|
||||
new Date(obj.channel.restriction.expiresAt) < new Date();
|
||||
if (isExpired) {
|
||||
// @ts-ignore
|
||||
obj.channel.restriction = null;
|
||||
} else {
|
||||
// @ts-ignore
|
||||
obj.channel.isRestricted = true;
|
||||
// @ts-ignore
|
||||
obj.channel.restrictionExpiresAt = obj.channel.restriction.expiresAt;
|
||||
// @ts-ignore
|
||||
delete obj.channel.restriction;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return Response.json(db);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,42 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { redirect, RedirectType } from 'next/navigation';
|
||||
import { prisma } from '@hctv/db';
|
||||
|
||||
export default async function Layout({ children }: { children: React.ReactNode }) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return redirect('/auth/slack');
|
||||
return redirect('/auth/hackclub');
|
||||
}
|
||||
if (!user.hasOnboarded) {
|
||||
return redirect(`/onboarding`, RedirectType.push);
|
||||
}
|
||||
|
||||
const ban = await prisma.userBan.findUnique({
|
||||
where: { userId: user.id },
|
||||
});
|
||||
|
||||
if (ban) {
|
||||
const isExpired = ban.expiresAt && new Date(ban.expiresAt) < new Date();
|
||||
if (!isExpired) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-screen">
|
||||
<h1 className="text-3xl font-bold text-destructive mb-4">Account Suspended</h1>
|
||||
<p className="text-muted-foreground text-center max-w-md mb-4">
|
||||
Your account has been suspended from hackclub.tv.
|
||||
</p>
|
||||
<div className="bg-muted p-4 rounded-lg max-w-md">
|
||||
<p className="text-sm font-medium">Reason:</p>
|
||||
<p className="text-sm text-muted-foreground">{ban.reason}</p>
|
||||
</div>
|
||||
{ban.expiresAt && (
|
||||
<p className="text-sm text-muted-foreground mt-4">
|
||||
Expires: {new Date(ban.expiresAt).toLocaleDateString()}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return children;
|
||||
}
|
||||
|
||||
@@ -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,5 +1,6 @@
|
||||
import { getBotBySlug } from '@/lib/db/resolve';
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { can } from '@/lib/auth/abac';
|
||||
import { redirect } from 'next/navigation';
|
||||
import Image from 'next/image';
|
||||
import { GeneralSettings } from '@/app/(ui)/(protected)/settings/bot/[slug]/gensettings';
|
||||
@@ -12,7 +13,7 @@ export default async function Page({ params }: { params: Promise<{ slug: string
|
||||
const { slug } = await params;
|
||||
const bot = await getBotBySlug(slug);
|
||||
|
||||
if (!bot || bot.ownerId !== user?.id) {
|
||||
if (!user || !bot || !can(user, 'update', 'bot', { bot })) {
|
||||
redirect('/settings/bot');
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { prisma } from '@hctv/db';
|
||||
import { redirect } from 'next/navigation';
|
||||
import ChannelSettingsClient from './page.client';
|
||||
import { resolvePersonalChannel } from '@/lib/auth/resolve';
|
||||
import { can } from '@/lib/auth/abac';
|
||||
|
||||
export default async function ChannelSettingsPage({
|
||||
params,
|
||||
@@ -13,7 +14,7 @@ export default async function ChannelSettingsPage({
|
||||
const { user } = await validateRequest();
|
||||
|
||||
if (!user) {
|
||||
redirect('/auth/slack');
|
||||
redirect('/auth/hackclub');
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({
|
||||
@@ -21,8 +22,11 @@ export default async function ChannelSettingsPage({
|
||||
include: {
|
||||
owner: true,
|
||||
managers: true,
|
||||
chatModerators: true,
|
||||
chatModeratorBots: true,
|
||||
streamInfo: true,
|
||||
streamKey: true,
|
||||
chatSettings: true,
|
||||
followers: {
|
||||
include: {
|
||||
user: {
|
||||
@@ -42,9 +46,8 @@ export default async function ChannelSettingsPage({
|
||||
}
|
||||
|
||||
const isOwner = channel.ownerId === user.id;
|
||||
const isManager = channel.managers.some((manager) => manager.id === user.id);
|
||||
|
||||
if (!isOwner && !isManager) {
|
||||
if (!can(user, 'update', 'channel', { channel })) {
|
||||
redirect('/');
|
||||
}
|
||||
|
||||
@@ -52,17 +55,38 @@ export default async function ChannelSettingsPage({
|
||||
const managerPersonalChannels = await Promise.all(
|
||||
channel.managers.map((manager) => resolvePersonalChannel(manager.id))
|
||||
);
|
||||
const managerIds = new Set(channel.managers.map((manager) => manager.id));
|
||||
const extraChatModerators = channel.chatModerators.filter(
|
||||
(moderator) => moderator.id !== channel.ownerId && !managerIds.has(moderator.id)
|
||||
);
|
||||
const chatModeratorPersonalChannels = await Promise.all(
|
||||
extraChatModerators.map((moderator) => resolvePersonalChannel(moderator.id))
|
||||
);
|
||||
const followerPersonalChannels = await Promise.all(
|
||||
channel.followers.map((follower) => resolvePersonalChannel(follower.user.id))
|
||||
);
|
||||
const allBotAccounts = await prisma.botAccount.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
displayName: true,
|
||||
slug: true,
|
||||
pfpUrl: true,
|
||||
},
|
||||
orderBy: {
|
||||
slug: 'asc',
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<ChannelSettingsClient
|
||||
channel={{
|
||||
...channel,
|
||||
chatModerators: extraChatModerators,
|
||||
ownerPersonalChannel,
|
||||
managerPersonalChannels,
|
||||
chatModeratorPersonalChannels,
|
||||
followerPersonalChannels,
|
||||
allBotAccounts,
|
||||
}}
|
||||
isOwner={isOwner}
|
||||
currentUser={user}
|
||||
|
||||
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';
|
||||
};
|
||||
218
apps/web/src/app/(ui)/(public)/auth/hackclub/callback/route.ts
Normal file
@@ -0,0 +1,218 @@
|
||||
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';
|
||||
import { generateIdFromEntropySize } from 'lucia';
|
||||
import { prisma } from '@hctv/db';
|
||||
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) {
|
||||
console.log('invalid state stuff');
|
||||
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}`,
|
||||
},
|
||||
});
|
||||
|
||||
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.', {
|
||||
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,
|
||||
},
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
// Update email if it's missing or changed
|
||||
if (existingUser.email !== identity.primary_email) {
|
||||
await prisma.user.update({
|
||||
where: { id: existingUser.id },
|
||||
data: { email: identity.primary_email },
|
||||
});
|
||||
}
|
||||
|
||||
const session = await lucia.createSession(existingUser.id, {});
|
||||
const sessionCookie = lucia.createSessionCookie(session.id);
|
||||
await getRedisConnection().set(`sessions:${session.id}`, '');
|
||||
cookies.set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
Location: '/',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const userId = generateIdFromEntropySize(10);
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
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',
|
||||
hasOnboarded: false,
|
||||
},
|
||||
});
|
||||
|
||||
const session = await lucia.createSession(userId, {});
|
||||
const sessionCookie = lucia.createSessionCookie(session.id);
|
||||
await getRedisConnection().set(`sessions:${session.id}`, '');
|
||||
cookies.set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
Location: '/',
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
// the specific error message depends on the provider
|
||||
if (e instanceof OAuth2RequestError) {
|
||||
// invalid code
|
||||
return new Response(null, {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
return new Response(null, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
interface HackClubIdentity {
|
||||
id: string;
|
||||
slack_id?: string;
|
||||
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;
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { generateState } from "arctic";
|
||||
import { slack } from '@hctv/auth';
|
||||
import { hackClub, HCID_AUTH_URL } from '@hctv/auth';
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const state = generateState();
|
||||
const url = slack.createAuthorizationURL(state, ['openid', 'profile']);
|
||||
const url = hackClub.createAuthorizationURL(HCID_AUTH_URL, state, ['slack_id', 'verification_status', 'email']);
|
||||
|
||||
(await cookies()).set("slack_oauth_state", state, {
|
||||
(await cookies()).set("hackclub_oauth_state", state, {
|
||||
path: "/",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
httpOnly: true,
|
||||
@@ -1,122 +0,0 @@
|
||||
import { slack, lucia } from '@hctv/auth';
|
||||
import { cookies as nextCookies } from 'next/headers';
|
||||
import { decodeIdToken, OAuth2RequestError } from 'arctic';
|
||||
import { generateIdFromEntropySize } from 'lucia';
|
||||
import { prisma } from '@hctv/db';
|
||||
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("slack_oauth_state")?.value ?? null;
|
||||
if (!code || !state || !storedState || state !== storedState) {
|
||||
console.log('invalid state stuff');
|
||||
return new Response(null, {
|
||||
status: 400
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const tokens = await slack.validateAuthorizationCode(code);
|
||||
const accessToken = tokens.accessToken()
|
||||
const slackUserResponse = await fetch('https://slack.com/api/openid.connect.userInfo', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
const slackUser: SlackUserInfo = await slackUserResponse.json();
|
||||
|
||||
const existingUser = await prisma.user.findFirst({
|
||||
where: {
|
||||
slack_id: slackUser.sub,
|
||||
},
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
const session = await lucia.createSession(existingUser.id, {});
|
||||
const sessionCookie = lucia.createSessionCookie(session.id);
|
||||
await getRedisConnection().set(`sessions:${session.id}`, '');
|
||||
cookies.set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
Location: '/',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const userId = generateIdFromEntropySize(10);
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: userId,
|
||||
slack_id: slackUser.sub,
|
||||
pfpUrl: `https://cachet.dunkirk.sh/users/${slackUser.sub}/r`,
|
||||
hasOnboarded: false,
|
||||
},
|
||||
});
|
||||
|
||||
const session = await lucia.createSession(userId, {});
|
||||
const sessionCookie = lucia.createSessionCookie(session.id);
|
||||
await getRedisConnection().set(`sessions:${session.id}`, '');
|
||||
cookies.set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
Location: '/',
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
// the specific error message depends on the provider
|
||||
if (e instanceof OAuth2RequestError) {
|
||||
// invalid code
|
||||
return new Response(null, {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
return new Response(null, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
interface SlackUserInfo {
|
||||
// OpenID Connect standard fields
|
||||
ok: boolean;
|
||||
sub: string;
|
||||
email: string;
|
||||
email_verified: boolean;
|
||||
date_email_verified: number;
|
||||
name: string;
|
||||
picture: string;
|
||||
given_name: string;
|
||||
family_name: string;
|
||||
locale: string;
|
||||
|
||||
// Slack-specific fields
|
||||
['https://slack.com/user_id']: string;
|
||||
['https://slack.com/team_id']: string;
|
||||
['https://slack.com/team_name']: string;
|
||||
['https://slack.com/team_domain']: string;
|
||||
|
||||
// User image URLs
|
||||
['https://slack.com/user_image_24']: string;
|
||||
['https://slack.com/user_image_32']: string;
|
||||
['https://slack.com/user_image_48']: string;
|
||||
['https://slack.com/user_image_72']: string;
|
||||
['https://slack.com/user_image_192']: string;
|
||||
['https://slack.com/user_image_512']: string;
|
||||
|
||||
// Team image URLs
|
||||
['https://slack.com/team_image_34']?: string;
|
||||
['https://slack.com/team_image_44']?: string;
|
||||
['https://slack.com/team_image_68']?: string;
|
||||
['https://slack.com/team_image_88']?: string;
|
||||
['https://slack.com/team_image_102']?: string;
|
||||
['https://slack.com/team_image_132']?: string;
|
||||
['https://slack.com/team_image_230']?: string;
|
||||
['https://slack.com/team_image_default']?: boolean;
|
||||
}
|
||||
@@ -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>
|
||||
@@ -107,7 +108,9 @@ export default function OnboardingClient() {
|
||||
name: 'username',
|
||||
label: 'Channel Username',
|
||||
type: 'text',
|
||||
placeholder: 'e.g., yourname or yourname-codes'
|
||||
placeholder: 'e.g., yourname or yourname-codes',
|
||||
maxChars: 20,
|
||||
inputFilter: /[^a-z0-9_-]/g,
|
||||
},
|
||||
]}
|
||||
schemaName="onboard"
|
||||
@@ -119,7 +122,7 @@ export default function OnboardingClient() {
|
||||
<div className="mt-4 p-3 bg-muted/30 rounded-md">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>Username rules:</strong> Only lowercase letters (a-z), numbers (0-9),
|
||||
underscores (_), and dashes (-) are allowed. Must be unique across the platform.
|
||||
underscores (_), and dashes (-) are allowed. Up to 20 characters. Must be unique across the platform.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
@@ -4,7 +4,10 @@ import OnboardingClient from "./page.client";
|
||||
|
||||
export default async function Page() {
|
||||
const { user } = await validateRequest();
|
||||
if (user!.hasOnboarded) {
|
||||
if (!user) {
|
||||
return redirect('/');
|
||||
}
|
||||
if (user.hasOnboarded) {
|
||||
return redirect('/');
|
||||
}
|
||||
return <OnboardingClient />;
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import LandingPage from '@/components/app/LandingPage/LandingPage';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import StreamGrid from '@/components/app/StreamGrid/StreamGrid';
|
||||
import ConfusedDino from '@/components/ui/confuseddino';
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@radix-ui/react-avatar';
|
||||
import Image from 'next/image';
|
||||
import Link from 'next/link';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
@@ -13,66 +11,45 @@ export default async function Home() {
|
||||
if (user && !user?.hasOnboarded) {
|
||||
redirect('/onboarding');
|
||||
}
|
||||
const streams = await prisma.streamInfo.findMany({
|
||||
where: {
|
||||
isLive: true,
|
||||
},
|
||||
include: {
|
||||
channel: true,
|
||||
},
|
||||
});
|
||||
|
||||
const [liveStreams, offlineStreams] = await Promise.all([
|
||||
prisma.streamInfo.findMany({
|
||||
where: { isLive: true },
|
||||
include: { channel: true },
|
||||
}),
|
||||
prisma.streamInfo.findMany({
|
||||
where: { isLive: false },
|
||||
include: { channel: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!user) {
|
||||
return <LandingPage />;
|
||||
}
|
||||
if (!streams.length) {
|
||||
|
||||
if (!liveStreams.length && !offlineStreams.length) {
|
||||
return (
|
||||
<div className="flex justify-center items-center text-center flex-col pt-4 gap-2">
|
||||
<h2>No streams found!</h2>
|
||||
<p>...maybe start one?</p>
|
||||
<ConfusedDino className='w-40 h-40' />
|
||||
<div className="flex min-h-[60vh] flex-col items-center justify-center gap-5 px-4 text-center">
|
||||
<ConfusedDino className="h-28 w-28 opacity-80" />
|
||||
<div className="space-y-1.5">
|
||||
<h2 className="pb-0 text-2xl font-semibold tracking-tight">Nothing live right now</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Nobody's streaming yet — why not be the first?
|
||||
</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/settings/channel"
|
||||
className="inline-flex h-9 items-center justify-center rounded-md bg-primary px-5 text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
Start streaming
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
{streams.map((stream) => (
|
||||
<Link href={`/${stream.username}`} key={stream.id}>
|
||||
<Card className="overflow-hidden hover:shadow-lg transition-shadow">
|
||||
<CardContent className="p-0">
|
||||
<div className="relative">
|
||||
<Image
|
||||
src={`/api/stream/thumb/${stream.channel.name}`}
|
||||
width={512}
|
||||
height={512}
|
||||
alt={stream.title}
|
||||
className="w-full h-48 object-cover"
|
||||
/>
|
||||
<div className="absolute bottom-2 left-2 bg-red-600 text-white text-xs font-bold px-2 py-1 rounded">
|
||||
LIVE
|
||||
</div>
|
||||
<div className="absolute bottom-2 right-2 bg-black bg-opacity-70 text-white text-xs px-2 py-1 rounded">
|
||||
{stream.viewers} viewers
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<div className="flex items-start">
|
||||
<Avatar className="h-10 w-10 mr-3">
|
||||
<AvatarImage src={stream.channel.pfpUrl} />
|
||||
<AvatarFallback>{stream.channel.name}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<h3 className="font-semibold line-clamp-1">{stream.title}</h3>
|
||||
<p className="text-sm text-muted-foreground">{stream.category}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<div className="p-3 md:p-6">
|
||||
<StreamGrid liveStreams={liveStreams} offlineStreams={offlineStreams} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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';
|
||||
import { SessionProvider } from '@/lib/providers/SessionProvider';
|
||||
@@ -8,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";
|
||||
@@ -18,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",
|
||||
@@ -31,9 +28,12 @@ export default async function RootLayout({
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
const sessionData = await validateRequest();
|
||||
const cookieStore = await cookies();
|
||||
const defaultOpen = cookieStore.get('sidebar:state')?.value === 'true';
|
||||
|
||||
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"
|
||||
@@ -45,16 +45,20 @@ export default async function RootLayout({
|
||||
<NextSSRPlugin
|
||||
routerConfig={extractRouterConfig(ourFileRouter)}
|
||||
/>
|
||||
<ConfirmDialogProvider>
|
||||
<ConfirmDialogProvider defaultOptions={{
|
||||
cancelButton: {
|
||||
variant: 'outline',
|
||||
},
|
||||
}}>
|
||||
<NuqsAdapter>
|
||||
<SidebarProvider>
|
||||
<SidebarProvider defaultOpen={defaultOpen}>
|
||||
<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,114 +1,163 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 220 23.077% 94.902%;
|
||||
--foreground: 233.793 16.022% 35.49%;
|
||||
@config "../../tailwind.config.mts";
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
--muted: 222.857 15.909% 82.745%;
|
||||
--muted-foreground: 233.333 12.796% 41.373%;
|
||||
@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;
|
||||
}
|
||||
|
||||
--popover: 220 23.077% 94.902%;
|
||||
--popover-foreground: 233.793 16.022% 35.49%;
|
||||
@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;
|
||||
}
|
||||
|
||||
--card: 220 23.077% 94.902%;
|
||||
--card-foreground: 233.793 16.022% 35.49%;
|
||||
@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: 225 13.559% 76.863%;
|
||||
--input: 225 13.559% 76.863%;
|
||||
: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: 219.907 91.489% 53.922%;
|
||||
--primary-foreground: 220 23.077% 94.902%;
|
||||
.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: 222.857 15.909% 82.745%;
|
||||
--secondary-foreground: 233.793 16.022% 35.49%;
|
||||
@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: 222.857 15.909% 82.745%;
|
||||
--accent-foreground: 233.793 16.022% 35.49%;
|
||||
|
||||
--destructive: 347.077 86.667% 44.118%;
|
||||
--destructive-foreground: 220 21.951% 91.961%;
|
||||
|
||||
--ring: 233.793 16.022% 35.49%;
|
||||
|
||||
--surface-1: 225 14% 77%;
|
||||
--surface-2: 227 12% 71%;
|
||||
|
||||
--mantle: 220 22% 92%;
|
||||
|
||||
--radius: 0.5rem;
|
||||
|
||||
--sidebar-background: 0 0% 98%;
|
||||
|
||||
--sidebar-foreground: 240 5.3% 26.1%;
|
||||
|
||||
--sidebar-primary: 240 5.9% 10%;
|
||||
|
||||
--sidebar-primary-foreground: 0 0% 98%;
|
||||
|
||||
--sidebar-accent: 240 4.8% 95.9%;
|
||||
|
||||
--sidebar-accent-foreground: 240 5.9% 10%;
|
||||
|
||||
--sidebar-border: 220 13% 91%;
|
||||
|
||||
--sidebar-ring: 217.2 91.2% 59.8%;
|
||||
@keyframes accordion-down {
|
||||
from {
|
||||
height: 0;
|
||||
}
|
||||
to {
|
||||
height: var(--radix-accordion-content-height);
|
||||
}
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: 240 21.053% 14.902%;
|
||||
--foreground: 226.154 63.934% 88.039%;
|
||||
|
||||
--muted: 240 12% 19%;
|
||||
--muted-foreground: 240 12% 69%;
|
||||
|
||||
--popover: 240 21.053% 14.902%;
|
||||
--popover-foreground: 226.154 63.934% 88.039%;
|
||||
|
||||
--card: 240 21.053% 14.902%;
|
||||
--card-foreground: 226.154 63.934% 88.039%;
|
||||
|
||||
--border: 234.286 13.208% 31.176%;
|
||||
--input: 234.286 13.208% 31.176%;
|
||||
|
||||
--primary: 267 84% 81%;
|
||||
--primary-foreground: 267 84% 21%;
|
||||
|
||||
--secondary: 236.842 16.239% 22.941%;
|
||||
--secondary-foreground: 226.154 63.934% 88.039%;
|
||||
|
||||
--accent: 236.842 16.239% 22.941%;
|
||||
--accent-foreground: 226.154 63.934% 88.039%;
|
||||
|
||||
--destructive: 343.269 81.25% 74.902%;
|
||||
--destructive-foreground: 240 21.311% 11.961%;
|
||||
|
||||
--ring: 226.154 63.934% 88.039%;
|
||||
|
||||
--surface-1: 234 13% 31%;
|
||||
--surface-2: 233 12% 39%;
|
||||
|
||||
--mantle: 240 21.311% 11.961%;
|
||||
|
||||
--radius: 0.5rem;
|
||||
|
||||
--sidebar-background: 240 21.311% 11.961%; /* crust - matches mantle var */
|
||||
|
||||
--sidebar-foreground: 226.154 63.934% 88.039%; /* matches main foreground */
|
||||
|
||||
--sidebar-primary: 217.168 91.87% 75.882%; /* matches primary */
|
||||
|
||||
--sidebar-primary-foreground: 240 21.053% 14.902%; /* matches primary-foreground */
|
||||
|
||||
--sidebar-accent: 236.842 16.239% 22.941%; /* matches accent */
|
||||
|
||||
--sidebar-accent-foreground: 226.154 63.934% 88.039%; /* matches accent-foreground */
|
||||
|
||||
--sidebar-border: 234.286 13.208% 31.176%; /* matches border */
|
||||
|
||||
--sidebar-ring: 217.168 91.87% 75.882%; /* matches primary */
|
||||
@keyframes accordion-up {
|
||||
from {
|
||||
height: var(--radix-accordion-content-height);
|
||||
}
|
||||
to {
|
||||
height: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,73 +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; }
|
||||
}
|
||||
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;
|
||||
.scrollbar-hide::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.scrollbar-hide {
|
||||
-ms-overflow-style: none;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
--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 |
@@ -2,8 +2,22 @@ import { NuqsAdapter } from 'nuqs/adapters/next/app';
|
||||
import './globals.css';
|
||||
|
||||
export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
const publicEnv = Object.keys(process.env).reduce((acc, key) => {
|
||||
if (key.startsWith('NEXT_PUBLIC_')) {
|
||||
acc[key] = process.env[key];
|
||||
}
|
||||
return acc;
|
||||
}, {} as Record<string, string | undefined>);
|
||||
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `window.__ENV = ${JSON.stringify(publicEnv)}`,
|
||||
}}
|
||||
/>
|
||||
</head>
|
||||
<NuqsAdapter>
|
||||
<body>
|
||||
<main>{children}</main>
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -9,9 +9,11 @@ import { Message } from './message';
|
||||
import { useMap } from '@uidotdev/usehooks';
|
||||
import { EmojiSearch } from './EmojiSearch';
|
||||
import { useQueryState } from 'nuqs';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function ChatPanel(props: Props) {
|
||||
const { username } = useParams();
|
||||
const channelName = (Array.isArray(username) ? username[0] : username) ?? '';
|
||||
const [grant, setGrant] = useQueryState('grant');
|
||||
const [message, setMessage] = useState('');
|
||||
const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);
|
||||
@@ -21,13 +23,19 @@ export default function ChatPanel(props: Props) {
|
||||
const [emojisToReq, setEmojisToReq] = useState<string[]>([]);
|
||||
const [cursorPosition, setCursorPosition] = useState(0);
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
const [viewer, setViewer] = useState<{ id: string; username: string } | null>(null);
|
||||
const [canModerate, setCanModerate] = useState(false);
|
||||
const [chatAccess, setChatAccess] = useState<ChatAccessState>({
|
||||
canSend: true,
|
||||
restriction: null,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
console.log('Initializing WebSocket connection for user:', username);
|
||||
const socket = new WebSocket(
|
||||
`ws${window.location.protocol === 'https:' ? 's' : ''}://${
|
||||
window.location.host
|
||||
}/api/stream/chat/ws/${username}?grant=${grant}`
|
||||
}/api/stream/chat/ws/${channelName}?grant=${grant}`
|
||||
);
|
||||
socketRef.current = socket;
|
||||
|
||||
@@ -50,6 +58,35 @@ export default function ChatPanel(props: Props) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'session') {
|
||||
setViewer(data.viewer ?? null);
|
||||
setCanModerate(Boolean(data.permissions?.canModerate));
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'chatAccess') {
|
||||
setChatAccess({
|
||||
canSend: Boolean(data.canSend),
|
||||
restriction: data.restriction ?? null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'systemMsg') {
|
||||
setChatMessages((prev) => [...prev, { message: data.message, type: 'systemMsg' }]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'messageDeleted') {
|
||||
setChatMessages((prev) => prev.filter((message) => message.msgId !== data.msgId));
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'moderationError') {
|
||||
toast.error(data.message || 'Message blocked by moderation rules.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'message') {
|
||||
console.log('Adding new chat message:', data);
|
||||
setChatMessages((prev) => [...prev, data]);
|
||||
@@ -72,7 +109,7 @@ export default function ChatPanel(props: Props) {
|
||||
return () => {
|
||||
socket.close();
|
||||
};
|
||||
}, [username]);
|
||||
}, [channelName]);
|
||||
|
||||
useEffect(() => {
|
||||
if (scrollRef.current) {
|
||||
@@ -84,6 +121,14 @@ export default function ChatPanel(props: Props) {
|
||||
}, [chatMessages]);
|
||||
|
||||
const sendMessage = () => {
|
||||
if (!chatAccess.canSend) {
|
||||
toast.error(
|
||||
chatAccess.restriction?.type === 'timeout'
|
||||
? 'You are currently timed out in this chat.'
|
||||
: 'You are currently banned from this chat.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!message.trim()) return;
|
||||
|
||||
if (socketRef.current && socketRef.current.readyState === WebSocket.OPEN) {
|
||||
@@ -93,7 +138,7 @@ export default function ChatPanel(props: Props) {
|
||||
const socket = new WebSocket(
|
||||
`ws${window.location.protocol === 'https:' ? 's' : ''}://${
|
||||
window.location.host
|
||||
}/api/stream/chat/ws/${username}?grant=${grant}`
|
||||
}/api/stream/chat/ws/${channelName}?grant=${grant}`
|
||||
);
|
||||
socket.onopen = () => {
|
||||
socket.send(JSON.stringify({ type: 'message', message }));
|
||||
@@ -102,6 +147,15 @@ export default function ChatPanel(props: Props) {
|
||||
}
|
||||
};
|
||||
|
||||
const sendModerationCommand = (command: ChatModerationCommand) => {
|
||||
if (!socketRef.current || socketRef.current.readyState !== WebSocket.OPEN) {
|
||||
toast.error('Chat connection is offline.');
|
||||
return;
|
||||
}
|
||||
|
||||
socketRef.current.send(JSON.stringify(command));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
if (socketRef.current && socketRef.current.readyState === WebSocket.OPEN) {
|
||||
@@ -146,7 +200,7 @@ export default function ChatPanel(props: Props) {
|
||||
const socket = new WebSocket(
|
||||
`ws${window.location.protocol === 'https:' ? 's' : ''}://${
|
||||
window.location.host
|
||||
}/api/stream/chat/ws/${username}?grant=${grant}`
|
||||
}/api/stream/chat/ws/${channelName}?grant=${grant}`
|
||||
);
|
||||
|
||||
socket.onopen = () => {
|
||||
@@ -209,7 +263,7 @@ export default function ChatPanel(props: Props) {
|
||||
setEmojisToReq([]);
|
||||
};
|
||||
}
|
||||
}, [emojisToReq, emojiMap, username]);
|
||||
}, [emojisToReq, emojiMap, channelName]);
|
||||
|
||||
const handleEmojiSelect = (emojiName: string) => {
|
||||
if (!textareaRef.current) return;
|
||||
@@ -245,9 +299,14 @@ export default function ChatPanel(props: Props) {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`${props.isObsPanel ? 'w-full text-white' : 'md:border bg-mantle w-[350px] max-w-[350px]'} flex flex-col h-full`}>
|
||||
<div ref={scrollRef} className={`flex-1 p-4 ${props.isObsPanel ? 'scrollbar-hide' : ''} overflow-y-auto flex flex-col`}>
|
||||
<div className="space-y-4 flex-1">
|
||||
<div
|
||||
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}
|
||||
className={`flex-1 px-4 py-2 ${props.isObsPanel ? 'scrollbar-hide' : 'scrollbar-thin scrollbar-thumb-border scrollbar-track-transparent'} overflow-y-auto overflow-x-hidden`}
|
||||
>
|
||||
<div className="space-y-1 min-h-full flex flex-col justify-end">
|
||||
{chatMessages.map((msg, i) => (
|
||||
<Message
|
||||
key={i}
|
||||
@@ -255,13 +314,25 @@ export default function ChatPanel(props: Props) {
|
||||
message={msg.message}
|
||||
type={msg.type}
|
||||
emojiMap={emojiMap}
|
||||
msgId={msg.msgId}
|
||||
canModerate={canModerate && Boolean(viewer?.id)}
|
||||
viewerId={viewer?.id}
|
||||
channelName={channelName}
|
||||
onModerationCommand={sendModerationCommand}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{!props.isObsPanel && (
|
||||
<div className="p-4 border-t relative">
|
||||
<div className="flex space-x-2">
|
||||
<div className="p-3 border-t border-border relative">
|
||||
{!chatAccess.canSend && (
|
||||
<p className="mb-2 text-xs text-destructive">
|
||||
{chatAccess.restriction?.type === 'timeout'
|
||||
? `Timed out${chatAccess.restriction.expiresAt ? ` until ${new Date(chatAccess.restriction.expiresAt).toLocaleTimeString()}` : ''}.`
|
||||
: 'You are banned from sending messages in this chat.'}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={message}
|
||||
@@ -281,11 +352,17 @@ export default function ChatPanel(props: Props) {
|
||||
onClick={(e) => {
|
||||
setCursorPosition(e.currentTarget.selectionStart || 0);
|
||||
}}
|
||||
placeholder="Type a message"
|
||||
className="flex-1 bg-transparent focus-visible:ring-offset-0 min-h-[40px] max-h-[120px] resize-none py-2"
|
||||
placeholder="Send a message..."
|
||||
className="flex-1 bg-background/50 border-border focus-visible:ring-1 focus-visible:ring-primary focus-visible:ring-offset-0 min-h-[40px] max-h-[100px] resize-none py-2 text-sm"
|
||||
rows={1}
|
||||
disabled={!chatAccess.canSend}
|
||||
/>
|
||||
<Button size="icon" className="text-black transition-colors" onClick={sendMessage}>
|
||||
<Button
|
||||
size="icon"
|
||||
className="shrink-0 transition-colors"
|
||||
onClick={sendMessage}
|
||||
disabled={!message.trim() || !chatAccess.canSend}
|
||||
>
|
||||
<Send className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -307,6 +384,32 @@ export interface ChatMessage {
|
||||
user?: User;
|
||||
message: string;
|
||||
type: 'message' | 'systemMsg';
|
||||
msgId?: string;
|
||||
}
|
||||
|
||||
export interface ChatModerationCommand {
|
||||
type:
|
||||
| 'mod:deleteMessage'
|
||||
| 'mod:timeoutUser'
|
||||
| 'mod:banUser'
|
||||
| 'mod:unbanUser'
|
||||
| 'mod:liftTimeout';
|
||||
msgId?: string;
|
||||
targetUserId?: string;
|
||||
targetUsername?: string;
|
||||
durationSeconds?: number;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
interface ChatAccessState {
|
||||
canSend: boolean;
|
||||
restriction: ChatRestriction | null;
|
||||
}
|
||||
|
||||
interface ChatRestriction {
|
||||
type: 'timeout' | 'ban';
|
||||
reason?: string;
|
||||
expiresAt?: string | null;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
@@ -315,6 +418,8 @@ export interface User {
|
||||
pfpUrl: string;
|
||||
isBot: boolean;
|
||||
displayName?: string;
|
||||
isPlatformAdmin?: boolean;
|
||||
channelRole?: 'owner' | 'manager' | 'chatModerator' | 'botModerator' | null;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
|
||||
@@ -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({
|
||||
@@ -28,25 +28,27 @@ export function EmojiSearch({
|
||||
useEffect(() => {
|
||||
const beforeCursor = message.substring(0, cursorPosition);
|
||||
const match = beforeCursor.match(/:[\w\-+]*$/);
|
||||
|
||||
|
||||
if (match) {
|
||||
const term = match[0].substring(1);
|
||||
setSearchTerm(term);
|
||||
|
||||
|
||||
if (term.length > 0) {
|
||||
const localResults = Array.from(emojiMap.keys())
|
||||
.filter(name => name.toLowerCase().includes(term.toLowerCase()))
|
||||
.filter((name) => name.toLowerCase().includes(term.toLowerCase()))
|
||||
.slice(0, 5);
|
||||
|
||||
|
||||
if (localResults.length > 0) {
|
||||
setSearchResults(localResults);
|
||||
}
|
||||
|
||||
|
||||
if (socket && socket.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify({
|
||||
type: 'emojiSearch',
|
||||
searchTerm: term
|
||||
}));
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'emojiSearch',
|
||||
searchTerm: term,
|
||||
})
|
||||
);
|
||||
}
|
||||
} else {
|
||||
setSearchResults([]);
|
||||
@@ -63,22 +65,22 @@ export function EmojiSearch({
|
||||
const handleEmojiSearchResponse = (event: MessageEvent) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
|
||||
|
||||
if (data.type === 'emojiSearchResponse') {
|
||||
const serverResults = data.results || [];
|
||||
|
||||
|
||||
const localResults = Array.from(emojiMap.keys())
|
||||
.filter(name => searchTerm && name.toLowerCase().includes(searchTerm.toLowerCase()))
|
||||
.filter((name) => searchTerm && name.toLowerCase().includes(searchTerm.toLowerCase()))
|
||||
.slice(0, 5);
|
||||
|
||||
|
||||
const combinedResults = [...serverResults];
|
||||
|
||||
localResults.forEach(name => {
|
||||
|
||||
localResults.forEach((name) => {
|
||||
if (!combinedResults.includes(name)) {
|
||||
combinedResults.push(name);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
setSearchResults(combinedResults.slice(0, 10));
|
||||
setSelectedIndex(0);
|
||||
}
|
||||
@@ -95,18 +97,18 @@ export function EmojiSearch({
|
||||
|
||||
useEffect(() => {
|
||||
if (!textareaRef.current) return;
|
||||
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (!searchTerm || searchResults.length === 0) return;
|
||||
|
||||
|
||||
switch (e.key) {
|
||||
case 'ArrowDown':
|
||||
e.preventDefault();
|
||||
setSelectedIndex(prev => (prev + 1) % searchResults.length);
|
||||
setSelectedIndex((prev) => (prev + 1) % searchResults.length);
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
e.preventDefault();
|
||||
setSelectedIndex(prev => (prev - 1 + searchResults.length) % searchResults.length);
|
||||
setSelectedIndex((prev) => (prev - 1 + searchResults.length) % searchResults.length);
|
||||
break;
|
||||
case 'Enter':
|
||||
if (searchResults[selectedIndex]) {
|
||||
@@ -127,10 +129,10 @@ export function EmojiSearch({
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const textarea = textareaRef.current;
|
||||
textarea.addEventListener('keydown', handleKeyDown);
|
||||
|
||||
|
||||
return () => {
|
||||
textarea.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
@@ -150,25 +152,25 @@ export function EmojiSearch({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="absolute bottom-16 left-4 bg-mantle border rounded-md shadow-lg max-h-60 overflow-y-auto z-10 min-w-[200px] max-w-[300px]">
|
||||
<div className="absolute bottom-full left-0 right-0 mb-2 mx-0 bg-mantle border border-border rounded-lg shadow-lg max-h-60 overflow-y-auto z-10">
|
||||
<div ref={resultsRef} className="py-1">
|
||||
{searchResults.map((emojiName, index) => {
|
||||
const isSelected = index === selectedIndex;
|
||||
const emojiUrl = emojiMap.get(emojiName);
|
||||
|
||||
|
||||
return (
|
||||
<div
|
||||
key={emojiName}
|
||||
className={`px-3 py-1.5 flex items-center gap-2 cursor-pointer ${
|
||||
className={`px-3 py-2 flex items-center gap-3 cursor-pointer transition-colors ${
|
||||
isSelected ? 'bg-primary/10' : 'hover:bg-primary/5'
|
||||
}`}
|
||||
onClick={() => onSelect(emojiName)}
|
||||
>
|
||||
{emojiUrl && (
|
||||
<Image src={emojiUrl} alt={emojiName} width={20} height={20} className="w-5 h-5" />
|
||||
<Image src={emojiUrl} alt={emojiName} width={24} height={24} className="w-6 h-6" />
|
||||
)}
|
||||
<span className="flex-grow text-sm">{emojiName}</span>
|
||||
{isSelected && <Check className="h-4 w-4 text-blue-500" />}
|
||||
<span className="flex-grow text-sm font-medium">{emojiName}</span>
|
||||
{isSelected && <Check className="h-4 w-4 text-primary" />}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,89 +1,398 @@
|
||||
import { User } from './ChatPanel';
|
||||
import React from 'react';
|
||||
import Image from 'next/image';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { Bot } from 'lucide-react';
|
||||
'use client';
|
||||
|
||||
import { ChatModerationCommand, User } from './ChatPanel';
|
||||
import { useState } from 'react';
|
||||
import Image from 'next/image';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import {
|
||||
Ban,
|
||||
Bot,
|
||||
Clock3,
|
||||
Crown,
|
||||
EllipsisVertical,
|
||||
Eraser,
|
||||
Flag,
|
||||
Shield,
|
||||
ShieldAlert,
|
||||
ShieldCheck,
|
||||
UserRoundCheck,
|
||||
Wrench,
|
||||
} from 'lucide-react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { toast } from 'sonner';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
type ChannelRole = NonNullable<User['channelRole']>;
|
||||
|
||||
const ROLE_META: Record<ChannelRole, { label: string; icon: LucideIcon; className: string }> = {
|
||||
owner: { label: 'Owner', icon: Crown, className: 'text-amber-500' },
|
||||
manager: { label: 'Manager', icon: Wrench, className: 'text-violet-500' },
|
||||
chatModerator: { label: 'Chat Mod', icon: Shield, className: 'text-emerald-500' },
|
||||
botModerator: { label: 'Bot Mod', icon: ShieldCheck, className: 'text-cyan-500' },
|
||||
};
|
||||
|
||||
function TooltipIcon({
|
||||
icon: Icon,
|
||||
label,
|
||||
className,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<Tooltip delayDuration={200}>
|
||||
<TooltipTrigger asChild>
|
||||
<span className={cn('inline-flex align-[-0.15em]', className)}>
|
||||
<Icon className="size-[1.1em] shrink-0" />
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">{label}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function UsernameRow({ user, displayName }: { user?: User; displayName?: string }) {
|
||||
const role = user?.channelRole ? ROLE_META[user.channelRole] : null;
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
{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>
|
||||
);
|
||||
}
|
||||
|
||||
function ReportDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
displayName,
|
||||
message,
|
||||
reportReason,
|
||||
onReasonChange,
|
||||
onSubmit,
|
||||
isSubmitting,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
displayName?: string;
|
||||
message: string;
|
||||
reportReason: string;
|
||||
onReasonChange: (value: string) => void;
|
||||
onSubmit: () => void;
|
||||
isSubmitting: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Report message</DialogTitle>
|
||||
<DialogDescription>
|
||||
Message against Hack Club's Code of Conduct? Let us know!
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-3">
|
||||
<div className="text-sm text-muted-foreground rounded-md border p-3 bg-muted/30">
|
||||
<p className="font-medium text-foreground mb-1">Reported user</p>
|
||||
<p>{displayName}</p>
|
||||
<p className="mt-2 whitespace-pre-wrap break-words">{message}</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Reason</label>
|
||||
<Textarea
|
||||
value={reportReason}
|
||||
onChange={(e) => onReasonChange(e.target.value)}
|
||||
placeholder="Describe why this should be reviewed (harassment, hate speech, spam, threats, etc)."
|
||||
rows={5}
|
||||
className="mt-2"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">Minimum 10 characters.</p>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={onSubmit} disabled={isSubmitting || reportReason.trim().length < 10}>
|
||||
Submit report
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function Message({
|
||||
user,
|
||||
message,
|
||||
type,
|
||||
emojiMap,
|
||||
msgId,
|
||||
canModerate,
|
||||
viewerId,
|
||||
channelName,
|
||||
onModerationCommand,
|
||||
}: MessageProps) {
|
||||
const [reportOpen, setReportOpen] = useState(false);
|
||||
const [reportReason, setReportReason] = useState('');
|
||||
const [isSubmittingReport, setIsSubmittingReport] = useState(false);
|
||||
const displayName = user?.displayName || user?.username;
|
||||
|
||||
export function Message({ user, message, type, emojiMap }: MessageProps) {
|
||||
if (type === 'systemMsg') {
|
||||
return (
|
||||
<div className="flex items-center justify-center">
|
||||
<span className="text-xs text-muted-foreground">{message}</span>
|
||||
<div className="flex items-center justify-center py-1">
|
||||
<span className="text-xs text-muted-foreground italic">{message}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex">
|
||||
<div lang="en" className="max-w-full break-all whitespace-pre-wrap hyphens-auto">
|
||||
<p className="flex flex-wrap items-center">
|
||||
<span className="font-bold mr-2 flex items-center">
|
||||
{user?.isBot && (
|
||||
<span className="text-xs text-muted-foreground flex mr-1">
|
||||
{' '}
|
||||
<Bot className="size-5" />
|
||||
</span>
|
||||
)}
|
||||
{user?.displayName || user?.username}
|
||||
</span>
|
||||
const submitReport = async () => {
|
||||
if (!user?.id || !viewerId || viewerId === user.id) return;
|
||||
|
||||
<EmojiRenderer text={message} emojiMap={emojiMap} />
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const reason = reportReason.trim();
|
||||
if (reason.length < 10) {
|
||||
toast.error('Please include at least 10 characters explaining the report.');
|
||||
return;
|
||||
}
|
||||
|
||||
export function EmojiRenderer({ text, emojiMap }: EmojiRendererProps) {
|
||||
if (!text) return null;
|
||||
setIsSubmittingReport(true);
|
||||
try {
|
||||
const res = await fetch('/api/stream/chat/report', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
channelName,
|
||||
targetUserId: user.id,
|
||||
targetUsername: displayName,
|
||||
msgId,
|
||||
message,
|
||||
reason,
|
||||
}),
|
||||
});
|
||||
|
||||
const parts = text.split(/(:[\w\-+]+:)/g);
|
||||
if (!res.ok) {
|
||||
toast.error((await res.text()) || 'Failed to submit report.');
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success('Report submitted. Thanks for helping keep chat safe.');
|
||||
setReportReason('');
|
||||
setReportOpen(false);
|
||||
} catch {
|
||||
toast.error('Failed to submit report.');
|
||||
} finally {
|
||||
setIsSubmittingReport(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReportOpenChange = (open: boolean) => {
|
||||
setReportOpen(open);
|
||||
if (!open) setReportReason('');
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{parts.map((part, index) => {
|
||||
if (part.match(/^:[\w\-+]+:$/)) {
|
||||
const emojiName = part.replaceAll(':', '');
|
||||
const emojiUrl = emojiMap.get(emojiName);
|
||||
|
||||
if (emojiUrl) {
|
||||
return (
|
||||
<Tooltip key={index} delayDuration={250}>
|
||||
<TooltipTrigger>
|
||||
<span
|
||||
key={index}
|
||||
className="inline-block align-middle"
|
||||
style={{ height: '1.2em' }}
|
||||
>
|
||||
<Image
|
||||
src={emojiUrl}
|
||||
alt={part}
|
||||
width={20}
|
||||
height={20}
|
||||
className="inline-block"
|
||||
/>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{part}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return <span key={index}>{part}</span>;
|
||||
})}
|
||||
<div className="group hover:bg-primary/5 rounded px-2 py-1 -mx-2 transition-colors">
|
||||
<div className="flex items-start gap-1.5">
|
||||
<div
|
||||
lang="en"
|
||||
className="text-foreground min-w-0 flex-1 leading-normal"
|
||||
style={{ overflowWrap: 'anywhere', wordBreak: 'break-word' }}
|
||||
>
|
||||
<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}
|
||||
msgId={msgId}
|
||||
canModerate={canModerate}
|
||||
viewerId={viewerId}
|
||||
onModerationCommand={onModerationCommand}
|
||||
onOpenReport={() => setReportOpen(true)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ReportDialog
|
||||
open={reportOpen}
|
||||
onOpenChange={handleReportOpenChange}
|
||||
displayName={displayName}
|
||||
message={message}
|
||||
reportReason={reportReason}
|
||||
onReasonChange={setReportReason}
|
||||
onSubmit={submitReport}
|
||||
isSubmitting={isSubmittingReport}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function MessageActionsMenu({
|
||||
user,
|
||||
msgId,
|
||||
canModerate,
|
||||
viewerId,
|
||||
onModerationCommand,
|
||||
onOpenReport,
|
||||
}: {
|
||||
user: User;
|
||||
msgId?: string;
|
||||
canModerate?: boolean;
|
||||
viewerId?: string;
|
||||
onModerationCommand?: (command: ChatModerationCommand) => void;
|
||||
onOpenReport: () => void;
|
||||
}) {
|
||||
if (!viewerId || !user.id || user.id === viewerId) return null;
|
||||
|
||||
const displayName = user.displayName || user.username;
|
||||
const canMod = Boolean(canModerate && onModerationCommand);
|
||||
|
||||
const runModeration = (command: ChatModerationCommand) => onModerationCommand?.(command);
|
||||
|
||||
const timeout = (durationSeconds: number) =>
|
||||
runModeration({
|
||||
type: 'mod:timeoutUser',
|
||||
targetUserId: user.id,
|
||||
targetUsername: displayName,
|
||||
durationSeconds,
|
||||
reason: 'Timed out by moderator',
|
||||
});
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-7 w-7 opacity-0 group-hover:opacity-100">
|
||||
<EllipsisVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-52">
|
||||
<DropdownMenuItem onClick={onOpenReport}>
|
||||
<Flag className="mr-2 h-4 w-4" />
|
||||
Report user
|
||||
</DropdownMenuItem>
|
||||
{canMod && (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
onClick={() => msgId && runModeration({ type: 'mod:deleteMessage', msgId })}
|
||||
>
|
||||
<Eraser className="mr-2 h-4 w-4" />
|
||||
Delete message
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => timeout(300)}>
|
||||
<Clock3 className="mr-2 h-4 w-4" />
|
||||
Timeout 5 min
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => timeout(3600)}>
|
||||
<Clock3 className="mr-2 h-4 w-4" />
|
||||
Timeout 1 hour
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
onClick={() =>
|
||||
runModeration({
|
||||
type: 'mod:banUser',
|
||||
targetUserId: user.id,
|
||||
targetUsername: displayName,
|
||||
reason: 'Banned by moderator',
|
||||
})
|
||||
}
|
||||
>
|
||||
<Ban className="mr-2 h-4 w-4" />
|
||||
Ban user
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
runModeration({
|
||||
type: 'mod:liftTimeout',
|
||||
targetUserId: user.id,
|
||||
targetUsername: displayName,
|
||||
})
|
||||
}
|
||||
>
|
||||
<UserRoundCheck className="mr-2 h-4 w-4" />
|
||||
Lift timeout/ban
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmojiRenderer({ text, emojiMap }: { text: string; emojiMap: Map<string, string> }) {
|
||||
if (!text) return null;
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<>
|
||||
{text.split(/(:[\w\-+]+:)/g).map((part, i) => {
|
||||
if (part.match(/^:[\w\-+]+:$/)) {
|
||||
const name = part.replaceAll(':', '');
|
||||
const url = emojiMap.get(name);
|
||||
if (url) {
|
||||
return (
|
||||
<Tooltip key={i} delayDuration={250}>
|
||||
<TooltipTrigger asChild>
|
||||
<span className="inline-flex items-center align-middle mx-0.5">
|
||||
<Image src={url} alt={part} width={20} height={20} className="inline-block" />
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{part}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
}
|
||||
return part ? <span key={i}>{part}</span> : null;
|
||||
})}
|
||||
</>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
interface MessageProps {
|
||||
user?: User;
|
||||
message: string;
|
||||
type: 'message' | 'systemMsg';
|
||||
emojiMap: Map<string, string>;
|
||||
}
|
||||
|
||||
interface EmojiRendererProps {
|
||||
text: string;
|
||||
emojiMap: Map<string, string>;
|
||||
msgId?: string;
|
||||
canModerate?: boolean;
|
||||
viewerId?: string;
|
||||
channelName: string;
|
||||
onModerationCommand?: (command: ChatModerationCommand) => void;
|
||||
}
|
||||
|
||||
@@ -8,22 +8,16 @@ export default function LandingPage() {
|
||||
return (
|
||||
<>
|
||||
<main className="flex-1">
|
||||
{/* Hero Section */}
|
||||
<section className="relative w-full py-20 md:py-32 lg:py-40 xl:py-48 overflow-hidden">
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary/10 via-transparent to-secondary/10"></div>
|
||||
<div className="absolute inset-0"></div>
|
||||
<div className="container px-4 md:px-6 relative">
|
||||
<div className="flex flex-col items-center space-y-8 text-center">
|
||||
<Badge variant="outline" className="px-4 py-2 text-sm font-medium bg-primary/10 text-primary border-primary/20">
|
||||
<Heart className="w-4 h-4 mr-2" />
|
||||
Made with ❤️ by Hack Clubbers
|
||||
</Badge>
|
||||
|
||||
<div className="flex flex-col items-center space-y-8 text-center">
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-4xl font-bold tracking-tight sm:text-5xl md:text-6xl lg:text-7xl bg-gradient-to-r from-primary via-primary/80 to-primary/60 bg-clip-text text-transparent">
|
||||
<h1 className="text-4xl font-bold tracking-tight sm:text-5xl md:text-6xl lg:text-7xl text-primary">
|
||||
hackclub.tv
|
||||
</h1>
|
||||
<p className="mx-auto max-w-[600px] text-lg text-muted-foreground md:text-xl">
|
||||
The streaming platform where Hack Clubbers share their coding journeys, workshops, and hackathon adventures with the world.
|
||||
The streaming website for Hack Clubbers, by Hack Clubbers.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -42,133 +36,6 @@ export default function LandingPage() {
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Features Section */}
|
||||
<section className="w-full py-16 md:py-24 lg:py-32 bg-muted/30" id="features">
|
||||
<div className="container px-4 md:px-6">
|
||||
<div className="flex flex-col items-center text-center space-y-8 mb-16">
|
||||
<Badge variant="secondary" className="px-4 py-2">
|
||||
Platform Features
|
||||
</Badge>
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-3xl font-bold tracking-tight sm:text-4xl md:text-5xl">
|
||||
Built for creators, by creators
|
||||
</h2>
|
||||
<p className="max-w-[700px] text-lg text-muted-foreground">
|
||||
Everything you need to connect, create, and grow within the Hack Club community.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3 max-w-5xl mx-auto">
|
||||
<Card className="border-0 shadow-sm hover:shadow-md transition-shadow">
|
||||
<CardHeader className="pb-4">
|
||||
<div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center mb-4">
|
||||
<Zap className="w-6 h-6 text-primary" />
|
||||
</div>
|
||||
<CardTitle className="text-xl">Low-Latency Streaming</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardDescription className="text-base">
|
||||
Share your coding sessions with ultra-low latency. Your audience stays engaged with real-time interaction.
|
||||
</CardDescription>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-0 shadow-sm hover:shadow-md transition-shadow">
|
||||
<CardHeader className="pb-4">
|
||||
<div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center mb-4">
|
||||
<MessageCircle className="w-6 h-6 text-primary" />
|
||||
</div>
|
||||
<CardTitle className="text-xl">Real-Time Chat</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardDescription className="text-base">
|
||||
Engage with your community through integrated chat. Get instant feedback and build connections.
|
||||
</CardDescription>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-0 shadow-sm hover:shadow-md transition-shadow">
|
||||
<CardHeader className="pb-4">
|
||||
<div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center mb-4">
|
||||
<Users className="w-6 h-6 text-primary" />
|
||||
</div>
|
||||
<CardTitle className="text-xl">Community First</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardDescription className="text-base">
|
||||
Follow your favorite streamers, discover new creators, and be part of the vibrant Hack Club ecosystem.
|
||||
</CardDescription>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-0 shadow-sm hover:shadow-md transition-shadow">
|
||||
<CardHeader className="pb-4">
|
||||
<div className="w-12 h-12 bg-accent/50 rounded-lg flex items-center justify-center mb-4">
|
||||
<Code className="w-6 h-6 text-accent-foreground" />
|
||||
</div>
|
||||
<CardTitle className="text-xl">Code-Focused</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardDescription className="text-base">
|
||||
Built specifically for developers. Perfect for coding sessions, tutorials, and technical workshops.
|
||||
</CardDescription>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-0 shadow-sm hover:shadow-md transition-shadow">
|
||||
<CardHeader className="pb-4">
|
||||
<div className="w-12 h-12 bg-secondary/50 rounded-lg flex items-center justify-center mb-4">
|
||||
<Play className="w-6 h-6 text-secondary-foreground" />
|
||||
</div>
|
||||
<CardTitle className="text-xl">Easy to Use</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardDescription className="text-base">
|
||||
Simple, intuitive interface. Start streaming in minutes, not hours. Focus on what you love: coding.
|
||||
</CardDescription>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-0 shadow-sm hover:shadow-md transition-shadow">
|
||||
<CardHeader className="pb-4">
|
||||
<div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center mb-4">
|
||||
<Heart className="w-6 h-6 text-primary" />
|
||||
</div>
|
||||
<CardTitle className="text-xl">Open Source</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardDescription className="text-base">
|
||||
Transparent, community-driven, and built in the open. Contribute, customize, and make it yours.
|
||||
</CardDescription>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* CTA Section */}
|
||||
<section className="w-full py-16 md:py-24">
|
||||
<div className="container px-4 md:px-6">
|
||||
<div className="flex flex-col items-center text-center space-y-8">
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-3xl font-bold tracking-tight sm:text-4xl">
|
||||
Ready to share your journey?
|
||||
</h2>
|
||||
<p className="max-w-[600px] text-lg text-muted-foreground">
|
||||
Join the community of makers, builders, and dreamers. Start streaming your coding adventures today.
|
||||
</p>
|
||||
</div>
|
||||
<Link href="/login">
|
||||
<Button size="lg" className="px-8 py-3 text-lg font-semibold">
|
||||
<Play className="w-5 h-5 mr-2" />
|
||||
Get Started Now
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,28 +1,98 @@
|
||||
'use client';
|
||||
|
||||
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';
|
||||
import type { StreamInfo, User, Channel } from '@hctv/db';
|
||||
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';
|
||||
|
||||
export default function LiveStream(props: Props) {
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
const { channels, refresh } = useAllChannels(5000);
|
||||
const [isRestricted, setIsRestricted] = useState(props.initialRestrictionActive);
|
||||
const [restrictionExpiresAt, setRestrictionExpiresAt] = useState<string | null>(
|
||||
props.initialRestrictionExpiresAt
|
||||
);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const currentStream = channels.find((s) => s.username === props.username);
|
||||
if (currentStream?.channel?.isRestricted) {
|
||||
setIsRestricted(true);
|
||||
setRestrictionExpiresAt(currentStream.channel.restrictionExpiresAt || null);
|
||||
} else if (isRestricted && currentStream && !currentStream.channel?.isRestricted) {
|
||||
setIsRestricted(false);
|
||||
setRestrictionExpiresAt(null);
|
||||
}
|
||||
}, [channels, props.username, isRestricted]);
|
||||
|
||||
const handleRefresh = async () => {
|
||||
setIsRefreshing(true);
|
||||
try {
|
||||
await refresh();
|
||||
} finally {
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
};
|
||||
|
||||
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>
|
||||
<p className="text-muted-foreground text-center max-w-md mb-4">
|
||||
This channel has been restricted by a moderator and is no longer available for viewing.
|
||||
</p>
|
||||
{restrictionExpiresAt && (
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Restriction lifts: {format(new Date(restrictionExpiresAt), 'PPP p')}
|
||||
</p>
|
||||
)}
|
||||
<Button variant="outline" onClick={handleRefresh} disabled={isRefreshing}>
|
||||
<RefreshCw className={`h-4 w-4 mr-2 ${isRefreshing ? 'animate-spin' : ''}`} />
|
||||
{isRefreshing ? 'Checking...' : 'Check again'}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`${isMobile ? 'flex flex-col' : 'flex'} h-[calc(100vh-64px)] w-full`}>
|
||||
<div className="flex-1 flex flex-col">
|
||||
<StreamPlayer />
|
||||
<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">
|
||||
{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="h-[300px]">
|
||||
<div className="w-full min-w-0 flex-1 min-h-[250px] max-h-[400px] border-t border-border">
|
||||
<ChatPanel />
|
||||
</div>
|
||||
)}
|
||||
<UserInfoCard streamInfo={props.streamInfo} />
|
||||
</div>
|
||||
|
||||
|
||||
{!isMobile && (
|
||||
<div>
|
||||
<div className="h-full shrink-0">
|
||||
<ChatPanel />
|
||||
</div>
|
||||
)}
|
||||
@@ -33,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,91 +15,183 @@ import { logout } from '@/lib/auth/actions';
|
||||
import { useSession } from '@/lib/providers/SessionProvider';
|
||||
import Link from 'next/link';
|
||||
import { ThemeSwitcher } from '../ThemeSwitcher/ThemeSwitcher';
|
||||
import { Slack } 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>
|
||||
</Link>
|
||||
<DropdownMenuSeparator />
|
||||
<Link href={'https://docs.hctv.srizan.dev'} 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}>
|
||||
<Settings className={iconClass} />
|
||||
Bot accounts
|
||||
</DropdownMenuItem>
|
||||
</Link>
|
||||
|
||||
{user.isAdmin && (
|
||||
<div>
|
||||
<DropdownMenuSeparator className="bg-border/40 my-2" />
|
||||
<Link href={`/admin`}>
|
||||
<DropdownMenuItem className={`${menuItemClass} text-primary hover:text-primary`}>
|
||||
<Shield className={`w-4 h-4 mr-3 text-primary`} />
|
||||
Admin Panel
|
||||
</DropdownMenuItem>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
className="cursor-pointer"
|
||||
onClick={() => {
|
||||
logout();
|
||||
}}
|
||||
>
|
||||
Sign out
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuSeparator className="bg-border/40 my-2" />
|
||||
|
||||
<DropdownMenuGroup className="space-y-1">
|
||||
<Link href={'https://docs.hackclub.tv'} target="_blank" rel="noreferrer">
|
||||
<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>
|
||||
|
||||
<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>
|
||||
) : (
|
||||
<Link href="/auth/slack">
|
||||
<Link href="/auth/hackclub">
|
||||
<Button variant="outline" size="sm" className="gap-1 md:gap-2 text-xs md:text-sm">
|
||||
<Slack className="w-3 h-3 md:w-4 md:h-4" />
|
||||
<IdCard className="w-3 h-3 md:w-4 md:h-4" />
|
||||
<span className="hidden sm:inline">Sign in</span>
|
||||
<span className="sm:hidden">Login</span>
|
||||
</Button>
|
||||
|
||||
@@ -1,136 +1,188 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import {
|
||||
Sidebar as UISidebar,
|
||||
SidebarContent,
|
||||
SidebarGroup,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
useSidebar,
|
||||
} from '@/components/ui/sidebar';
|
||||
import { StreamInfoResponse, useStreams } from '@/lib/providers/StreamInfoProvider';
|
||||
import { StreamInfoResponse } from '@/lib/providers/StreamInfoProvider';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { useAllChannels } from '@/lib/hooks/useUserList';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
|
||||
export default function Sidebar({ ...props }: React.ComponentProps<typeof UISidebar>) {
|
||||
const { channels: stream, isLoading } = useAllChannels(5000);
|
||||
const [followedExpanded, setFollowedExpanded] = React.useState(true);
|
||||
const { state } = useSidebar();
|
||||
const isCollapsed = state === 'collapsed';
|
||||
|
||||
if (isLoading) return <SidebarSkeleton />;
|
||||
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 (
|
||||
<UISidebar {...props}>
|
||||
<UISidebar collapsible="icon" {...props}>
|
||||
<SidebarContent>
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel asChild>
|
||||
<button
|
||||
onClick={() => setFollowedExpanded(!followedExpanded)}
|
||||
className="w-full flex items-center justify-between"
|
||||
>
|
||||
<span>Live Channels</span>
|
||||
{followedExpanded ? (
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
<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">
|
||||
Live Channels
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground group-data-[collapsible=icon]:opacity-0 transition-opacity duration-200">
|
||||
{liveStreamers.length}
|
||||
</span>
|
||||
</SidebarGroupLabel>
|
||||
|
||||
{followedExpanded && (
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{liveStreamers.map((streamer) => (
|
||||
<StreamerItem key={streamer.id} streamer={streamer} />
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
)}
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{liveStreamers.length === 0 && !isCollapsed && (
|
||||
<div className="px-4 py-2 text-sm text-muted-foreground">
|
||||
No channels live
|
||||
</div>
|
||||
)}
|
||||
{liveStreamers.map((streamer) => (
|
||||
<StreamerItem key={streamer.id} streamer={streamer} isCollapsed={isCollapsed} />
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
|
||||
{offlineStreamers.length > 0 && (
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel>Offline Channels</SidebarGroupLabel>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{offlineStreamers.map((streamer) => (
|
||||
<StreamerItem key={streamer.id} streamer={streamer} />
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</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>
|
||||
<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">
|
||||
Offline Channels
|
||||
</span>
|
||||
</SidebarGroupLabel>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{offlineStreamers.map((streamer) => (
|
||||
<StreamerItem key={streamer.id} streamer={streamer} isCollapsed={isCollapsed} />
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
</SidebarContent>
|
||||
</UISidebar>
|
||||
);
|
||||
}
|
||||
|
||||
function StreamerItem({ streamer }: { streamer: StreamInfoResponse[0] }) {
|
||||
function StreamerItem({ streamer, isCollapsed }: { streamer: StreamInfoResponse[0], isCollapsed: boolean }) {
|
||||
const router = useRouter();
|
||||
|
||||
return (
|
||||
<SidebarMenuItem key={streamer.id} className={streamer.isLive ? '' : '*:text-muted-foreground'}>
|
||||
<SidebarMenuButton className="flex items-center gap-3 h-full" onClick={() => {
|
||||
router.push(`/${streamer.username}`);
|
||||
}}>
|
||||
<div className="relative">
|
||||
<Avatar className="h-9 w-9">
|
||||
<AvatarImage src={streamer.channel.pfpUrl} alt={streamer.username} />
|
||||
<AvatarFallback>{streamer.username}</AvatarFallback>
|
||||
</Avatar>
|
||||
{streamer.isLive && (
|
||||
<span className="absolute -top-1 -right-1 w-3 h-3 bg-primary rounded-full border-2 border-black" />
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
asChild
|
||||
tooltip={streamer.username}
|
||||
className="h-12"
|
||||
onClick={() => router.push(`/${streamer.username}`)}
|
||||
>
|
||||
<button className="flex w-full items-center gap-3">
|
||||
<div className="relative flex-shrink-0">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={streamer.channel.pfpUrl}
|
||||
alt={streamer.username}
|
||||
className="h-8 w-8 rounded-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
{streamer.isLive && (
|
||||
<span className="absolute -bottom-0.5 -right-0.5 flex h-3 w-3 items-center justify-center rounded-full bg-background ring-2 ring-background">
|
||||
<span className="h-2 w-2 rounded-full bg-red-500 animate-pulse" />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!isCollapsed && (
|
||||
<div className="flex flex-1 flex-col items-start overflow-hidden">
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<span className="truncate font-medium text-sm leading-none">
|
||||
{streamer.username}
|
||||
</span>
|
||||
{streamer.isLive && (
|
||||
<div className="flex items-center gap-1 text-xs text-red-500">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-red-500" />
|
||||
<span>{streamer.viewers}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<span className="truncate text-xs text-muted-foreground w-full text-left">
|
||||
{streamer.isLive ? streamer.title || streamer.category || 'Live' : 'Offline'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<p className="font-medium truncate">{streamer.username}</p>
|
||||
<p className="text-sm truncate">{streamer.category}</p>
|
||||
{streamer.isLive && (
|
||||
<p className="text-sm">
|
||||
{streamer.viewers} viewer{streamer.viewers === 1 ? '' : 's'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarSkeleton({ ...props }: React.ComponentProps<typeof UISidebar>) {
|
||||
const { state } = useSidebar();
|
||||
const isCollapsed = state === 'collapsed';
|
||||
|
||||
return (
|
||||
<UISidebar {...props}>
|
||||
<UISidebar collapsible="icon" {...props}>
|
||||
<SidebarContent>
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel asChild>
|
||||
<button className="w-full flex items-center justify-between">
|
||||
<span>Live Channels</span>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</button>
|
||||
<SidebarGroupLabel className="px-2 py-1.5">
|
||||
<Skeleton className="h-4 w-24 group-data-[collapsible=icon]:opacity-0 transition-opacity duration-200" />
|
||||
</SidebarGroupLabel>
|
||||
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{Array(3).fill(0).map((_, i) => (
|
||||
<StreamerItemSkeleton key={i} />
|
||||
<StreamerItemSkeleton key={i} isCollapsed={isCollapsed} />
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
|
||||
<Separator className="group-data-[collapsible=icon]:block hidden" />
|
||||
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel>Offline Channels</SidebarGroupLabel>
|
||||
<SidebarGroupLabel className="px-2 py-1.5">
|
||||
<Skeleton className="h-4 w-24 group-data-[collapsible=icon]:opacity-0 transition-opacity duration-200" />
|
||||
</SidebarGroupLabel>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{Array(5).fill(0).map((_, i) => (
|
||||
<StreamerItemSkeleton key={i} />
|
||||
<StreamerItemSkeleton key={i} isCollapsed={isCollapsed} />
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
@@ -140,18 +192,20 @@ function SidebarSkeleton({ ...props }: React.ComponentProps<typeof UISidebar>) {
|
||||
);
|
||||
}
|
||||
|
||||
function StreamerItemSkeleton() {
|
||||
function StreamerItemSkeleton({ isCollapsed }: { isCollapsed: boolean }) {
|
||||
return (
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton className="flex items-center gap-3 h-full">
|
||||
<div className="relative">
|
||||
<Skeleton className="h-9 w-9 rounded-full" />
|
||||
</div>
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
<SidebarMenuButton className="h-12">
|
||||
<div className="flex w-full items-center gap-3">
|
||||
<Skeleton className="h-8 w-8 rounded-full flex-shrink-0" />
|
||||
{!isCollapsed && (
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Skeleton className="h-3.5 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
220
apps/web/src/components/app/StreamGrid/StreamGrid.tsx
Normal file
@@ -0,0 +1,220 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import ConfusedDino from '@/components/ui/confuseddino';
|
||||
import {
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
CarouselNext,
|
||||
CarouselPrevious,
|
||||
} from '@/components/ui/carousel';
|
||||
import type { Channel, StreamInfo } from '@hctv/db';
|
||||
|
||||
type StreamWithChannel = StreamInfo & { channel: Channel };
|
||||
|
||||
interface StreamGridProps {
|
||||
liveStreams: StreamWithChannel[];
|
||||
offlineStreams: StreamWithChannel[];
|
||||
}
|
||||
|
||||
export default function StreamGrid({ liveStreams, offlineStreams }: StreamGridProps) {
|
||||
const sortedLiveStreams = liveStreams
|
||||
.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 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">
|
||||
<p className="font-semibold">Nobody's live right now</p>
|
||||
<p className="text-sm text-muted-foreground">Why not be the first?</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/settings/channel"
|
||||
className="inline-flex h-9 items-center justify-center rounded-md bg-primary px-5 text-sm font-medium text-primary-foreground shadow-sm transition-colors hover:bg-primary/90"
|
||||
>
|
||||
Start streaming
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{sortedLiveStreams.length > 0 && (
|
||||
<section>
|
||||
<SectionHeading label="Live now" count={sortedLiveStreams.length} />
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 md:gap-4 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{sortedLiveStreams.map((stream) => (
|
||||
<StreamCard key={stream.id} stream={stream} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{alwaysOnStreams.length > 0 && (
|
||||
<section>
|
||||
<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>
|
||||
))}
|
||||
</CarouselContent>
|
||||
<CarouselPrevious className="hidden md:flex" />
|
||||
<CarouselNext className="hidden md:flex" />
|
||||
</Carousel>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StreamCard({ stream }: { stream: StreamWithChannel }) {
|
||||
return (
|
||||
<Link href={`/${stream.username}`} className="group block w-full max-w-sm">
|
||||
<div className="overflow-hidden rounded-lg border border-border bg-card shadow-sm transition-shadow duration-200 group-hover:shadow-md">
|
||||
<div className="relative aspect-video overflow-hidden bg-muted">
|
||||
<img
|
||||
src={`/api/stream/thumb/${stream.channel.name}`}
|
||||
alt={stream.title}
|
||||
className="absolute inset-0 object-cover"
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent" />
|
||||
{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}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
<AvatarFallback className="text-[10px]">
|
||||
{stream.channel.name.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-xs font-medium leading-snug md:text-sm">{stream.title}</p>
|
||||
<p className="truncate text-[10px] text-muted-foreground md:text-xs">
|
||||
{stream.channel.name}
|
||||
</p>
|
||||
{stream.category && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="mt-1 rounded-full px-1.5 py-0 text-[9px] font-medium md:mt-1.5 md:px-2 md:text-[10px]"
|
||||
>
|
||||
{stream.category}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function OfflineCard({ stream }: { stream: StreamWithChannel }) {
|
||||
return (
|
||||
<Link href={`/${stream.username}`} className="group inline-flex w-[70px]">
|
||||
<div className="flex w-[70px] flex-col items-center gap-1 rounded-lg p-1.5 transition-colors duration-150 hover:bg-muted/50 sm:w-[78px] md:w-[86px] md:gap-1.5 md:p-2">
|
||||
<div className="relative">
|
||||
<Avatar className="h-9 w-9 ring-2 ring-border transition-colors duration-150 group-hover:ring-border/60 sm:h-10 sm:w-10 md:h-11 md:w-11">
|
||||
<AvatarImage
|
||||
src={stream.channel.pfpUrl}
|
||||
alt={stream.channel.name}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
<AvatarFallback className="text-xs font-semibold">
|
||||
{stream.channel.name.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2 border-background bg-muted-foreground/40" />
|
||||
</div>
|
||||
<p className="w-full truncate text-center text-[10px] font-medium">{stream.channel.name}</p>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function LiveBadge({ small }: { small?: boolean }) {
|
||||
return (
|
||||
<span
|
||||
className={`flex items-center gap-1 rounded-full bg-red-600 font-bold uppercase tracking-wide text-white ${small ? 'px-1.5 py-0.5 text-[9px]' : 'px-2 py-0.5 text-[10px]'}`}
|
||||
>
|
||||
<span className="inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-white" />
|
||||
Live
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ViewerCount({ count, small }: { count: number; small?: boolean }) {
|
||||
return (
|
||||
<span
|
||||
className={`flex items-center gap-1 rounded-full bg-black/70 font-medium text-white backdrop-blur-sm ${small ? 'px-1.5 py-0.5 text-[9px]' : 'px-2 py-0.5 text-xs'}`}
|
||||
>
|
||||
<span className="inline-block h-1.5 w-1.5 rounded-full bg-red-400" />
|
||||
{count.toLocaleString()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function SectionHeading({ label, count }: { label: string; count?: number }) {
|
||||
return (
|
||||
<div className="mb-3 flex items-center gap-2">
|
||||
<h2 className="pb-0 text-sm font-semibold tracking-tight md:text-base">{label}</h2>
|
||||
{count !== undefined && (
|
||||
<span className="rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
|
||||
{count}
|
||||
</span>
|
||||
)}
|
||||
<div className="ml-2 h-px flex-1 bg-border" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,69 +1,218 @@
|
||||
'use client';
|
||||
|
||||
import { useParams } from 'next/navigation';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
MediaController,
|
||||
MediaLoadingIndicator,
|
||||
MediaControlBar,
|
||||
MediaPlayButton,
|
||||
MediaSeekBackwardButton,
|
||||
MediaSeekForwardButton,
|
||||
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 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 && streamSrc && session) {
|
||||
const user = 'skibiditoilet';
|
||||
const credentials = btoa(`${user}:${session.id}`);
|
||||
|
||||
video.config = {
|
||||
xhrSetup: (xhr: XMLHttpRequest) => {
|
||||
xhr.setRequestHeader('Authorization', `Basic ${credentials}`);
|
||||
},
|
||||
lowLatencyMode: true,
|
||||
debug: process.env.NODE_ENV === 'development',
|
||||
backBufferLength: 90,
|
||||
enableWorker: true,
|
||||
maxLiveSyncPlaybackRate: 1,
|
||||
liveSyncDurationCount: 2,
|
||||
liveMaxLatencyDurationCount: 4,
|
||||
};
|
||||
|
||||
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) {
|
||||
clearWaitingTimeout();
|
||||
video.removeAttribute('src');
|
||||
video.load();
|
||||
}
|
||||
};
|
||||
}, [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
|
||||
src={`/api/rtmp/hls/${username}.m3u8`}
|
||||
slot="media"
|
||||
crossOrigin="anonymous"
|
||||
autoplay
|
||||
config={{
|
||||
lowLatencyMode: true,
|
||||
liveSyncDurationCount: 1,
|
||||
liveMaxLatencyDurationCount: 2,
|
||||
liveDurationInfinity: true,
|
||||
enableWorker: true,
|
||||
backBufferLength: 1,
|
||||
startLevel: -1,
|
||||
maxBufferLength: 2,
|
||||
maxMaxBufferLength: 4,
|
||||
startFragPrefetch: true,
|
||||
testBandwidth: false,
|
||||
progressive: false,
|
||||
maxBufferSize: 10 * 1000 * 1000,
|
||||
maxBufferHole: 0.1,
|
||||
highBufferWatchdogPeriod: 0.5,
|
||||
nudgeOffset: 0.01,
|
||||
nudgeMaxRetry: 3,
|
||||
manifestLoadingTimeOut: 3000,
|
||||
manifestLoadingMaxRetry: 3,
|
||||
levelLoadingTimeOut: 3000,
|
||||
fragLoadingTimeOut: 5000,
|
||||
debug: process.env.NODE_ENV === 'development',
|
||||
liveSyncDuration: 1,
|
||||
liveMaxLatencyDuration: 3,
|
||||
maxLiveSyncPlaybackRate: 1.5,
|
||||
liveBackBufferLength: 0,
|
||||
}}
|
||||
/>
|
||||
<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';
|
||||
@@ -21,7 +20,14 @@ import { Textarea } from '@/components/ui/textarea';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
createBotSchema,
|
||||
createChannelSchema, editBotSchema, onboardSchema, streamInfoEditSchema, updateChannelSettingsSchema
|
||||
createChannelSchema,
|
||||
changeUsernameSchema,
|
||||
editBotSchema,
|
||||
onboardSchema,
|
||||
streamInfoEditSchema,
|
||||
updateChatModerationSchema,
|
||||
updateChannelSettingsSchema,
|
||||
updateNotificationChannelsSchema,
|
||||
} from '@/lib/form/zod';
|
||||
|
||||
export const schemaDb = [
|
||||
@@ -30,20 +36,24 @@ export const schemaDb = [
|
||||
{ name: 'createChannel', zod: createChannelSchema },
|
||||
{ name: 'updateChannelSettings', zod: updateChannelSettingsSchema },
|
||||
{ name: 'createBot', zod: createBotSchema },
|
||||
{ name: 'editBot', zod: editBotSchema }
|
||||
{ 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;
|
||||
@@ -61,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(() => {
|
||||
@@ -79,15 +87,15 @@ 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>
|
||||
{(field.type !== 'hidden' || field.label) && <FormLabel>{field.label}</FormLabel>}
|
||||
<FormItem className={field.type === 'hidden' ? 'hidden' : undefined}>
|
||||
{field.type !== 'hidden' && field.label && <FormLabel>{field.label}</FormLabel>}
|
||||
<FormControl>
|
||||
{field.component ? (
|
||||
field.component({ field: formField, ...field.componentProps })
|
||||
@@ -97,27 +105,37 @@ export function UniversalForm<T extends z.ZodType>({
|
||||
{...formField}
|
||||
value={formField.value ?? ''}
|
||||
rows={field.textAreaRows ?? 5}
|
||||
maxLength={field.maxChars}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
type={field.type || 'text'}
|
||||
placeholder={field.placeholder}
|
||||
{...formField}
|
||||
onChange={(e) => {
|
||||
if (field.inputFilter) {
|
||||
e.target.value = e.target.value.replace(field.inputFilter, '');
|
||||
}
|
||||
formField.onChange(e);
|
||||
}}
|
||||
value={formField.value ?? ''}
|
||||
maxLength={field.maxChars}
|
||||
/>
|
||||
)}
|
||||
</FormControl>
|
||||
{field.description && <FormDescription>{field.description}</FormDescription>}
|
||||
<FormMessage />
|
||||
{field.type !== 'hidden' && field.description && (
|
||||
<FormDescription>{field.description}</FormDescription>
|
||||
)}
|
||||
{field.type !== 'hidden' && <FormMessage />}
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
<div className={cn("flex gap-2 py-2", submitButtonDivClassname)}>
|
||||
<div className={cn('flex gap-2 py-2', submitButtonDivClassname)}>
|
||||
{otherSubmitButton}
|
||||
<SubmitButton buttonText={submitText} className={submitClassname} />
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,30 +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;
|
||||
component?: (props: { field: ControllerRenderProps<any, any> } & any) => React.ReactNode;
|
||||
maxChars?: number;
|
||||
inputFilter?: RegExp;
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2,12 +2,13 @@ import { Avatar, AvatarImage } from '@/components/ui/avatar';
|
||||
import type { StreamInfo, Channel } from '@hctv/db';
|
||||
import FollowButton from './follow';
|
||||
import FollowCountText from './followCount';
|
||||
import StreamUptime from './streamUptime';
|
||||
import ViewerCount from './viewerCount';
|
||||
import { Preview } from '@/components/ui/channel-desc-fancy-area/preview';
|
||||
|
||||
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">
|
||||
@@ -21,6 +22,7 @@ export default function UserInfoCard(props: Props) {
|
||||
</div>
|
||||
<div className="flex items-center space-x-4">
|
||||
<ViewerCount />
|
||||
<StreamUptime />
|
||||
<FollowButton channel={props.streamInfo.username} />
|
||||
</div>
|
||||
</div>
|
||||
@@ -33,4 +35,4 @@ export default function UserInfoCard(props: Props) {
|
||||
|
||||
interface Props {
|
||||
streamInfo: StreamInfo & { channel: Channel };
|
||||
}
|
||||
}
|
||||
|
||||
55
apps/web/src/components/app/UserInfoCard/streamUptime.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Clock3 } from 'lucide-react';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { useStreams } from '@/lib/providers/StreamInfoProvider';
|
||||
|
||||
export default function StreamUptime() {
|
||||
const { stream, isLoading } = useStreams();
|
||||
const { username } = useParams<{ username: string }>();
|
||||
const [now, setNow] = useState(Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(() => {
|
||||
setNow(Date.now());
|
||||
}, 1000);
|
||||
|
||||
return () => {
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const startedAt = useMemo(() => {
|
||||
if (!stream || !username) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentStream = stream.find((entry) => entry.username === username);
|
||||
if (!currentStream?.isLive) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Date(currentStream.startedAt).getTime();
|
||||
}, [stream, username]);
|
||||
|
||||
if (isLoading || !startedAt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const elapsedSeconds = Math.max(0, Math.floor((now - startedAt) / 1000));
|
||||
const hours = Math.floor(elapsedSeconds / 3600)
|
||||
.toString()
|
||||
.padStart(2, '0');
|
||||
const minutes = Math.floor((elapsedSeconds % 3600) / 60)
|
||||
.toString()
|
||||
.padStart(2, '0');
|
||||
const seconds = (elapsedSeconds % 60).toString().padStart(2, '0');
|
||||
|
||||
return (
|
||||
<div className="flex items-center space-x-2 text-sm text-muted-foreground">
|
||||
<Clock3 className="h-4 w-4" />
|
||||
<span>{`${hours}:${minutes}:${seconds}`}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,8 @@ const buttonVariants = cva(
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
lg: "h-11 rounded-md px-8",
|
||||
icon: "h-10 w-10"
|
||||
icon: "h-10 w-10",
|
||||
smicon: "h-9 w-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
|
||||
213
apps/web/src/components/ui/calendar.tsx
Normal file
@@ -0,0 +1,213 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
} from "lucide-react"
|
||||
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
|
||||
function Calendar({
|
||||
className,
|
||||
classNames,
|
||||
showOutsideDays = true,
|
||||
captionLayout = "label",
|
||||
buttonVariant = "ghost",
|
||||
formatters,
|
||||
components,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayPicker> & {
|
||||
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||
}) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
return (
|
||||
<DayPicker
|
||||
showOutsideDays={showOutsideDays}
|
||||
className={cn(
|
||||
"bg-background group/calendar p-3 [--cell-size:2rem] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
|
||||
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||
className
|
||||
)}
|
||||
captionLayout={captionLayout}
|
||||
formatters={{
|
||||
formatMonthDropdown: (date) =>
|
||||
date.toLocaleString("default", { month: "short" }),
|
||||
...formatters,
|
||||
}}
|
||||
classNames={{
|
||||
root: cn("w-fit", defaultClassNames.root),
|
||||
months: cn(
|
||||
"relative flex flex-col gap-4 md:flex-row",
|
||||
defaultClassNames.months
|
||||
),
|
||||
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
|
||||
nav: cn(
|
||||
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
|
||||
defaultClassNames.nav
|
||||
),
|
||||
button_previous: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"h-[--cell-size] w-[--cell-size] select-none p-0 aria-disabled:opacity-50",
|
||||
defaultClassNames.button_previous
|
||||
),
|
||||
button_next: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"h-[--cell-size] w-[--cell-size] select-none p-0 aria-disabled:opacity-50",
|
||||
defaultClassNames.button_next
|
||||
),
|
||||
month_caption: cn(
|
||||
"flex h-[--cell-size] w-full items-center justify-center px-[--cell-size]",
|
||||
defaultClassNames.month_caption
|
||||
),
|
||||
dropdowns: cn(
|
||||
"flex h-[--cell-size] w-full items-center justify-center gap-1.5 text-sm font-medium",
|
||||
defaultClassNames.dropdowns
|
||||
),
|
||||
dropdown_root: cn(
|
||||
"has-focus:border-ring border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] relative rounded-md border",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn(
|
||||
"bg-popover absolute inset-0 opacity-0",
|
||||
defaultClassNames.dropdown
|
||||
),
|
||||
caption_label: cn(
|
||||
"select-none font-medium",
|
||||
captionLayout === "label"
|
||||
? "text-sm"
|
||||
: "[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md pl-2 pr-1 text-sm [&>svg]:size-3.5",
|
||||
defaultClassNames.caption_label
|
||||
),
|
||||
table: "w-full border-collapse",
|
||||
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||
weekday: cn(
|
||||
"text-muted-foreground flex-1 select-none rounded-md text-[0.8rem] font-normal",
|
||||
defaultClassNames.weekday
|
||||
),
|
||||
week: cn("mt-2 flex w-full", defaultClassNames.week),
|
||||
week_number_header: cn(
|
||||
"w-[--cell-size] select-none",
|
||||
defaultClassNames.week_number_header
|
||||
),
|
||||
week_number: cn(
|
||||
"text-muted-foreground select-none text-[0.8rem]",
|
||||
defaultClassNames.week_number
|
||||
),
|
||||
day: cn(
|
||||
"group/day relative aspect-square h-full w-full select-none p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md",
|
||||
defaultClassNames.day
|
||||
),
|
||||
range_start: cn(
|
||||
"bg-accent rounded-l-md",
|
||||
defaultClassNames.range_start
|
||||
),
|
||||
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||
range_end: cn("bg-accent rounded-r-md", defaultClassNames.range_end),
|
||||
today: cn(
|
||||
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
|
||||
defaultClassNames.today
|
||||
),
|
||||
outside: cn(
|
||||
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||
defaultClassNames.outside
|
||||
),
|
||||
disabled: cn(
|
||||
"text-muted-foreground opacity-50",
|
||||
defaultClassNames.disabled
|
||||
),
|
||||
hidden: cn("invisible", defaultClassNames.hidden),
|
||||
...classNames,
|
||||
}}
|
||||
components={{
|
||||
Root: ({ className, rootRef, ...props }) => {
|
||||
return (
|
||||
<div
|
||||
data-slot="calendar"
|
||||
ref={rootRef}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
},
|
||||
Chevron: ({ className, orientation, ...props }) => {
|
||||
if (orientation === "left") {
|
||||
return (
|
||||
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
if (orientation === "right") {
|
||||
return (
|
||||
<ChevronRightIcon
|
||||
className={cn("size-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
},
|
||||
DayButton: CalendarDayButton,
|
||||
WeekNumber: ({ children, ...props }) => {
|
||||
return (
|
||||
<td {...props}>
|
||||
<div className="flex size-[--cell-size] items-center justify-center text-center">
|
||||
{children}
|
||||
</div>
|
||||
</td>
|
||||
)
|
||||
},
|
||||
...components,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CalendarDayButton({
|
||||
className,
|
||||
day,
|
||||
modifiers,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayButton>) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
const ref = React.useRef<HTMLButtonElement>(null)
|
||||
React.useEffect(() => {
|
||||
if (modifiers.focused) ref.current?.focus()
|
||||
}, [modifiers.focused])
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
data-day={day.date.toLocaleDateString()}
|
||||
data-selected-single={
|
||||
modifiers.selected &&
|
||||
!modifiers.range_start &&
|
||||
!modifiers.range_end &&
|
||||
!modifiers.range_middle
|
||||
}
|
||||
data-range-start={modifiers.range_start}
|
||||
data-range-end={modifiers.range_end}
|
||||
data-range-middle={modifiers.range_middle}
|
||||
className={cn(
|
||||
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 flex aspect-square h-auto w-full min-w-[--cell-size] flex-col gap-1 font-normal leading-none data-[range-end=true]:rounded-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] [&>span]:text-xs [&>span]:opacity-70",
|
||||
defaultClassNames.day,
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Calendar, CalendarDayButton }
|
||||
262
apps/web/src/components/ui/carousel.tsx
Normal file
@@ -0,0 +1,262 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import useEmblaCarousel, {
|
||||
type UseEmblaCarouselType,
|
||||
} from "embla-carousel-react"
|
||||
import { ArrowLeft, ArrowRight } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
type CarouselApi = UseEmblaCarouselType[1]
|
||||
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
|
||||
type CarouselOptions = UseCarouselParameters[0]
|
||||
type CarouselPlugin = UseCarouselParameters[1]
|
||||
|
||||
type CarouselProps = {
|
||||
opts?: CarouselOptions
|
||||
plugins?: CarouselPlugin
|
||||
orientation?: "horizontal" | "vertical"
|
||||
setApi?: (api: CarouselApi) => void
|
||||
}
|
||||
|
||||
type CarouselContextProps = {
|
||||
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
|
||||
api: ReturnType<typeof useEmblaCarousel>[1]
|
||||
scrollPrev: () => void
|
||||
scrollNext: () => void
|
||||
canScrollPrev: boolean
|
||||
canScrollNext: boolean
|
||||
} & CarouselProps
|
||||
|
||||
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
|
||||
|
||||
function useCarousel() {
|
||||
const context = React.useContext(CarouselContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useCarousel must be used within a <Carousel />")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
const Carousel = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement> & CarouselProps
|
||||
>(
|
||||
(
|
||||
{
|
||||
orientation = "horizontal",
|
||||
opts,
|
||||
setApi,
|
||||
plugins,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const [carouselRef, api] = useEmblaCarousel(
|
||||
{
|
||||
...opts,
|
||||
axis: orientation === "horizontal" ? "x" : "y",
|
||||
},
|
||||
plugins
|
||||
)
|
||||
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
|
||||
const [canScrollNext, setCanScrollNext] = React.useState(false)
|
||||
|
||||
const onSelect = React.useCallback((api: CarouselApi) => {
|
||||
if (!api) {
|
||||
return
|
||||
}
|
||||
|
||||
setCanScrollPrev(api.canScrollPrev())
|
||||
setCanScrollNext(api.canScrollNext())
|
||||
}, [])
|
||||
|
||||
const scrollPrev = React.useCallback(() => {
|
||||
api?.scrollPrev()
|
||||
}, [api])
|
||||
|
||||
const scrollNext = React.useCallback(() => {
|
||||
api?.scrollNext()
|
||||
}, [api])
|
||||
|
||||
const handleKeyDown = React.useCallback(
|
||||
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (event.key === "ArrowLeft") {
|
||||
event.preventDefault()
|
||||
scrollPrev()
|
||||
} else if (event.key === "ArrowRight") {
|
||||
event.preventDefault()
|
||||
scrollNext()
|
||||
}
|
||||
},
|
||||
[scrollPrev, scrollNext]
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api || !setApi) {
|
||||
return
|
||||
}
|
||||
|
||||
setApi(api)
|
||||
}, [api, setApi])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api) {
|
||||
return
|
||||
}
|
||||
|
||||
onSelect(api)
|
||||
api.on("reInit", onSelect)
|
||||
api.on("select", onSelect)
|
||||
|
||||
return () => {
|
||||
api?.off("select", onSelect)
|
||||
}
|
||||
}, [api, onSelect])
|
||||
|
||||
return (
|
||||
<CarouselContext.Provider
|
||||
value={{
|
||||
carouselRef,
|
||||
api: api,
|
||||
opts,
|
||||
orientation:
|
||||
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
|
||||
scrollPrev,
|
||||
scrollNext,
|
||||
canScrollPrev,
|
||||
canScrollNext,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={ref}
|
||||
onKeyDownCapture={handleKeyDown}
|
||||
className={cn("relative", className)}
|
||||
role="region"
|
||||
aria-roledescription="carousel"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</CarouselContext.Provider>
|
||||
)
|
||||
}
|
||||
)
|
||||
Carousel.displayName = "Carousel"
|
||||
|
||||
const CarouselContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { carouselRef, orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div ref={carouselRef} className="overflow-hidden">
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex",
|
||||
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
CarouselContent.displayName = "CarouselContent"
|
||||
|
||||
const CarouselItem = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
role="group"
|
||||
aria-roledescription="slide"
|
||||
className={cn(
|
||||
"min-w-0 shrink-0 grow-0 basis-full",
|
||||
orientation === "horizontal" ? "pl-4" : "pt-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
CarouselItem.displayName = "CarouselItem"
|
||||
|
||||
const CarouselPrevious = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<typeof Button>
|
||||
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
|
||||
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute h-8 w-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "-left-12 top-1/2 -translate-y-1/2"
|
||||
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollPrev}
|
||||
onClick={scrollPrev}
|
||||
{...props}
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
<span className="sr-only">Previous slide</span>
|
||||
</Button>
|
||||
)
|
||||
})
|
||||
CarouselPrevious.displayName = "CarouselPrevious"
|
||||
|
||||
const CarouselNext = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<typeof Button>
|
||||
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
|
||||
const { orientation, scrollNext, canScrollNext } = useCarousel()
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute h-8 w-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "-right-12 top-1/2 -translate-y-1/2"
|
||||
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollNext}
|
||||
onClick={scrollNext}
|
||||
{...props}
|
||||
>
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
<span className="sr-only">Next slide</span>
|
||||
</Button>
|
||||
)
|
||||
})
|
||||
CarouselNext.displayName = "CarouselNext"
|
||||
|
||||
export {
|
||||
type CarouselApi,
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
CarouselPrevious,
|
||||
CarouselNext,
|
||||
}
|
||||
@@ -37,7 +37,7 @@ export function Mention({ children, handle }: Props) {
|
||||
}
|
||||
|
||||
const fallback = handle.substring(0, 2).toUpperCase();
|
||||
const url = `https://hctv.srizan.dev/${handle}`;
|
||||
const url = `https://hackclub.tv/${handle}`;
|
||||
|
||||
return (
|
||||
<HoverCard>
|
||||
|
||||
@@ -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]);
|
||||
|
||||
@@ -23,7 +23,7 @@ const SIDEBAR_COOKIE_NAME = "sidebar:state"
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
|
||||
const SIDEBAR_WIDTH = "16rem"
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
const SIDEBAR_WIDTH_ICON = "4rem"
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
|
||||
type SidebarContext = {
|
||||
@@ -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}
|
||||
@@ -512,13 +512,13 @@ const SidebarMenuItem = React.forwardRef<
|
||||
SidebarMenuItem.displayName = "SidebarMenuItem"
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-12 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
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={
|
||||
{
|
||||
|
||||
@@ -6,6 +6,7 @@ export async function register() {
|
||||
if (process.env.NEXT_RUNTIME === 'nodejs') {
|
||||
await (await import('@/lib/instrumentation/streamInfo')).default();
|
||||
await (await import('@/lib/instrumentation/writeSessions')).default();
|
||||
await (await import('@/lib/instrumentation/syncStreamKeys')).default();
|
||||
}
|
||||
|
||||
if (process.env.NEXT_RUNTIME === 'nodejs') {
|
||||
|
||||
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 |