Compare commits
452 Commits
feat/nginx
...
renovate/s
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7fc090c272 | ||
| 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 | |||
| 17f550ce9d | |||
| ebd0a8bffd | |||
| 2298b8bc0c | |||
| 7dd9bf765e | |||
| 8b3df28f1e | |||
| ecca138257 | |||
| cb0f75dfb9 | |||
| 747af0aeb3 | |||
| 64c7a80883 | |||
| e8fdfa8f49 | |||
| 9e965c779f | |||
| 9ce6770115 | |||
| 6d413bc53e | |||
| 93ae6bd73e | |||
| ae99121af6 | |||
| 331a0185af | |||
| d223902a9f | |||
| 18a00bba6e | |||
| 061d1d3348 | |||
| 95ec96fe72 | |||
| 9eca54cbb5 | |||
| 31fa5f36de | |||
| d327da90ef | |||
| 7072b762d8 | |||
| 82a13007c8 | |||
| a35fd858dc | |||
| 4f03f002ab | |||
| d36e590ab6 | |||
| c77d7a16e6 | |||
| d656d0f579 | |||
| 2896cae2bb | |||
| 6710423b92 | |||
| a4f940b990 | |||
| 307b697ac9 | |||
| 49c0da708a | |||
| 4c415dacc4 | |||
| e616ac20d4 | |||
| 387f0943a3 | |||
| a22937793c | |||
| 302e9be737 | |||
| d5d8894f9c | |||
| c10b4b3674 | |||
| c18cdc83b9 | |||
| 6e10da6f98 | |||
| 6a7b449363 | |||
| ab72dacb61 | |||
| 31d27f92ca | |||
| cd685edd78 | |||
| bd7047d19b | |||
| 9a7c72321d | |||
| 8d6e097f94 | |||
| 3fbb2b5d7f | |||
| 834e5087c3 | |||
| 2e2185568d | |||
| 451952e3f8 | |||
| f236086dba | |||
| d4e09389ad | |||
| 2b078c9c1e | |||
| 74461398c5 | |||
| 41ad53b531 | |||
| 2dc28ae8d9 | |||
| 1fa8c59c33 | |||
| 4237b1b41b | |||
| 54e3d120f6 | |||
| ed5f29824c | |||
| f4e809ae83 | |||
| cb7f6b0676 | |||
| f46fd35980 | |||
| 9b8e83d2e2 | |||
| c89a3bed87 | |||
| ed1fd6a18e | |||
| 79fe992f6c | |||
| 3b684c2cfd | |||
| a0ef59e577 | |||
| ff91e4b8d6 | |||
| 0ef38f0270 | |||
| a1d849092b | |||
| 87961cd18f | |||
| c0ff5912e4 | |||
| 21f7c0fb82 | |||
| a7a046abd8 | |||
| be5576c2c6 | |||
| 78fe930771 | |||
| 28061a83b0 | |||
| 877fd490bc | |||
| 9305b62e2a | |||
| c7d3a4bf1f | |||
| 92429c1390 | |||
| f7ae4cecf4 | |||
| a3d6d587e5 | |||
| cd90281cf9 | |||
| 5366116e26 | |||
| 12daf61c5b | |||
| db01e3bb59 | |||
| 3aa7cd0c87 | |||
| 818566b1c5 | |||
| 338254889a | |||
| 3029de4fae | |||
| 87ba1c0f3a | |||
| d2e2d0ce62 | |||
| 47fdbf66f9 | |||
| 7e26ffb2d1 | |||
| f45d604468 | |||
| 67989a694c | |||
| 10c10b6d2a | |||
| 6218d328cd | |||
| 02ebaa2914 | |||
| 212e0ea8a0 | |||
| 172a0f887f | |||
| 1048c822ac | |||
| 40d4fb7b09 | |||
| c22e653528 | |||
| 26c2a0b320 | |||
| efb84fe1f9 | |||
| 6268e85fce | |||
| e77e750b0a | |||
| ee1ef27be5 | |||
| 87d7e5752b | |||
| ee442f27de | |||
| 71890520cb | |||
| a5768cfe0a | |||
| 17228d20be | |||
| 502e60d85d | |||
| 752dc641b3 | |||
| 1b384de455 | |||
| d39d6f8ed7 | |||
| 18d69a6aab | |||
| 648d3296e2 | |||
| 836b5b6951 | |||
| e83d0cf713 | |||
| 6974a78201 | |||
| 185fc910a0 | |||
| 6406df0501 | |||
| 30d3ad2f2d | |||
| dd16124cb5 | |||
| 6a63fe388e | |||
| 441aa64166 | |||
| 41c50a8ee5 | |||
| ede61678aa | |||
| f2c0abbcdc | |||
| fbdb43e6df | |||
| 6b82975350 | |||
| 72d49df94c | |||
| 9d88f32f6a | |||
| 59b07928c6 | |||
| 9d6bcf25b9 | |||
| 981b0b8b77 | |||
| e57312e48f | |||
| e736375d17 | |||
| fe3a146bf1 | |||
| f216ddc57d | |||
| bd29c4848d | |||
| 089b1fd157 | |||
| 679a741155 | |||
| 021962b78b | |||
|
|
9c2b166b8a | ||
|
|
b935be00f0 | ||
| b7484bbfa1 | |||
| ab6652f2c7 | |||
| 5e1609abc2 | |||
| 9538d23ed1 | |||
| ed81b494f7 | |||
| 7af4137ff9 | |||
| c702db9121 | |||
| 95e821727b | |||
| a9924d19e4 | |||
| acd5f5b5f4 | |||
|
|
10db7d5833 | ||
| 51d8e8b6ad | |||
| b470c33e9d | |||
| 5751ad1c64 | |||
| 6289b73498 | |||
| 10a7cc5ed5 | |||
| 23a1ed1624 | |||
| 4fd76deb98 | |||
| 9837cbb713 |
@@ -1,34 +1,41 @@
|
||||
# Ignore node_modules and build output
|
||||
node_modules
|
||||
.next
|
||||
out
|
||||
|
||||
# Ignore logs and temporary files
|
||||
*.log
|
||||
*.tmp
|
||||
*.swp
|
||||
|
||||
# Ignore local environment files
|
||||
.env
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
# Ignore Docker files
|
||||
Dockerfile
|
||||
docker-compose.yml
|
||||
|
||||
# Ignore git files
|
||||
# Version control
|
||||
.git
|
||||
.gitignore
|
||||
|
||||
# Dependencies
|
||||
**/node_modules
|
||||
.pnpm-store
|
||||
|
||||
# Build outputs
|
||||
**/dist
|
||||
**/.next
|
||||
**/build
|
||||
**/out
|
||||
|
||||
# Development files
|
||||
**/.env*
|
||||
!**/.env.example
|
||||
**/.vscode
|
||||
**/.idea
|
||||
**/coverage
|
||||
**/.turbo
|
||||
**/.cache
|
||||
|
||||
# System files
|
||||
.DS_Store
|
||||
**/Thumbs.db
|
||||
|
||||
# Logs
|
||||
**/npm-debug.log*
|
||||
**/yarn-debug.log*
|
||||
**/yarn-error.log*
|
||||
**/pnpm-debug.log*
|
||||
|
||||
# Test files
|
||||
**/__tests__
|
||||
**/*.test.*
|
||||
**/*.spec.*
|
||||
|
||||
# Ignore editor directories and files
|
||||
.vscode
|
||||
.idea
|
||||
*.sublime-project
|
||||
*.sublime-workspace
|
||||
|
||||
# Ignore other unnecessary files
|
||||
README.md
|
||||
dev/
|
||||
packages/db/generated
|
||||
dev/
|
||||
flv-module/
|
||||
140
.github/workflows/docker.yml
vendored
Normal file
@@ -0,0 +1,140 @@
|
||||
name: Publish Docker image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
frontend:
|
||||
name: Push frontend to Docker Hub
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Wait
|
||||
uses: NathanFirmo/wait-for-other-action@v1.0.4
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
workflow: 'emojis.yml'
|
||||
|
||||
- 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
|
||||
tags: latest
|
||||
|
||||
- name: Download latest emoji importer
|
||||
run: |
|
||||
RELEASE_URL=$(curl -s https://api.github.com/repos/srizan10/hctv/releases/latest | \
|
||||
grep "browser_download_url.*slack-import-emojis-linux-x86_64" | \
|
||||
cut -d '"' -f 4)
|
||||
|
||||
curl -L -o slack-import-emojis-bin $RELEASE_URL
|
||||
chmod +x slack-import-emojis-bin
|
||||
|
||||
mkdir -p apps/web/src/lib/instrumentation/
|
||||
|
||||
./slack-import-emojis-bin default
|
||||
|
||||
cp emojis.json apps/web/
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./apps/web/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
|
||||
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-chat
|
||||
tags: latest
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./apps/chat/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 }}
|
||||
mediamtx:
|
||||
name: Push MediaMTX image to Docker Hub
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
|
||||
with:
|
||||
images: srizan10/hclive-mediamtx
|
||||
tags: latest
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./docker/mediamtx/Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
platforms: linux/amd64
|
||||
deploy:
|
||||
name: Deploy to Coolify
|
||||
runs-on: ubuntu-latest
|
||||
needs: [frontend, chat, 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
|
||||
64
.github/workflows/emojis.yml
vendored
Normal file
@@ -0,0 +1,64 @@
|
||||
name: Slack Emoji Importer Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'slack-import-emojis/**'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-and-release:
|
||||
name: Build and create release
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ./slack-import-emojis
|
||||
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
workspaces: "./slack-import-emojis -> target"
|
||||
|
||||
- name: Build release binary
|
||||
run: cargo build --release
|
||||
|
||||
- name: Extract version from Cargo.toml
|
||||
id: get_version
|
||||
run: |
|
||||
VERSION=$(grep '^version =' Cargo.toml | head -n 1 | cut -d '"' -f 2)
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create GitHub Release
|
||||
id: create_release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
tag_name: emoji-importer-v${{ steps.get_version.outputs.version }}
|
||||
name: Slack Emoji Importer v${{ steps.get_version.outputs.version }}
|
||||
body: |
|
||||
Slack Emoji Importer v${{ steps.get_version.outputs.version }}
|
||||
|
||||
Fetches emojis from the Slack workspace and exports them to JSON.
|
||||
|
||||
## Usage
|
||||
```
|
||||
export SLACK_TOKEN=xoxb-your-token
|
||||
./slack-import-emojis
|
||||
```
|
||||
|
||||
- name: Upload Linux binary
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: ./slack-import-emojis/target/release/slack-import-emojis
|
||||
asset_name: slack-import-emojis-linux-x86_64
|
||||
asset_content_type: application/octet-stream
|
||||
24
.gitignore
vendored
@@ -1,7 +1,7 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
*node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
.yarn/install-state.gz
|
||||
@@ -10,7 +10,7 @@
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
*.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
@@ -27,7 +27,8 @@ yarn-error.log*
|
||||
|
||||
# local env files
|
||||
.env*.local
|
||||
.env
|
||||
.env*
|
||||
!.env.example
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
@@ -37,5 +38,18 @@ yarn-error.log*
|
||||
next-env.d.ts
|
||||
|
||||
certificates
|
||||
dev/
|
||||
!dev/docker-compose.yml
|
||||
dev/psql
|
||||
dev/redis
|
||||
|
||||
.turbo
|
||||
packages/db/generated/client
|
||||
*dist
|
||||
|
||||
slack-import-emojis/target
|
||||
**/*/emojis.json
|
||||
|
||||
.idea
|
||||
|
||||
/apps/docs/src/content/docs/typedoc-sdk
|
||||
|
||||
.codex
|
||||
8
.vscode/mcp.json
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"servers": {
|
||||
"Sentry": {
|
||||
"url": "https://mcp.sentry.dev/mcp/sr-izan/hctv",
|
||||
"type": "http"
|
||||
}
|
||||
}
|
||||
}
|
||||
343
AGENTS.md
Normal file
@@ -0,0 +1,343 @@
|
||||
# Agent Guidelines for HackClub.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
|
||||
45
Dockerfile
@@ -1,45 +0,0 @@
|
||||
# Stage 1: Building the code
|
||||
FROM node:lts-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files
|
||||
COPY package.json yarn.lock ./
|
||||
|
||||
# Install dependencies
|
||||
RUN yarn install --frozen-lockfile
|
||||
|
||||
# Copy app files
|
||||
COPY . .
|
||||
|
||||
# Build app
|
||||
RUN yarn build
|
||||
|
||||
# Stage 2: Production
|
||||
FROM node:lts-alpine AS runner
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
||||
# Copy necessary files
|
||||
COPY --from=builder /app/next.config.mjs ./
|
||||
COPY --from=builder /app/package.json ./
|
||||
COPY --from=builder /app/yarn.lock ./
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder /app/.next ./.next
|
||||
COPY --from=builder /app/prisma ./prisma
|
||||
|
||||
# Install production dependencies only
|
||||
RUN apk add --no-cache openssl
|
||||
RUN yarn install --frozen-lockfile --production && \
|
||||
yarn cache clean
|
||||
|
||||
# Remove unnecessary files
|
||||
RUN rm -rf /app/.git \
|
||||
/app/.next/cache \
|
||||
/app/README.md
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["yarn", "start"]
|
||||
674
LICENSE
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
25
README.md
@@ -1,24 +1,11 @@
|
||||
# Sr Izan Stack
|
||||
# hackclub.tv
|
||||
|
||||
Sr Izan Stack is a next.js template which runs on modern technologies, with a focus on developer experience and ease-of-use.
|
||||
This is the source code for [hackclub.tv](https://hackclub.tv), a livestreaming website for Hack Clubbers.
|
||||
|
||||
## The stack
|
||||
The development setup guide can be read at <https://docs.hackclub.tv/guides/dev/>
|
||||
|
||||
- Framework: [Next.js](https://nextjs.org/)
|
||||
- Language: [TypeScript](https://www.typescriptlang.org/)
|
||||
- Styling: [Tailwind CSS](https://tailwindcss.com/)
|
||||
- UI Library: [shadcn/ui](https://ui.shadcn.com)
|
||||
- Authentication: [Lucia](https://lucia-auth.com)
|
||||
- Deployment: [Vercel](https://vercel.com)
|
||||
- Database: [Supabase Postgres](https://supabase.com) with [Prisma](https://www.prisma.io/)
|
||||
Join [#hctv](https://hackclub.slack.com/archives/C08HGLXGXAB) on the Hack Club Slack for discussion and updates!
|
||||
|
||||
## Why (insert tool here)?
|
||||
## Streaming
|
||||
|
||||
- **Next.js**: I like the next.js app router because it has a very good developer experience and it's very easy to use.
|
||||
- **TypeScript**: Don't even need to explain why
|
||||
- **Tailwind CSS**: I like the utility-first approach and the speed of development it provides
|
||||
- **shadcn/ui**: Copy-pasting components is so fire (also is Radix UI)
|
||||
- **Lucia**: The DevEX is amazing and it's very easy to use
|
||||
- **Vercel**: Next.js and Vercel are like bread and butter, but it's a bit slow with the free tier.
|
||||
- **MongoDB Atlas**: It has a very generous free tier, and I'm choosing NoSQL because Postgres hates me.
|
||||
- **Prisma**: Even though there are solid competitors like Drizzle, Prisma is easy to use, understand, and fast enough for my use case.
|
||||
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/>.
|
||||
28
apps/chat/.gitignore
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
# dev
|
||||
.yarn/
|
||||
!.yarn/releases
|
||||
.vscode/*
|
||||
!.vscode/launch.json
|
||||
!.vscode/*.code-snippets
|
||||
.idea/workspace.xml
|
||||
.idea/usage.statistics.xml
|
||||
.idea/shelf
|
||||
|
||||
# deps
|
||||
node_modules/
|
||||
|
||||
# env
|
||||
.env
|
||||
.env.production
|
||||
|
||||
# logs
|
||||
logs/
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
47
apps/chat/Dockerfile
Normal file
@@ -0,0 +1,47 @@
|
||||
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 pnpm add -g turbo@^2
|
||||
COPY . .
|
||||
|
||||
RUN turbo prune @hctv/chat --docker
|
||||
|
||||
FROM base AS installer
|
||||
RUN apk update
|
||||
RUN apk add --no-cache libc6-compat
|
||||
WORKDIR /app
|
||||
|
||||
# First install the dependencies
|
||||
COPY --from=builder /app/out/json/ .
|
||||
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) pnpm turbo run build --concurrency=1
|
||||
|
||||
FROM base AS runner
|
||||
WORKDIR /app
|
||||
|
||||
RUN apk add --no-cache curl
|
||||
|
||||
RUN addgroup --system --gid 1001 nodejs
|
||||
RUN adduser --system --uid 1001 nodeapp
|
||||
USER nodeapp
|
||||
|
||||
COPY --from=installer --chown=nodeapp:nodejs /app/apps ./apps
|
||||
COPY --from=installer --chown=nodeapp:nodejs /app/packages ./packages
|
||||
COPY --from=installer --chown=nodeapp:nodejs /app/node_modules ./node_modules
|
||||
COPY --from=installer --chown=nodeapp:nodejs /app/package.json ./package.json
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
||||
WORKDIR /app/apps/chat
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
ENTRYPOINT ["node", "dist/index.js"]
|
||||
25
apps/chat/package.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "@hctv/chat",
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc --build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@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.12.16",
|
||||
"prom-client": "^15.1.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.6.0",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^6.0.3"
|
||||
}
|
||||
}
|
||||
15
apps/chat/src/3d.txt
Normal file
@@ -0,0 +1,15 @@
|
||||
,---, ___
|
||||
,--.' | ,--.'|_
|
||||
| | : | | :,'
|
||||
: : : : : ' : .---.
|
||||
: | |,--. ,---. .;__,' / /. ./|
|
||||
| : ' | / \| | | .-' . ' |
|
||||
| | /' : / / ':__,'| : /___/ \: |
|
||||
' : | | |. ' / ' : |__. \ ' .
|
||||
| | ' | :' ; :__ | | '.'|\ \ '
|
||||
| : :_:,'' | '.'| ; : ; \ \
|
||||
| | ,' | : : | , / \ \ |
|
||||
`--'' \ \ / ---`-' '---"
|
||||
`----'
|
||||
|
||||
This is hctv's chat backend. There's not much here, so go back to where you came from :)
|
||||
891
apps/chat/src/index.ts
Normal file
@@ -0,0 +1,891 @@
|
||||
import { serve } from '@hono/node-server';
|
||||
import { createNodeWebSocket } from '@hctv/hono-ws';
|
||||
import { Hono } from 'hono';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { lucia } from '@hctv/auth';
|
||||
import { getCookie } from 'hono/cookie';
|
||||
import {
|
||||
chatMetricsRegistry,
|
||||
recordChatConnectionAccepted,
|
||||
recordChatConnectionRejected,
|
||||
recordChatDisconnect,
|
||||
recordChatError,
|
||||
recordChatModerationBlock,
|
||||
recordDeliveredChatMessage,
|
||||
recordDeliveredChatMessageBytes,
|
||||
recordEmojiSearchResults,
|
||||
recordHistoryMessagesLoaded,
|
||||
recordIncomingChatMessage,
|
||||
recordUniqueChatter,
|
||||
setChannelHistorySize,
|
||||
setChatModerationState,
|
||||
startChatMessageTimer,
|
||||
} from './metrics.js';
|
||||
import { getPersonalChannel } from './utils/personalChannel.js';
|
||||
import { ChatModerationAction, getRedisConnection, prisma } from '@hctv/db';
|
||||
import uFuzzy from '@leeoniya/ufuzzy';
|
||||
import {
|
||||
handleDeleteMessageCommand,
|
||||
handleUserRestrictionCommand,
|
||||
sendModerationError,
|
||||
} from './utils/moderation.js';
|
||||
import { randomString } from './utils/randomString.js';
|
||||
import type {
|
||||
ChatModerationCommand,
|
||||
ChatModerationSettingsShape,
|
||||
ChatRestrictionState,
|
||||
ChatSocket,
|
||||
ChatUser,
|
||||
} from './types/chat.js';
|
||||
import { basicAuth } from 'hono/basic-auth';
|
||||
|
||||
const redis = getRedisConnection();
|
||||
const MESSAGE_HISTORY_SIZE = 100;
|
||||
const MESSAGE_TTL = 60 * 60 * 24;
|
||||
const MODERATION_SETTINGS_CACHE_TTL_SECONDS = 30;
|
||||
const threed = await readFile('./src/3d.txt', 'utf-8');
|
||||
const uf = new uFuzzy();
|
||||
|
||||
type IncomingMessage = {
|
||||
type?: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
const METRICS_MESSAGE_TYPES = [
|
||||
'ping',
|
||||
'message',
|
||||
'emojiMsg',
|
||||
'emojiSearch',
|
||||
'mod:deleteMessage',
|
||||
'mod:timeoutUser',
|
||||
'mod:banUser',
|
||||
'mod:unbanUser',
|
||||
'mod:liftTimeout',
|
||||
] as const;
|
||||
|
||||
type MetricsMessageType = (typeof METRICS_MESSAGE_TYPES)[number] | 'unknown';
|
||||
|
||||
function getMetricsMessageType(type: unknown): MetricsMessageType {
|
||||
if (typeof type !== 'string') {
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
return (METRICS_MESSAGE_TYPES as readonly string[]).includes(type)
|
||||
? (type as MetricsMessageType)
|
||||
: 'unknown';
|
||||
}
|
||||
|
||||
const DEFAULT_MODERATION_SETTINGS: ChatModerationSettingsShape = {
|
||||
blockedTerms: [],
|
||||
slowModeSeconds: 0,
|
||||
maxMessageLength: 400,
|
||||
rateLimitCount: 8,
|
||||
rateLimitWindowSeconds: 10,
|
||||
};
|
||||
|
||||
function normalizeModerationSettings(
|
||||
settings?: Partial<ChatModerationSettingsShape> | null
|
||||
): ChatModerationSettingsShape {
|
||||
return {
|
||||
blockedTerms:
|
||||
settings?.blockedTerms
|
||||
?.map((term) => term.trim().toLowerCase())
|
||||
.filter((term) => term.length >= 2)
|
||||
.slice(0, 200) ?? [],
|
||||
slowModeSeconds: Math.min(Math.max(settings?.slowModeSeconds ?? 0, 0), 120),
|
||||
maxMessageLength: Math.min(Math.max(settings?.maxMessageLength ?? 50, 50), 2000),
|
||||
rateLimitCount: Math.min(Math.max(settings?.rateLimitCount ?? 8, 3), 30),
|
||||
rateLimitWindowSeconds: Math.min(Math.max(settings?.rateLimitWindowSeconds ?? 10, 5), 60),
|
||||
};
|
||||
}
|
||||
|
||||
function escapeRegExp(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
function containsBlockedTerm(message: string, blockedTerms: string[]): string | null {
|
||||
const normalizedMessage = message.toLowerCase();
|
||||
|
||||
for (const term of blockedTerms) {
|
||||
const regex = new RegExp(`(^|\\W)${escapeRegExp(term)}($|\\W)`, 'i');
|
||||
if (regex.test(normalizedMessage)) {
|
||||
return term;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function getCachedModerationSettings(
|
||||
channelId: string
|
||||
): Promise<ChatModerationSettingsShape> {
|
||||
const cacheKey = `chat:moderation:settings:${channelId}`;
|
||||
const cachedSettings = await redis.get(cacheKey);
|
||||
|
||||
if (cachedSettings) {
|
||||
try {
|
||||
return normalizeModerationSettings(JSON.parse(cachedSettings));
|
||||
} catch {
|
||||
await redis.del(cacheKey);
|
||||
}
|
||||
}
|
||||
|
||||
const dbSettings = await prisma.chatModerationSettings.findUnique({
|
||||
where: { channelId },
|
||||
select: {
|
||||
blockedTerms: true,
|
||||
slowModeSeconds: true,
|
||||
maxMessageLength: true,
|
||||
rateLimitCount: true,
|
||||
rateLimitWindowSeconds: true,
|
||||
},
|
||||
});
|
||||
|
||||
const normalized = normalizeModerationSettings(dbSettings ?? DEFAULT_MODERATION_SETTINGS);
|
||||
await redis.setex(cacheKey, MODERATION_SETTINGS_CACHE_TTL_SECONDS, JSON.stringify(normalized));
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function resolveSocketState(socket: ChatSocket): ChatSocket {
|
||||
return (socket.raw as unknown as ChatSocket | undefined) ?? socket;
|
||||
}
|
||||
|
||||
function broadcastToChannel(
|
||||
targetUsername: string,
|
||||
ws: ChatSocket,
|
||||
payload: Record<string, unknown>
|
||||
) {
|
||||
ws.wss.clients.forEach((clientSocket: unknown) => {
|
||||
const client = clientSocket as ChatSocket;
|
||||
const clientState = resolveSocketState(client);
|
||||
if (client.readyState === client.OPEN && clientState.targetUsername === targetUsername) {
|
||||
client.send(JSON.stringify(payload));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function getActiveRestriction(
|
||||
channelId: string,
|
||||
userId: string
|
||||
): Promise<ChatRestrictionState | null> {
|
||||
const activeBan = await prisma.chatUserBan.findUnique({
|
||||
where: {
|
||||
channelId_userId: {
|
||||
channelId,
|
||||
userId,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
reason: true,
|
||||
expiresAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!activeBan) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (activeBan.expiresAt && activeBan.expiresAt < new Date()) {
|
||||
await prisma.chatUserBan.delete({
|
||||
where: {
|
||||
channelId_userId: {
|
||||
channelId,
|
||||
userId,
|
||||
},
|
||||
},
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
type: activeBan.expiresAt ? 'timeout' : 'ban',
|
||||
reason: activeBan.reason,
|
||||
expiresAt: activeBan.expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
async function sendChatAccessState(socket: ChatSocket, channelId: string, userId: string) {
|
||||
const restriction = await getActiveRestriction(channelId, userId);
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'chatAccess',
|
||||
canSend: !restriction,
|
||||
restriction,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async function broadcastRestrictionStateToUser(
|
||||
targetUsername: string,
|
||||
targetUserId: string,
|
||||
channelId: string,
|
||||
ws: ChatSocket
|
||||
) {
|
||||
const restriction = await getActiveRestriction(channelId, targetUserId);
|
||||
ws.wss.clients.forEach((clientSocket: unknown) => {
|
||||
const client = clientSocket as ChatSocket;
|
||||
const clientState = resolveSocketState(client);
|
||||
if (
|
||||
client.readyState === client.OPEN &&
|
||||
clientState.targetUsername === targetUsername &&
|
||||
clientState.chatUser?.id === targetUserId
|
||||
) {
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
type: 'chatAccess',
|
||||
canSend: !restriction,
|
||||
restriction,
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const RATE_LIMIT_LUA = `
|
||||
local current = redis.call('INCR', KEYS[1])
|
||||
if current == 1 then
|
||||
redis.call('EXPIRE', KEYS[1], ARGV[1])
|
||||
end
|
||||
return current
|
||||
`;
|
||||
|
||||
async function isRateLimited(
|
||||
channelId: string,
|
||||
userId: string,
|
||||
count: number,
|
||||
windowSeconds: number
|
||||
): Promise<boolean> {
|
||||
const key = `chat:ratelimit:${channelId}:${userId}`;
|
||||
const currentCount = (await redis.eval(RATE_LIMIT_LUA, 1, key, String(windowSeconds))) as number;
|
||||
return currentCount > count;
|
||||
}
|
||||
|
||||
async function logModerationEvent(payload: {
|
||||
action: ChatModerationAction;
|
||||
channelId: string;
|
||||
moderatorId: string;
|
||||
targetUserId?: string;
|
||||
reason?: string;
|
||||
details?: Record<string, unknown>;
|
||||
}) {
|
||||
await prisma.chatModerationEvent.create({
|
||||
data: {
|
||||
action: payload.action,
|
||||
channelId: payload.channelId,
|
||||
moderatorId: payload.moderatorId,
|
||||
targetUserId: payload.targetUserId,
|
||||
reason: payload.reason,
|
||||
details: payload.details as any,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteMessageFromHistory(
|
||||
targetUsername: string,
|
||||
msgId: string
|
||||
): Promise<{ deleted: boolean; messageContent?: string }> {
|
||||
const channelKey = `chat:history:${targetUsername}`;
|
||||
const history = await redis.zrange(channelKey, 0, -1);
|
||||
|
||||
for (const entry of history) {
|
||||
try {
|
||||
const parsed = JSON.parse(entry) as { msgId?: string; message?: string };
|
||||
if (parsed.msgId === msgId) {
|
||||
await redis.zrem(channelKey, entry);
|
||||
return {
|
||||
deleted: true,
|
||||
messageContent:
|
||||
typeof parsed.message === 'string' && parsed.message.length > 0
|
||||
? parsed.message
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return { deleted: false };
|
||||
}
|
||||
|
||||
const app = new Hono();
|
||||
const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
app.use(
|
||||
'/metrics',
|
||||
basicAuth({ username: process.env.METRICS_USER!, password: process.env.METRICS_PASSWORD! })
|
||||
);
|
||||
}
|
||||
|
||||
app.get('/', async (c) => {
|
||||
return c.text(threed);
|
||||
});
|
||||
|
||||
app.get('/up', async (c) => {
|
||||
return c.text('hello world');
|
||||
});
|
||||
|
||||
app.get('/metrics', async () => {
|
||||
return new Response(await chatMetricsRegistry.metrics(), {
|
||||
headers: {
|
||||
'Content-Type': chatMetricsRegistry.contentType,
|
||||
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.get(
|
||||
'/ws/:username',
|
||||
upgradeWebSocket((c) => ({
|
||||
async onOpen(evt, ws) {
|
||||
let authMethod = 'unknown';
|
||||
const token = getCookie(c, 'auth_session');
|
||||
const grant = c.req.query('grant');
|
||||
const authHeader = c.req.header('Authorization');
|
||||
const botAuth = c.req.query('botAuth');
|
||||
|
||||
if (!token && (!grant || grant === 'null') && !authHeader && !botAuth) {
|
||||
recordChatConnectionRejected(authMethod, 'missing_auth');
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
|
||||
let chatUser: ChatUser | null = null;
|
||||
let personalChannel: any = null;
|
||||
|
||||
let apiKey: string | null = null;
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
const extractedKey = authHeader.substring(7);
|
||||
if (extractedKey.startsWith('hctvb_')) {
|
||||
apiKey = extractedKey;
|
||||
}
|
||||
} else if (botAuth && typeof botAuth === 'string' && botAuth.trim().length > 0) {
|
||||
if (botAuth.startsWith('hctvb_')) {
|
||||
apiKey = botAuth;
|
||||
}
|
||||
}
|
||||
|
||||
if (apiKey) {
|
||||
const botAccount = await prisma.botApiKey.findUnique({
|
||||
where: { key: apiKey },
|
||||
include: { botAccount: true },
|
||||
});
|
||||
|
||||
if (botAccount) {
|
||||
authMethod = 'bot_api_key';
|
||||
chatUser = {
|
||||
id: botAccount.botAccount.id,
|
||||
username: botAccount.botAccount.slug,
|
||||
pfpUrl: botAccount.botAccount.pfpUrl,
|
||||
displayName: botAccount.botAccount.displayName,
|
||||
isBot: true,
|
||||
moderatorUserId: botAccount.botAccount.ownerId,
|
||||
isPlatformAdmin: false,
|
||||
channelRole: null,
|
||||
};
|
||||
|
||||
personalChannel = {
|
||||
id: botAccount.botAccount.id,
|
||||
name: botAccount.botAccount.slug,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (!chatUser && token) {
|
||||
const session = await lucia.validateSession(token);
|
||||
if (session.user) {
|
||||
const userChannel = await getPersonalChannel(session.user.id);
|
||||
if (userChannel) {
|
||||
authMethod = 'session';
|
||||
chatUser = {
|
||||
id: session.user.id,
|
||||
username: userChannel.name,
|
||||
pfpUrl: session.user.pfpUrl,
|
||||
isBot: false,
|
||||
moderatorUserId: session.user.id,
|
||||
isPlatformAdmin: Boolean(session.user.isAdmin),
|
||||
channelRole: null,
|
||||
};
|
||||
personalChannel = userChannel;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const dbGrant =
|
||||
grant && grant !== 'null'
|
||||
? await prisma.channel.findFirst({
|
||||
where: { obsChatGrantToken: grant },
|
||||
})
|
||||
: null;
|
||||
|
||||
if (!chatUser && !dbGrant) {
|
||||
recordChatConnectionRejected(authMethod, 'auth_failed');
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
|
||||
const { username } = c.req.param();
|
||||
if (!chatUser && dbGrant) {
|
||||
authMethod = 'obs_grant';
|
||||
}
|
||||
|
||||
if (dbGrant && dbGrant.name !== username) {
|
||||
recordChatConnectionRejected(authMethod, 'grant_mismatch');
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { name: username },
|
||||
select: {
|
||||
id: true,
|
||||
ownerId: true,
|
||||
managers: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
chatModerators: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
chatModeratorBots: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
recordChatConnectionRejected(authMethod, 'channel_not_found');
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
|
||||
let channelRole: ChatUser['channelRole'] = null;
|
||||
const activeChatUser = chatUser;
|
||||
if (activeChatUser) {
|
||||
if (activeChatUser.isBot) {
|
||||
if (channel.chatModeratorBots.some((bot) => bot.id === activeChatUser.id)) {
|
||||
channelRole = 'botModerator';
|
||||
}
|
||||
} else if (channel.ownerId === activeChatUser.id) {
|
||||
channelRole = 'owner';
|
||||
} else if (channel.managers.some((manager) => manager.id === activeChatUser.id)) {
|
||||
channelRole = 'manager';
|
||||
} else if (channel.chatModerators.some((moderator) => moderator.id === activeChatUser.id)) {
|
||||
channelRole = 'chatModerator';
|
||||
}
|
||||
}
|
||||
|
||||
if (chatUser) {
|
||||
const moderatorUser = await prisma.user.findUnique({
|
||||
where: { id: chatUser.moderatorUserId },
|
||||
select: { isAdmin: true },
|
||||
});
|
||||
|
||||
chatUser = {
|
||||
...chatUser,
|
||||
isPlatformAdmin: chatUser.isBot ? false : Boolean(moderatorUser?.isAdmin),
|
||||
channelRole,
|
||||
};
|
||||
}
|
||||
|
||||
const isModerator = Boolean(
|
||||
chatUser &&
|
||||
(chatUser.isPlatformAdmin ||
|
||||
chatUser.channelRole === 'owner' ||
|
||||
chatUser.channelRole === 'manager' ||
|
||||
chatUser.channelRole === 'chatModerator' ||
|
||||
chatUser.channelRole === 'botModerator')
|
||||
);
|
||||
|
||||
const moderationSettings = await getCachedModerationSettings(channel.id);
|
||||
|
||||
const socket = ws as unknown as ChatSocket;
|
||||
const socketState = resolveSocketState(socket);
|
||||
|
||||
socket.targetUsername = username;
|
||||
socket.channelId = channel.id;
|
||||
socket.chatUser = chatUser;
|
||||
socket.personalChannel = personalChannel;
|
||||
socket.viewerId = randomString(10);
|
||||
socket.isModerator = isModerator;
|
||||
socket.excludeFromViewerCount = Boolean(dbGrant);
|
||||
|
||||
socketState.targetUsername = username;
|
||||
socketState.channelId = channel.id;
|
||||
socketState.chatUser = chatUser;
|
||||
socketState.personalChannel = personalChannel;
|
||||
socketState.viewerId = socket.viewerId;
|
||||
socketState.isModerator = isModerator;
|
||||
socket.metricsTracked = true;
|
||||
socketState.metricsTracked = true;
|
||||
socket.metricsAuthMethod = authMethod;
|
||||
socketState.metricsAuthMethod = authMethod;
|
||||
|
||||
recordChatConnectionAccepted(username, authMethod);
|
||||
setChatModerationState(username, {
|
||||
blockedTerms: moderationSettings.blockedTerms.length,
|
||||
maxMessageLength: moderationSettings.maxMessageLength,
|
||||
rateLimitCount: moderationSettings.rateLimitCount,
|
||||
rateLimitWindowSeconds: moderationSettings.rateLimitWindowSeconds,
|
||||
slowModeSeconds: moderationSettings.slowModeSeconds,
|
||||
});
|
||||
|
||||
socketState.excludeFromViewerCount = Boolean(dbGrant);
|
||||
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'session',
|
||||
viewer: chatUser
|
||||
? {
|
||||
id: chatUser.id,
|
||||
username: chatUser.username,
|
||||
}
|
||||
: null,
|
||||
permissions: {
|
||||
canModerate: isModerator,
|
||||
},
|
||||
moderation: {
|
||||
hasBlockedTerms: moderationSettings.blockedTerms.length > 0,
|
||||
slowModeSeconds: moderationSettings.slowModeSeconds,
|
||||
maxMessageLength: moderationSettings.maxMessageLength,
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
if (chatUser && !chatUser.isBot) {
|
||||
await sendChatAccessState(socket, channel.id, chatUser.id);
|
||||
}
|
||||
|
||||
const channelKey = `chat:history:${username}`;
|
||||
const messages = await redis.zrange(channelKey, 0, MESSAGE_HISTORY_SIZE - 1);
|
||||
|
||||
if (messages.length > 0) {
|
||||
recordHistoryMessagesLoaded(username, messages.length);
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'history',
|
||||
messages: messages.map((msg) => JSON.parse(msg)),
|
||||
})
|
||||
);
|
||||
}
|
||||
setChannelHistorySize(username, messages.length);
|
||||
},
|
||||
async onClose(evt, ws) {
|
||||
const socket = ws as unknown as ChatSocket;
|
||||
const socketState = resolveSocketState(socket);
|
||||
if (process.env.NODE_ENV !== 'production') console.log('client disconnected');
|
||||
if (!socketState.targetUsername) return;
|
||||
|
||||
if (socketState.metricsTracked) {
|
||||
recordChatDisconnect(
|
||||
socketState.targetUsername,
|
||||
socketState.metricsAuthMethod ?? 'unknown'
|
||||
);
|
||||
socketState.metricsTracked = false;
|
||||
}
|
||||
|
||||
const streamInfo = await prisma.streamInfo.findUnique({
|
||||
where: {
|
||||
username: socketState.targetUsername,
|
||||
},
|
||||
select: {
|
||||
viewers: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!streamInfo) return;
|
||||
|
||||
if (!socketState.excludeFromViewerCount) {
|
||||
await redis.del(`viewer:${socketState.targetUsername}:${socketState.viewerId}`);
|
||||
}
|
||||
},
|
||||
async onMessage(evt, ws) {
|
||||
let outcome = 'ignored';
|
||||
let messageType = 'unknown';
|
||||
let stopTimer: ReturnType<typeof startChatMessageTimer> | null = null;
|
||||
|
||||
try {
|
||||
const socket = ws as unknown as ChatSocket;
|
||||
const socketState = resolveSocketState(socket);
|
||||
const rawPayload = evt.data.toString();
|
||||
const msg = JSON.parse(rawPayload) as IncomingMessage;
|
||||
messageType = getMetricsMessageType(msg.type);
|
||||
recordIncomingChatMessage(messageType, Buffer.byteLength(rawPayload));
|
||||
stopTimer = startChatMessageTimer(messageType);
|
||||
|
||||
if (msg.type === 'ping') {
|
||||
if (!socketState.excludeFromViewerCount) {
|
||||
await redis.setex(
|
||||
`viewer:${socketState.targetUsername}:${socketState.viewerId}`,
|
||||
30,
|
||||
'1'
|
||||
);
|
||||
}
|
||||
socket.send(JSON.stringify({ type: 'pong' }));
|
||||
outcome = 'pong';
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'mod:deleteMessage') {
|
||||
await handleDeleteMessageCommand(socket, socketState, msg as ChatModerationCommand, {
|
||||
deleteMessageFromHistory,
|
||||
logModerationEvent,
|
||||
broadcastToChannel,
|
||||
});
|
||||
outcome = 'moderation';
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
msg.type === 'mod:timeoutUser' ||
|
||||
msg.type === 'mod:banUser' ||
|
||||
msg.type === 'mod:unbanUser' ||
|
||||
msg.type === 'mod:liftTimeout'
|
||||
) {
|
||||
await handleUserRestrictionCommand(socket, socketState, msg as ChatModerationCommand, {
|
||||
logModerationEvent,
|
||||
broadcastRestrictionStateToUser,
|
||||
broadcastToChannel,
|
||||
});
|
||||
outcome = 'moderation';
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'message') {
|
||||
if (
|
||||
!socketState.chatUser ||
|
||||
!socketState.personalChannel ||
|
||||
!socketState.channelId ||
|
||||
!socketState.targetUsername
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const chatUser = socketState.chatUser;
|
||||
const channelId = socketState.channelId;
|
||||
const targetUsername = socketState.targetUsername;
|
||||
const isModerator = Boolean(socketState.isModerator);
|
||||
|
||||
if (!chatUser || !channelId || !targetUsername) {
|
||||
return;
|
||||
}
|
||||
|
||||
const moderationSettings = await getCachedModerationSettings(channelId);
|
||||
|
||||
const restriction = await getActiveRestriction(channelId, chatUser.id);
|
||||
if (restriction) {
|
||||
sendModerationError(
|
||||
socket,
|
||||
restriction.type === 'timeout' ? 'TIMED_OUT' : 'BANNED',
|
||||
restriction.type === 'timeout'
|
||||
? 'You are currently timed out in this chat.'
|
||||
: 'You are currently banned from this chat.',
|
||||
restriction
|
||||
);
|
||||
|
||||
await sendChatAccessState(socket, channelId, chatUser.id);
|
||||
outcome = 'blocked';
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!isModerator &&
|
||||
(await isRateLimited(
|
||||
channelId,
|
||||
chatUser.id,
|
||||
moderationSettings.rateLimitCount,
|
||||
moderationSettings.rateLimitWindowSeconds
|
||||
))
|
||||
) {
|
||||
sendModerationError(socket, 'RATE_LIMIT', 'You are sending messages too fast.');
|
||||
recordChatModerationBlock('rate_limit');
|
||||
outcome = 'rate_limited';
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isModerator && moderationSettings.slowModeSeconds > 0) {
|
||||
const slowModeKey = `chat:slowmode:${channelId}:${chatUser.id}`;
|
||||
const timeRemaining = await redis.ttl(slowModeKey);
|
||||
if (timeRemaining > 0) {
|
||||
sendModerationError(socket, 'SLOW_MODE', `Slow mode is on. Wait ${timeRemaining}s.`);
|
||||
recordChatModerationBlock('slow_mode');
|
||||
outcome = 'slow_mode';
|
||||
return;
|
||||
}
|
||||
await redis.setex(slowModeKey, moderationSettings.slowModeSeconds, '1');
|
||||
}
|
||||
|
||||
const message = (msg.message as string).trim();
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
if (message.length > moderationSettings.maxMessageLength) {
|
||||
sendModerationError(
|
||||
socket,
|
||||
'MESSAGE_TOO_LONG',
|
||||
`Message exceeds ${moderationSettings.maxMessageLength} characters.`
|
||||
);
|
||||
recordChatModerationBlock('message_too_long');
|
||||
outcome = 'message_too_long';
|
||||
return;
|
||||
}
|
||||
|
||||
const blockedTerm = containsBlockedTerm(message, moderationSettings.blockedTerms);
|
||||
if (blockedTerm) {
|
||||
if (!chatUser.isBot) {
|
||||
await logModerationEvent({
|
||||
action: ChatModerationAction.MESSAGE_BLOCKED,
|
||||
channelId,
|
||||
moderatorId: chatUser.id,
|
||||
targetUserId: chatUser.id,
|
||||
reason: 'Blocked term matched',
|
||||
details: { blockedTerm },
|
||||
});
|
||||
}
|
||||
recordChatModerationBlock('blocked_term');
|
||||
sendModerationError(socket, 'BLOCKED_TERM', 'Message blocked by channel moderation.');
|
||||
outcome = 'blocked_term';
|
||||
return;
|
||||
}
|
||||
|
||||
const msgId = crypto.randomUUID();
|
||||
const msgObj = {
|
||||
user: {
|
||||
id: chatUser.id,
|
||||
username: chatUser.username,
|
||||
pfpUrl: chatUser.pfpUrl,
|
||||
displayName: chatUser.displayName,
|
||||
isBot: chatUser.isBot || false,
|
||||
isPlatformAdmin: chatUser.isPlatformAdmin,
|
||||
channelRole: chatUser.channelRole,
|
||||
},
|
||||
message,
|
||||
msgId,
|
||||
type: 'message',
|
||||
};
|
||||
|
||||
const redisStr = JSON.stringify(msgObj);
|
||||
|
||||
const channelKey = `chat:history:${targetUsername}`;
|
||||
await redis.zadd(channelKey, Date.now(), redisStr);
|
||||
await redis.zremrangebyrank(channelKey, 0, -MESSAGE_HISTORY_SIZE - 1);
|
||||
await redis.expire(channelKey, MESSAGE_TTL);
|
||||
const historySize = await redis.zcard(channelKey);
|
||||
setChannelHistorySize(targetUsername, historySize);
|
||||
|
||||
broadcastToChannel(targetUsername, socket, msgObj as unknown as Record<string, unknown>);
|
||||
recordDeliveredChatMessage(chatUser.isBot ? 'bot' : 'user');
|
||||
recordDeliveredChatMessageBytes(
|
||||
chatUser.isBot ? 'bot' : 'user',
|
||||
Buffer.byteLength(message)
|
||||
);
|
||||
const isFirstMessageFromUser =
|
||||
(await redis.sadd(`chat:unique-chatters:${targetUsername}`, chatUser.id)) === 1;
|
||||
|
||||
if (isFirstMessageFromUser) {
|
||||
recordUniqueChatter(chatUser.isBot ? 'bot' : 'user');
|
||||
}
|
||||
outcome = 'broadcast';
|
||||
}
|
||||
if (msg.type === 'emojiMsg') {
|
||||
if (!socketState.chatUser) return;
|
||||
const emojis = msg.emojis as string[];
|
||||
const emojiMap: Record<string, string> = {};
|
||||
|
||||
await Promise.all(
|
||||
emojis.map(async (emoji) => {
|
||||
let url = await redis.hget('emojis', emoji);
|
||||
|
||||
if (!url) {
|
||||
url = await redis.hget(`emojis:${emoji}`, 'url');
|
||||
}
|
||||
if (!url) {
|
||||
url = await redis.hget(`emoji:${emoji}`, 'url');
|
||||
}
|
||||
|
||||
emojiMap[emoji] = url ?? '';
|
||||
})
|
||||
);
|
||||
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: 'emojiMsgResponse',
|
||||
emojis: emojiMap,
|
||||
})
|
||||
);
|
||||
outcome = 'emoji_lookup';
|
||||
}
|
||||
if (msg.type === 'emojiSearch') {
|
||||
if (!socketState.chatUser) return;
|
||||
const rawSearchTerm = (msg.searchTerm as string)?.trim() ?? '';
|
||||
if (!rawSearchTerm || rawSearchTerm.length > 50) {
|
||||
ws.send(JSON.stringify({ type: 'emojiSearchResponse', results: [] }));
|
||||
recordEmojiSearchResults('empty', 0);
|
||||
outcome = 'emoji_search_empty';
|
||||
return;
|
||||
}
|
||||
const searchTerm = rawSearchTerm;
|
||||
|
||||
const emojis = await redis.hgetall('emojis');
|
||||
const emojiKeys = Object.keys(emojis);
|
||||
const idxs = uf.filter(emojiKeys, searchTerm);
|
||||
|
||||
if (idxs && idxs.length > 0) {
|
||||
const results: string[] = [];
|
||||
|
||||
if (idxs.length <= 150) {
|
||||
const info = uf.info(idxs, emojiKeys, searchTerm);
|
||||
const order = uf.sort(info, emojiKeys, searchTerm);
|
||||
for (let i = 0; i < order.length && i < 10; i++) {
|
||||
results.push(emojiKeys[idxs[order[i]]]);
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < idxs.length && i < 10; i++) {
|
||||
results.push(emojiKeys[idxs[i]]);
|
||||
}
|
||||
}
|
||||
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: 'emojiSearchResponse',
|
||||
results: results,
|
||||
})
|
||||
);
|
||||
recordEmojiSearchResults('matched', results.length);
|
||||
outcome = 'emoji_search';
|
||||
} else {
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: 'emojiSearchResponse',
|
||||
results: [],
|
||||
})
|
||||
);
|
||||
recordEmojiSearchResults('no_match', 0);
|
||||
outcome = 'emoji_search_empty';
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
outcome = 'error';
|
||||
recordChatError('on_message');
|
||||
console.error('Error processing message:', e);
|
||||
} finally {
|
||||
stopTimer?.({ type: messageType, outcome });
|
||||
}
|
||||
},
|
||||
}))
|
||||
);
|
||||
|
||||
const server = serve(
|
||||
{
|
||||
fetch: app.fetch,
|
||||
port: 8000,
|
||||
},
|
||||
(info) => {
|
||||
console.log(`Server is running on http://localhost:${info.port}`);
|
||||
}
|
||||
);
|
||||
injectWebSocket(server);
|
||||
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.`,
|
||||
});
|
||||
}
|
||||
17
apps/chat/src/utils/personalChannel.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { prisma } from "@hctv/db";
|
||||
|
||||
export async function getPersonalChannel(id: string) {
|
||||
const db = await prisma.user.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
select: {
|
||||
personalChannel: true,
|
||||
},
|
||||
});
|
||||
if (!db) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return db.personalChannel;
|
||||
}
|
||||
8
apps/chat/src/utils/randomString.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export function randomString(length: number): string {
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||
let result = '';
|
||||
for (let i = 0; i < length; i++) {
|
||||
result += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
16
apps/chat/tsconfig.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"module": "NodeNext",
|
||||
"strict": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"skipLibCheck": true,
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "hono/jsx",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src"
|
||||
}
|
||||
}
|
||||
21
apps/docs/.gitignore
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
# build output
|
||||
dist/
|
||||
# generated types
|
||||
.astro/
|
||||
|
||||
# dependencies
|
||||
node_modules/
|
||||
|
||||
# logs
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
|
||||
|
||||
# environment variables
|
||||
.env
|
||||
.env.production
|
||||
|
||||
# macOS-specific files
|
||||
.DS_Store
|
||||
4
apps/docs/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"recommendations": ["astro-build.astro-vscode"],
|
||||
"unwantedRecommendations": []
|
||||
}
|
||||
11
apps/docs/.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"command": "./node_modules/.bin/astro dev",
|
||||
"name": "Development server",
|
||||
"request": "launch",
|
||||
"type": "node-terminal"
|
||||
}
|
||||
]
|
||||
}
|
||||
45
apps/docs/astro.config.mjs
Normal file
@@ -0,0 +1,45 @@
|
||||
// @ts-check
|
||||
import { defineConfig } from 'astro/config';
|
||||
import starlight from '@astrojs/starlight';
|
||||
import mermaid from 'astro-mermaid';
|
||||
import catppuccin from '@catppuccin/starlight';
|
||||
import starlightTypeDoc, { typeDocSidebarGroup } from 'starlight-typedoc';
|
||||
|
||||
// https://astro.build/config
|
||||
export default defineConfig({
|
||||
integrations: [
|
||||
mermaid({
|
||||
theme: 'base',
|
||||
autoTheme: true,
|
||||
}),
|
||||
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' },
|
||||
}),
|
||||
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,
|
||||
],
|
||||
}),
|
||||
],
|
||||
});
|
||||
23
apps/docs/package.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "@hctv/docs",
|
||||
"type": "module",
|
||||
"version": "0.0.1",
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
"start": "astro dev",
|
||||
"build": "astro build",
|
||||
"preview": "astro preview",
|
||||
"astro": "astro"
|
||||
},
|
||||
"dependencies": {
|
||||
"@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"
|
||||
}
|
||||
}
|
||||
1
apps/docs/public/favicon.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><path fill-rule="evenodd" d="M81 36 64 0 47 36l-1 2-9-10a6 6 0 0 0-9 9l10 10h-2L0 64l36 17h2L28 91a6 6 0 1 0 9 9l9-10 1 2 17 36 17-36v-2l9 10a6 6 0 1 0 9-9l-9-9 2-1 36-17-36-17-2-1 9-9a6 6 0 1 0-9-9l-9 10v-2Zm-17 2-2 5c-4 8-11 15-19 19l-5 2 5 2c8 4 15 11 19 19l2 5 2-5c4-8 11-15 19-19l5-2-5-2c-8-4-15-11-19-19l-2-5Z" clip-rule="evenodd"/><path d="M118 19a6 6 0 0 0-9-9l-3 3a6 6 0 1 0 9 9l3-3Zm-96 4c-2 2-6 2-9 0l-3-3a6 6 0 1 1 9-9l3 3c3 2 3 6 0 9Zm0 82c-2-2-6-2-9 0l-3 3a6 6 0 1 0 9 9l3-3c3-2 3-6 0-9Zm96 4a6 6 0 0 1-9 9l-3-3a6 6 0 1 1 9-9l3 3Z"/><style>path{fill:#000}@media (prefers-color-scheme:dark){path{fill:#fff}}</style></svg>
|
||||
|
After Width: | Height: | Size: 696 B |
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/houston.webp
Normal file
|
After Width: | Height: | Size: 96 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 |
7
apps/docs/src/content.config.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { defineCollection } from 'astro:content';
|
||||
import { docsLoader } from '@astrojs/starlight/loaders';
|
||||
import { docsSchema } from '@astrojs/starlight/schema';
|
||||
|
||||
export const collections = {
|
||||
docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
|
||||
};
|
||||
353
apps/docs/src/content/docs/api/chat.mdx
Normal file
@@ -0,0 +1,353 @@
|
||||
---
|
||||
title: Chat
|
||||
description: Chat websocket
|
||||
---
|
||||
|
||||
import { Aside } from '@astrojs/starlight/components';
|
||||
|
||||
The chat system is powered by a websocket server. Please read the entire page before implementing anything, as there are some important notes.
|
||||
|
||||
## Connection and messages
|
||||
|
||||
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.
|
||||
|
||||
<Aside type="tip">
|
||||
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 about 5 seconds. This is because of Cloudflare limitations.
|
||||
|
||||
Messages are sent and received in JSON format. The following message types are supported:
|
||||
|
||||
- `session`: sent by the server immediately upon connection.
|
||||
- received by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "session",
|
||||
"viewer": {
|
||||
"id": "user_id",
|
||||
"username": "your_username"
|
||||
},
|
||||
"permissions": {
|
||||
"canModerate": false
|
||||
},
|
||||
"moderation": {
|
||||
"hasBlockedTerms": false,
|
||||
"slowModeSeconds": 0,
|
||||
"maxMessageLength": 400
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`viewer` is `null` for unauthenticated (grant-only) connections. `canModerate` is `true` for channel owners, managers, moderators, and platform admins.
|
||||
|
||||
- `chatAccess`: sent by the server on connect (for authenticated non-bot users) and whenever a user's restriction state changes.
|
||||
- received by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "chatAccess",
|
||||
"canSend": true,
|
||||
"restriction": null
|
||||
}
|
||||
```
|
||||
|
||||
When the user is restricted, `canSend` is `false` and `restriction` contains:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "timeout",
|
||||
"reason": "Timed out by moderator",
|
||||
"expiresAt": "2026-01-01T00:00:00.000Z"
|
||||
}
|
||||
```
|
||||
|
||||
`type` is either `"timeout"` or `"ban"`. `expiresAt` is an ISO 8601 string for timeouts, or `null` for permanent bans.
|
||||
|
||||
- `ping`: a ping message to keep the connection alive.
|
||||
- sent by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "ping"
|
||||
}
|
||||
```
|
||||
|
||||
- received by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "pong"
|
||||
}
|
||||
```
|
||||
|
||||
- `message`: a chat message.
|
||||
- sent by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "message",
|
||||
"message": "Hello, world!"
|
||||
}
|
||||
```
|
||||
|
||||
- received by client (broadcast to all viewers of the channel):
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "message",
|
||||
"msgId": "uuid-v4",
|
||||
"user": {
|
||||
"id": "user_id",
|
||||
"username": "user_who_sent_message",
|
||||
"pfpUrl": "https://example.com/avatar.png",
|
||||
"displayName": "Display Name",
|
||||
"isBot": false,
|
||||
"isPlatformAdmin": false,
|
||||
"channelRole": null
|
||||
},
|
||||
"message": "Hello, world!"
|
||||
}
|
||||
```
|
||||
|
||||
`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",
|
||||
"pfpUrl": "https://example.com/avatar.png",
|
||||
"displayName": "Display Name",
|
||||
"isBot": false,
|
||||
"isPlatformAdmin": false,
|
||||
"channelRole": null
|
||||
},
|
||||
"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_
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "Emoji Processing Pipeline"
|
||||
CHAT_MSG["Chat Message"]
|
||||
PATTERN_MATCH["Regex :emoji: Pattern"]
|
||||
EMOJI_REQUEST["emojiMsg WebSocket"]
|
||||
REDIS_LOOKUP["Redis HGET emojis"]
|
||||
FUZZY_SEARCH["uFuzzy"]
|
||||
EMOJI_RESPONSE["emojiMsgResponse"]
|
||||
end
|
||||
|
||||
subgraph "Redis Storage"
|
||||
EMOJI_HASH["emojis hash key"]
|
||||
EMOJI_PREFIXED["emoji:{name} url"]
|
||||
EMOJIS_PREFIXED["emojis:{name} url"]
|
||||
end
|
||||
|
||||
CHAT_MSG --> PATTERN_MATCH
|
||||
PATTERN_MATCH --":emojiname:"--> EMOJI_REQUEST
|
||||
EMOJI_REQUEST --> REDIS_LOOKUP
|
||||
|
||||
REDIS_LOOKUP --> EMOJI_HASH
|
||||
REDIS_LOOKUP --> EMOJI_PREFIXED
|
||||
REDIS_LOOKUP --> EMOJIS_PREFIXED
|
||||
|
||||
REDIS_LOOKUP --> EMOJI_RESPONSE
|
||||
|
||||
FUZZY_SEARCH --> EMOJI_HASH
|
||||
FUZZY_SEARCH --"search results"--> EMOJI_RESPONSE
|
||||
```
|
||||
|
||||
When a chat message is sent, the server looks for patterns in the format `:emojiname:` using regex. For each match, it sends a request to the `emojiMsg` WebSocket.
|
||||
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": {
|
||||
"aga": "https://emoji.slack-edge.com/aga.png",
|
||||
"yapa": "https://emoji.slack-edge.com/yapa.png",
|
||||
"heavysob": "https://emoji.slack-edge.com/heavysob.png",
|
||||
"yay": "https://emoji.slack-edge.com/yay.png",
|
||||
"yay-bounce": "https://emoji.slack-edge.com/yay-bounce.png"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `emojiSearch`: Searches for emojis
|
||||
- sent by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "emojiSearch",
|
||||
"searchTerm": "aga"
|
||||
}
|
||||
```
|
||||
|
||||
- received by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "emojiSearchResponse",
|
||||
"results": [
|
||||
"aga",
|
||||
"aga-brick-throw",
|
||||
"aga-dance",
|
||||
"aga-transparent",
|
||||
"a-aga",
|
||||
"a-aga-transparent",
|
||||
"agaban",
|
||||
"agaboing",
|
||||
"agabounce",
|
||||
"agabusiness"
|
||||
]
|
||||
}
|
||||
```
|
||||
19
apps/docs/src/content/docs/api/index.mdx
Normal file
@@ -0,0 +1,19 @@
|
||||
---
|
||||
title: API Documentation
|
||||
description: Documented API endpoints for hackclub.tv
|
||||
---
|
||||
|
||||
hctv is meant to be one of the most hackable streaming platforms out there. to that end, we have a (currently limited) public API that you can use to interact with the platform.
|
||||
|
||||
since this is beta software, the API is subject to change. additionally, many endpoints are yet not implemented or not fun to implement. please send a message in #hctv on the Hack Club Slack if you have any requests.
|
||||
|
||||
## Base url
|
||||
|
||||
base url for all endpoints is `https://hackclub.tv/api`.
|
||||
|
||||
## Authentication
|
||||
|
||||
most endpoints require authentication. this will be pointed out in the documentation.
|
||||
for now, it is done via a cookie called `auth_session` (as per lucia auth). this will change in the future as bot accounts are planned.
|
||||
|
||||
you'll need your user account to authenticate. as a recommendation, open an incognito window, log in to hctv, and copy the `auth_session` cookie from there.
|
||||
4
apps/docs/src/content/docs/api/meta.json
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"title": "API",
|
||||
"description": "Documented API endpoints for hackclub.tv"
|
||||
}
|
||||
12
apps/docs/src/content/docs/api/rtmp.mdx
Normal file
@@ -0,0 +1,12 @@
|
||||
---
|
||||
title: RTMP
|
||||
description: RTMP related endpoint group
|
||||
---
|
||||
|
||||
## POST `/rtmp/streamKey`
|
||||
regenerates your stream key. **authentication required**.
|
||||
body parameters (json):
|
||||
- `channel`: string - the channel name you want to regenerate the key for. must be one of your channels.
|
||||
|
||||
response (json):
|
||||
- `key`: string - the new stream key
|
||||
47
apps/docs/src/content/docs/api/stream.mdx
Normal file
@@ -0,0 +1,47 @@
|
||||
---
|
||||
title: Stream
|
||||
description: Stream related endpoint group
|
||||
---
|
||||
|
||||
## GET `/stream/follow`
|
||||
checks if **authenticated user** is following a certain channel.
|
||||
query parameters:
|
||||
- `username`: string - the channel name you want to check.
|
||||
|
||||
response (json):
|
||||
- `following`: boolean - whether the authenticated user is following the channel or not.
|
||||
|
||||
## POST `/stream/follow`
|
||||
cycle through follow or unfollow a channel. **authentication required**.
|
||||
body parameters (json):
|
||||
- `channel`: string - the channel name you want to make the action. must be one of your channels.
|
||||
|
||||
response (json):
|
||||
- `success`: boolean - whether the operation was successful or not.
|
||||
|
||||
## GET `/stream/followers/:channel`
|
||||
gets the followcount of a channel.
|
||||
path parameters:
|
||||
- `channel`: string - the channel name you want to get the followcount of.
|
||||
|
||||
response (json):
|
||||
- `count`: integer - the number of followers the channel has.
|
||||
- `success`: boolean - whether the operation was successful or not. (true if 200 status code)
|
||||
|
||||
## GET `/stream/info`
|
||||
get stream info of certain channels by filtering. **authentication on some**.
|
||||
query parameters:
|
||||
- `owned`: boolean (optional) - if true, only returns channels owned by the authenticated user. requires authentication.
|
||||
- `personal`: boolean (optional) - if true, only returns personal channels. requires authentication.
|
||||
- `live`: boolean (optional) - if true, only returns channels that are currently live.
|
||||
|
||||
response (json):
|
||||
- StreamInfo[] (check database schema for all returned data or just try it out!)
|
||||
|
||||
## GET `/stream/thumb/:channel`
|
||||
gets the preview thumbnail of a channel's livestream. **authentication required**
|
||||
|
||||
path parameters:
|
||||
- `channel`: string - the channel name you want to get the thumbnail of.
|
||||
|
||||
response: image (webp)
|
||||
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
|
||||
```
|
||||
4
apps/docs/src/content/docs/guides/meta.json
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"title": "Guides",
|
||||
"description": "Useful guides to help you get started with hackclub.tv"
|
||||
}
|
||||
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)
|
||||
51
apps/docs/src/content/docs/guides/start-stream.mdx
Normal file
@@ -0,0 +1,51 @@
|
||||
---
|
||||
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';
|
||||
|
||||
_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._
|
||||
|
||||
<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!
|
||||
8
apps/docs/src/content/docs/index.mdx
Normal file
@@ -0,0 +1,8 @@
|
||||
---
|
||||
title: About hctv docs
|
||||
description: Index documentation page!
|
||||
---
|
||||
|
||||
Welcome to the hackclub.tv docs! Here you'll find tips and tricks to get the most out of hackclub.tv and its features.
|
||||
|
||||
Additionally, some useful guides are available to help you get started with common tasks.
|
||||
8
apps/docs/tsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "astro/tsconfigs/strict",
|
||||
"compilerOptions": {
|
||||
"ignoreDeprecations": "6.0"
|
||||
},
|
||||
"include": [".astro/types.d.ts", "**/*"],
|
||||
"exclude": ["dist"]
|
||||
}
|
||||
0
apps/docs/yarn.lock
Normal file
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=
|
||||
111
apps/web/Dockerfile
Normal file
@@ -0,0 +1,111 @@
|
||||
FROM node:22-slim AS base
|
||||
ENV PNPM_HOME="/pnpm"
|
||||
ENV PATH="$PNPM_HOME/bin:$PATH"
|
||||
RUN corepack enable
|
||||
|
||||
FROM base AS builder
|
||||
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
|
||||
RUN pnpm add -g turbo@^2
|
||||
COPY . .
|
||||
|
||||
# Get the git commit hash before pruning (since .git might be removed)
|
||||
RUN git rev-parse --short HEAD > /tmp/commit_hash || echo "unknown" > /tmp/commit_hash
|
||||
|
||||
# Generate a partial monorepo with a pruned lockfile for a target workspace.
|
||||
# Assuming "web" is the name entered in the project's package.json: { name: "web" }
|
||||
RUN turbo prune @hctv/web --docker
|
||||
|
||||
# Add lockfile and package.json's of isolated subworkspace
|
||||
FROM base AS installer
|
||||
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
|
||||
WORKDIR /app
|
||||
|
||||
# First install the dependencies (as they change less often)
|
||||
COPY --from=builder /app/out/json/ .
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
# Install a standalone Prisma CLI for runtime migrations (no pnpm symlinks).
|
||||
RUN mkdir -p /opt/prisma-cli && cd /opt/prisma-cli && npm init -y && npm install prisma@6.5.0
|
||||
|
||||
COPY --from=builder /app/out/full/ .
|
||||
|
||||
# Generate latest emojis.json during image build.
|
||||
RUN ARCH=$(dpkg --print-architecture) && \
|
||||
if [ "$ARCH" = "amd64" ]; then EMOJI_ARCH="x86_64"; \
|
||||
elif [ "$ARCH" = "arm64" ]; then EMOJI_ARCH="aarch64"; \
|
||||
else EMOJI_ARCH=""; fi && \
|
||||
RELEASE_JSON=$(curl -fsSL https://api.github.com/repos/srizan10/hctv/releases/latest || true) && \
|
||||
RELEASE_URL=$(printf '%s' "$RELEASE_JSON" | grep "browser_download_url.*slack-import-emojis-linux-${EMOJI_ARCH}" | cut -d '"' -f 4 || true) && \
|
||||
if [ -n "$RELEASE_URL" ] && \
|
||||
curl -fsSL -o /tmp/slack-import-emojis-bin "$RELEASE_URL" && \
|
||||
chmod +x /tmp/slack-import-emojis-bin && \
|
||||
/tmp/slack-import-emojis-bin default; then \
|
||||
cp /app/emojis.json /app/apps/web/emojis.json; \
|
||||
else \
|
||||
cp /app/apps/web/src/lib/instrumentation/emojis.json /app/apps/web/emojis.json; \
|
||||
fi
|
||||
|
||||
RUN --mount=type=secret,id=TURBO_TOKEN --mount=type=secret,id=TURBO_TEAM --mount=type=secret,id=SENTRY_AUTH_TOKEN \
|
||||
COMMIT=$(cat /tmp/commit_hash 2>/dev/null || echo "unknown") && \
|
||||
TURBO_TOKEN=$(cat /run/secrets/TURBO_TOKEN) TURBO_TEAM=$(cat /run/secrets/TURBO_TEAM) \
|
||||
SENTRY_AUTH_TOKEN=$(cat /run/secrets/SENTRY_AUTH_TOKEN) \
|
||||
commit=$COMMIT pnpm turbo run build --env-mode=loose
|
||||
|
||||
FROM base AS runner
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ffmpeg \
|
||||
libvips42 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
USER nextjs
|
||||
|
||||
# Automatically leverage output traces to reduce image size
|
||||
# https://nextjs.org/docs/advanced-features/output-file-tracing
|
||||
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 --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"]
|
||||
87
apps/web/benchmark.py
Normal file
@@ -0,0 +1,87 @@
|
||||
# quick and dirty ai generated benchmark i created for hls streams
|
||||
|
||||
#!/usr/bin/env python3
|
||||
import asyncio
|
||||
import aiohttp
|
||||
import argparse
|
||||
import time
|
||||
import random
|
||||
from tqdm import tqdm
|
||||
|
||||
async def simulate_viewer(session, base_url, stream_name, viewer_id, duration):
|
||||
"""Simulate a viewer watching an HLS stream"""
|
||||
hls_url = f"{base_url}/hls/{stream_name}.m3u8"
|
||||
|
||||
# First request the playlist
|
||||
try:
|
||||
start_time = time.time()
|
||||
end_time = start_time + duration
|
||||
|
||||
while time.time() < end_time:
|
||||
# Get the master playlist
|
||||
async with session.get(hls_url) as response:
|
||||
if response.status != 200:
|
||||
print(f"Viewer {viewer_id}: Failed to get playlist: {response.status}")
|
||||
return
|
||||
|
||||
playlist = await response.text()
|
||||
|
||||
# Parse the playlist to find segments
|
||||
segments = [line for line in playlist.splitlines() if line.endswith('.ts')]
|
||||
|
||||
if segments:
|
||||
# Request a random segment to simulate viewing
|
||||
segment = random.choice(segments)
|
||||
segment_url = f"{base_url}/hls/{segment}"
|
||||
|
||||
async with session.get(segment_url) as seg_response:
|
||||
if seg_response.status != 200:
|
||||
print(f"Viewer {viewer_id}: Failed to get segment: {seg_response.status}")
|
||||
|
||||
# Wait a bit before requesting again (simulating segment download)
|
||||
await asyncio.sleep(2)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Viewer {viewer_id} error: {str(e)}")
|
||||
|
||||
async def run_benchmark(base_url, stream_name, num_viewers, duration):
|
||||
"""Run the benchmark with the specified number of viewers"""
|
||||
print(f"Starting benchmark with {num_viewers} viewers for {duration} seconds")
|
||||
|
||||
all_tasks = [] # Keep track of all tasks
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
with tqdm(total=num_viewers, desc="Connecting viewers") as pbar:
|
||||
# Start viewers gradually to avoid overwhelming the server
|
||||
for i in range(0, num_viewers, 10):
|
||||
batch = []
|
||||
for j in range(i, min(i+10, num_viewers)):
|
||||
task = asyncio.create_task(simulate_viewer(session, base_url, stream_name, j, duration))
|
||||
batch.append(task)
|
||||
all_tasks.append(task)
|
||||
|
||||
pbar.update(len(batch))
|
||||
await asyncio.sleep(0.5) # Small delay between batches
|
||||
|
||||
print(f"All {num_viewers} viewers connected. Running for {duration} seconds...")
|
||||
|
||||
# Wait for all tasks to complete
|
||||
await asyncio.gather(*all_tasks)
|
||||
|
||||
print(f"Benchmark completed after {duration} seconds.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description='Benchmark NGINX-RTMP HLS streaming with simulated viewers')
|
||||
parser.add_argument('--url', default='http://localhost:8888', help='Base URL of the NGINX server')
|
||||
parser.add_argument('--stream', required=True, help='Stream name to connect to')
|
||||
parser.add_argument('--viewers', type=int, default=100, help='Number of simulated viewers')
|
||||
parser.add_argument('--duration', type=int, default=60, help='Duration in seconds to run the test')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
print(f"Benchmarking stream: {args.stream}")
|
||||
print(f"Server: {args.url}")
|
||||
print(f"Viewers: {args.viewers}")
|
||||
print(f"Duration: {args.duration} seconds")
|
||||
|
||||
asyncio.run(run_benchmark(args.url, args.stream, args.viewers, args.duration))
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
104
apps/web/next.config.mjs
Normal file
@@ -0,0 +1,104 @@
|
||||
import {withSentryConfig} from '@sentry/nextjs';
|
||||
import * as path from 'node:path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { execSync } from 'node:child_process';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const LIVE_SERVER_URL =
|
||||
process.env.NODE_ENV === 'production'
|
||||
? 'http://nginx-rtmp:8888'
|
||||
: 'http://localhost:8888';
|
||||
|
||||
const packageJson = JSON.parse(readFileSync('./package.json', 'utf8'));
|
||||
const { version } = packageJson;
|
||||
const commit = process.env.commit || execSync('git rev-parse --short HEAD')
|
||||
.toString().trim();
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
images: {
|
||||
remotePatterns: [
|
||||
{
|
||||
hostname: 'picsum.photos',
|
||||
},
|
||||
{
|
||||
hostname: 'secure.gravatar.com',
|
||||
},
|
||||
{
|
||||
hostname: 'emoji.slack-edge.com',
|
||||
},
|
||||
{
|
||||
hostname: 'cdn.jsdelivr.net',
|
||||
pathname: '/npm/emoji-datasource-twitter@15.1.2/img/twitter/64/*',
|
||||
},
|
||||
{
|
||||
hostname: 'eoceqrx2r7.ufs.sh'
|
||||
},
|
||||
{
|
||||
hostname: 'thesvg.org',
|
||||
}
|
||||
],
|
||||
minimumCacheTTL: 120,
|
||||
},
|
||||
env: {
|
||||
LIVE_SERVER_URL,
|
||||
commit,
|
||||
version,
|
||||
},
|
||||
reactStrictMode: false,
|
||||
output: 'standalone',
|
||||
outputFileTracingRoot: path.join(__dirname, '../../'),
|
||||
serverExternalPackages: ['bullmq'],
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
source: '/api/stream/chat/:path*',
|
||||
destination: `http://${process.env.NODE_ENV === 'production' ? 'chat' : 'localhost'}:8000/:path*`,
|
||||
},
|
||||
];
|
||||
},
|
||||
logging: {
|
||||
incomingRequests: false,
|
||||
},
|
||||
};
|
||||
|
||||
export default withSentryConfig(nextConfig, {
|
||||
// For all available options, see:
|
||||
// https://www.npmjs.com/package/@sentry/webpack-plugin#options
|
||||
|
||||
org: "sr-izan",
|
||||
|
||||
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,
|
||||
|
||||
// For all available options, see:
|
||||
// https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/
|
||||
|
||||
// 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-
|
||||
// side errors will fail.
|
||||
tunnelRoute: "/monitoring",
|
||||
|
||||
// Automatically tree-shake Sentry logger statements to reduce bundle size
|
||||
disableLogger: true,
|
||||
|
||||
// Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.)
|
||||
// See the following for more information:
|
||||
// https://docs.sentry.io/product/crons/
|
||||
// https://vercel.com/docs/cron-jobs
|
||||
automaticVercelMonitors: true,
|
||||
});
|
||||
99
apps/web/package.json
Normal file
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"name": "@hctv/web",
|
||||
"version": "0.5.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dd": "docker compose --file ../../dev/docker-compose.yml up -d",
|
||||
"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",
|
||||
"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": "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": "^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.3",
|
||||
"ajv": "^8.20.0",
|
||||
"arctic": "^3.7.0",
|
||||
"bullmq": "^5.76.4",
|
||||
"cheerio": "^1.2.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"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": "^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.5",
|
||||
"sonner": "^2.0.7",
|
||||
"swr": "^2.4.1",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"unified": "^11.0.5",
|
||||
"uploadthing": "^7.7.4",
|
||||
"util-utils": "^1.0.3",
|
||||
"valtio": "^2.3.2",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.6.0",
|
||||
"@types/node-cron": "^3.0.11",
|
||||
"@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': {},
|
||||
},
|
||||
};
|
||||
|
||||
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 |
20
apps/web/sentry.edge.config.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on).
|
||||
// The config you add here will be used whenever one of the edge features is loaded.
|
||||
// Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally.
|
||||
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
|
||||
|
||||
import * as Sentry from "@sentry/nextjs";
|
||||
|
||||
Sentry.init({
|
||||
dsn: "https://f3c26671c39af48406c6e23702a4f3dd@o4506961023860736.ingest.us.sentry.io/4509895816773632",
|
||||
|
||||
// Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control.
|
||||
tracesSampleRate: 1,
|
||||
|
||||
// Enable logs to be sent to Sentry
|
||||
enableLogs: true,
|
||||
|
||||
// Setting this option to true will print useful information to the console while you're setting up Sentry.
|
||||
debug: false,
|
||||
enabled: process.env.NODE_ENV === 'production',
|
||||
});
|
||||
@@ -1,16 +1,18 @@
|
||||
import LiveStream from "@/components/app/Livestream/Livestream";
|
||||
import prisma from "@/lib/db";
|
||||
import ChatPanel from "@/components/app/ChatPanel/ChatPanel";
|
||||
import { prisma } from '@hctv/db';
|
||||
|
||||
export default async function Page({ params }: { params: Promise<{ username: string }> }) {
|
||||
const { username } = await params;
|
||||
const streamInfo = await prisma.streamInfo.findUnique({
|
||||
where: { username },
|
||||
include: { ownedBy: true },
|
||||
include: { channel: true },
|
||||
});
|
||||
if (!streamInfo) {
|
||||
return <div>Stream not found</div>;
|
||||
}
|
||||
return (
|
||||
<LiveStream username={username} streamInfo={streamInfo} />
|
||||
<div className="bg-transparent h-screen">
|
||||
<ChatPanel isObsPanel />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
49
apps/web/src/app/(ui)/(protected)/[username]/page.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
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: {
|
||||
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}
|
||||
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 });
|
||||
}
|
||||
6
apps/web/src/app/(ui)/(protected)/api/commit/route.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export function GET() {
|
||||
return Response.json({
|
||||
version: process.env.version,
|
||||
commit: process.env.commit,
|
||||
});
|
||||
}
|
||||
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,
|
||||
});
|
||||
57
apps/web/src/app/(ui)/(protected)/api/rtmp/publish/route.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { prisma } from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const formData = await request.formData();
|
||||
const streamKey = formData.get('name');
|
||||
if (typeof streamKey !== 'string') {
|
||||
return new Response('bad request', {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
|
||||
const key = await prisma.streamKey.findFirst({
|
||||
where: {
|
||||
key: streamKey,
|
||||
},
|
||||
include: {
|
||||
channel: {
|
||||
include: {
|
||||
restriction: true,
|
||||
owner: {
|
||||
include: { ban: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!key) {
|
||||
return new Response('nay', {
|
||||
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: {
|
||||
'Location': key.channel.name,
|
||||
},
|
||||
});
|
||||
}
|
||||
106
apps/web/src/app/(ui)/(protected)/api/rtmp/streamKey/route.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { regenerateStreamKey } from '@/lib/db/streamKey';
|
||||
import { prisma } from '@hctv/db';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const channelName = await readChannelNameFromBody(request);
|
||||
|
||||
if (!channelName) {
|
||||
return badRequestResponse();
|
||||
}
|
||||
|
||||
const result = await getAuthorizedChannel(channelName);
|
||||
if ('response' in result) {
|
||||
return result.response;
|
||||
}
|
||||
|
||||
const streamKey = await regenerateStreamKey(result.channel.id, channelName);
|
||||
return Response.json({ key: streamKey.key });
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const channelName = request.nextUrl.searchParams.get('channel');
|
||||
|
||||
if (!isValidChannelName(channelName)) {
|
||||
return badRequestResponse();
|
||||
}
|
||||
|
||||
const result = await getAuthorizedChannel(channelName);
|
||||
if ('response' in result) {
|
||||
return result.response;
|
||||
}
|
||||
|
||||
const streamKey = await prisma.streamKey.findUnique({
|
||||
where: { channelId: result.channel.id },
|
||||
select: { key: true },
|
||||
});
|
||||
|
||||
if (!streamKey) {
|
||||
return new Response('Stream key not found', { status: 404 });
|
||||
}
|
||||
|
||||
return Response.json({ key: streamKey.key });
|
||||
}
|
||||
|
||||
async function getAuthorizedChannel(channelName: string): Promise<AuthorizedChannelResult> {
|
||||
const { user } = await validateRequest();
|
||||
|
||||
if (!user) {
|
||||
return { response: unauthorizedResponse() };
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { name: channelName },
|
||||
select: {
|
||||
id: true,
|
||||
ownerId: true,
|
||||
managers: {
|
||||
where: { id: user.id },
|
||||
select: { id: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
return { response: new Response('Channel not found', { status: 404 }) };
|
||||
}
|
||||
|
||||
const isBroadcaster = channel.ownerId === user.id || channel.managers.length > 0;
|
||||
if (!isBroadcaster) {
|
||||
return { response: unauthorizedResponse() };
|
||||
}
|
||||
|
||||
return { channel: { id: channel.id } };
|
||||
}
|
||||
|
||||
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;
|
||||
};
|
||||
@@ -0,0 +1,130 @@
|
||||
import { validateRequest } from "@/lib/auth/validate";
|
||||
import { prisma } from "@hctv/db";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
type Params = Promise<{ slug: string }>;
|
||||
|
||||
export async function POST(request: NextRequest, segmentData: { params: Params }) {
|
||||
const { slug } = await segmentData.params;
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return new Response(JSON.stringify({ success: false, error: 'Unauthorized' }), { status: 401 });
|
||||
}
|
||||
|
||||
const bodySchema = z.object({
|
||||
action: z.enum(['revoke', 'regenerate', 'create']),
|
||||
name: z.string().min(3, 'Name must be at least 3 characters long').max(50, 'Name must be at most 50 characters long'),
|
||||
});
|
||||
const body = await request.json();
|
||||
const parsedBody = bodySchema.safeParse(body);
|
||||
if (!parsedBody.success) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: parsedBody.error.issues.map((issue) => issue.message).join(', '),
|
||||
}),
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { action, name } = parsedBody.data;
|
||||
|
||||
if (action === 'create') {
|
||||
const exists = await prisma.botApiKey.findFirst({
|
||||
where: {
|
||||
name,
|
||||
botAccount: {
|
||||
ownerId: user.id,
|
||||
slug,
|
||||
}
|
||||
}
|
||||
});
|
||||
if (exists) {
|
||||
return new Response(JSON.stringify({ success: false, error: 'API Key with this name already exists' }), { status: 400 });
|
||||
}
|
||||
const newKey = await prisma.botApiKey.create({
|
||||
data: {
|
||||
name,
|
||||
botAccount: {
|
||||
connect: {
|
||||
ownerId: user.id,
|
||||
slug,
|
||||
}
|
||||
},
|
||||
key: generateApiKey(),
|
||||
}
|
||||
});
|
||||
return new Response(JSON.stringify({ success: true, apiKey: newKey.key, id: newKey.id }));
|
||||
}
|
||||
if (action === 'regenerate') {
|
||||
const existingKey = await prisma.botApiKey.findFirst({
|
||||
where: {
|
||||
name,
|
||||
botAccount: {
|
||||
ownerId: user.id,
|
||||
slug,
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!existingKey) {
|
||||
return new Response(JSON.stringify({ success: false, error: 'API Key not found' }), { status: 404 });
|
||||
}
|
||||
const newKey = generateApiKey();
|
||||
await prisma.botApiKey.update({
|
||||
where: { id: existingKey.id },
|
||||
data: { key: newKey },
|
||||
});
|
||||
return new Response(JSON.stringify({ success: true, apiKey: newKey, id: existingKey.id }));
|
||||
}
|
||||
if (action === 'revoke') {
|
||||
const existingKey = await prisma.botApiKey.findFirst({
|
||||
where: {
|
||||
name,
|
||||
botAccount: {
|
||||
ownerId: user.id,
|
||||
slug,
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!existingKey) {
|
||||
return new Response(JSON.stringify({ success: false, error: 'API Key not found' }), { status: 404 });
|
||||
}
|
||||
await prisma.botApiKey.delete({
|
||||
where: { id: existingKey.id },
|
||||
});
|
||||
return new Response(JSON.stringify({ success: true }));
|
||||
}
|
||||
return new Response(JSON.stringify({ success: false, error: 'Invalid action' }), { status: 400 });
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest, segmentData: { params: Params }) {
|
||||
const { slug } = await segmentData.params;
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return new Response(JSON.stringify({ success: false, error: 'Unauthorized' }), { status: 401 });
|
||||
}
|
||||
|
||||
const apiKeys = await prisma.botApiKey.findMany({
|
||||
where: {
|
||||
botAccount: {
|
||||
ownerId: user.id,
|
||||
slug,
|
||||
}
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
createdAt: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc',
|
||||
}
|
||||
});
|
||||
return new Response(JSON.stringify({ success: true, apiKeys }));
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { validateRequest } from '@/lib/auth';
|
||||
import prisma from '@/lib/db';
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { getNotificationQueue } from '@/lib/workers';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
@@ -12,6 +13,17 @@ export async function GET(request: NextRequest) {
|
||||
if (!username) {
|
||||
return new Response('Bad Request', { status: 400 });
|
||||
}
|
||||
const channelOwner = await prisma.channel.findFirst({
|
||||
where: {
|
||||
name: username,
|
||||
}
|
||||
})
|
||||
if (!channelOwner) {
|
||||
return new Response('Not Found', { status: 404 });
|
||||
}
|
||||
if (channelOwner.ownerId === user.id) {
|
||||
return new Response('you are of course not able to follow yourself', { status: 418 });
|
||||
}
|
||||
|
||||
const isFollowing =
|
||||
(await prisma.follow.count({
|
||||
@@ -30,6 +42,7 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
const queue = getNotificationQueue();
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const username = searchParams.get('username');
|
||||
if (!user) {
|
||||
@@ -38,6 +51,17 @@ export async function POST(request: NextRequest) {
|
||||
if (!username) {
|
||||
return new Response('Bad Request', { status: 400 });
|
||||
}
|
||||
const channelOwner = await prisma.channel.findFirst({
|
||||
where: {
|
||||
name: username,
|
||||
}
|
||||
})
|
||||
if (!channelOwner) {
|
||||
return new Response('Not Found', { status: 404 });
|
||||
}
|
||||
if (channelOwner.ownerId === user.id) {
|
||||
return new Response('you are of course not able to follow yourself', { status: 418 });
|
||||
}
|
||||
|
||||
const isFollowing =
|
||||
(await prisma.follow.count({
|
||||
@@ -77,6 +101,11 @@ export async function POST(request: NextRequest) {
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await queue.add(`newFollow:${username}`, {
|
||||
text: `You started following \`${username}\`!\n_Stream notifications are disabled by default. If you want to enable them, you can do so in \`Profile > Notifications\`._`,
|
||||
channel: user.slack_id,
|
||||
});
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ following: !isFollowing }), { status: 200 });
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import db from '@/lib/db';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { resolveChannelNameId } from '@/lib/db/resolve';
|
||||
|
||||
export async function GET(
|
||||
@@ -15,7 +15,7 @@ export async function GET(
|
||||
|
||||
const channelId = await resolveChannelNameId(channel);
|
||||
|
||||
const count = await db.follow.count({
|
||||
const count = await prisma.follow.count({
|
||||
where: {
|
||||
channelId,
|
||||
},
|
||||
92
apps/web/src/app/(ui)/(protected)/api/stream/info/route.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
// FIXME: THIS EFFING SUCKS OH MY GOD
|
||||
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { Prisma, prisma } from '@hctv/db';
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
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) {
|
||||
return new Response('No user found in cookies', { status: 401 });
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (isLive) {
|
||||
where.isLive = true;
|
||||
}
|
||||
|
||||
if (channelConditions.length > 0) {
|
||||
where.channel =
|
||||
channelConditions.length === 1 ? channelConditions[0] : { OR: channelConditions };
|
||||
}
|
||||
|
||||
const db = await prisma.streamInfo.findMany({
|
||||
where,
|
||||
include: {
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import fsP from 'fs/promises';
|
||||
import fs from 'fs';
|
||||
|
||||
export async function GET(request: Request, { params }: { params: Promise<{ username: string }> }) {
|
||||
const { username } = await params;
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return new Response("Unauthorized", { status: 401 });
|
||||
}
|
||||
if (username.includes('..')) {
|
||||
return new Response("nuh uh", { status: 403 });
|
||||
}
|
||||
|
||||
const filePath = `/dev/shm/hctv-thumb/${username}.webp`;
|
||||
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return new Response("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
const fileContent = await fsP.readFile(filePath);
|
||||
return new Response(fileContent, {
|
||||
headers: {
|
||||
'Content-Type': 'image/webp',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': 'GET',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createRouteHandler } from "uploadthing/next";
|
||||
|
||||
import { ourFileRouter } from "@/lib/services/uploadthing/fileRouter";
|
||||
|
||||
// Export routes for Next App Router
|
||||
export const { GET, POST } = createRouteHandler({
|
||||
router: ourFileRouter,
|
||||
});
|
||||
42
apps/web/src/app/(ui)/(protected)/layout.tsx
Normal file
@@ -0,0 +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/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;
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { fetcher } from '@/lib/services/swr';
|
||||
import { useConfirm } from '@omit/react-confirm-dialog';
|
||||
import { Plus, RefreshCcw, Trash } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import useSWR from 'swr';
|
||||
import useSWRMutation from 'swr/mutation';
|
||||
|
||||
export function ApiKeys({ slug }: { slug: string }) {
|
||||
const confirm = useConfirm();
|
||||
const [newApiKeyName, setNewApiKeyName] = useState('');
|
||||
const { data, error, isLoading, mutate } = useSWR<GetResponse>(
|
||||
`/api/settings/bot/${slug}/apiKey`,
|
||||
fetcher
|
||||
);
|
||||
const { trigger } = useSWRMutation(`/api/settings/bot/${slug}/apiKey`, createApiKey);
|
||||
|
||||
const apiKeyCreate = () => {
|
||||
if (newApiKeyName.trim().length < 3) {
|
||||
toast.error('API Key name must be at least 3 characters long');
|
||||
return;
|
||||
}
|
||||
if (newApiKeyName.trim().length > 50) {
|
||||
toast.error('API Key name must be at most 50 characters long');
|
||||
return;
|
||||
}
|
||||
trigger({ action: 'create', name: newApiKeyName }).then(
|
||||
async (res: PostResponse) => {
|
||||
if (res.success) {
|
||||
setNewApiKeyName('');
|
||||
await navigator.clipboard
|
||||
.writeText(res.apiKey || '')
|
||||
.then(() => toast.success('API key copied to clipboard'))
|
||||
.catch(() => {
|
||||
alert('Failed to copy API key to clipboard, here it is: ' + res.apiKey);
|
||||
});
|
||||
await mutate();
|
||||
} else {
|
||||
toast.error(res.error || 'Error creating API key');
|
||||
}
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>API Keys</CardTitle>
|
||||
<CardDescription>Manage your API keys</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading && <ApiKeysSkeleton />}
|
||||
{error && <p>Error loading API keys</p>}
|
||||
{data && !data.success && <p>Error: Could not fetch API keys</p>}
|
||||
{data && (
|
||||
<div className="flex">
|
||||
<Input
|
||||
placeholder="New API Key Name"
|
||||
className="flex-1 mr-2"
|
||||
value={newApiKeyName}
|
||||
onChange={(e) => setNewApiKeyName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
apiKeyCreate();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
size="icon"
|
||||
onClick={apiKeyCreate}
|
||||
>
|
||||
<Plus />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{data && data.success && data.apiKeys.length === 0 && <p>No API keys found</p>}
|
||||
{data && data.success && data.apiKeys.length > 0 && (
|
||||
<ul className="space-y-2 pt-4">
|
||||
{data.apiKeys.map((key) => (
|
||||
<li
|
||||
key={key.id}
|
||||
className="flex items-center justify-between p-3 bg-mantle/50 rounded-md"
|
||||
>
|
||||
<div className="flex-1">
|
||||
<strong className="text-sm font-medium">{key.name}</strong>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
const confirmation = await confirm({
|
||||
title: 'Regenerate API Key',
|
||||
description:
|
||||
'Are you sure you want to regenerate this API key? The old key will stop working.',
|
||||
confirmText: 'Regenerate',
|
||||
cancelText: 'Cancel',
|
||||
});
|
||||
if (!confirmation) return;
|
||||
|
||||
trigger({ action: 'regenerate', name: key.name }).then(
|
||||
async (res: PostResponse) => {
|
||||
if (res.success) {
|
||||
await navigator.clipboard
|
||||
.writeText(res.apiKey || '')
|
||||
.then(() => {
|
||||
toast.success('API key copied to clipboard');
|
||||
})
|
||||
.catch(() => {
|
||||
alert(
|
||||
'Failed to copy API key to clipboard, here it is: ' + res.apiKey
|
||||
);
|
||||
});
|
||||
mutate();
|
||||
} else {
|
||||
toast.error(res.error || 'Error regenerating API key');
|
||||
}
|
||||
}
|
||||
);
|
||||
}}
|
||||
>
|
||||
<RefreshCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
const confirmation = await confirm({
|
||||
title: 'Revoke API Key',
|
||||
description:
|
||||
'Are you sure you want to revoke this API key? This action cannot be undone.',
|
||||
confirmText: 'Revoke',
|
||||
cancelText: 'Cancel',
|
||||
});
|
||||
if (!confirmation) return;
|
||||
trigger({ action: 'revoke', name: key.name }).then(
|
||||
async (res: PostResponse) => {
|
||||
if (res.success) {
|
||||
await mutate();
|
||||
} else {
|
||||
toast.error(res.error || 'Error revoking API key');
|
||||
}
|
||||
}
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Trash className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function ApiKeysSkeleton() {
|
||||
return (
|
||||
<>
|
||||
<div className='flex'>
|
||||
<Skeleton className='h-10 flex-1 mr-2' />
|
||||
<Skeleton className='h-10 w-10' />
|
||||
</div>
|
||||
<div className='space-y-2 pt-4'>
|
||||
{[1, 2, 3].map((i) => (
|
||||
<div key={i} className='flex items-center justify-between p-3 bg-mantle/50 rounded-md'>
|
||||
<div className='flex-1'>
|
||||
<Skeleton className='h-4 w-1/2' />
|
||||
</div>
|
||||
<div className='flex items-center space-x-2'>
|
||||
<Skeleton className='h-8 w-8' />
|
||||
<Skeleton className='h-8 w-8' />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
async function createApiKey(url: string, { arg }: { arg: PostRequest }) {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(arg),
|
||||
});
|
||||
return res.json();
|
||||
}
|
||||
|
||||
interface GetResponse {
|
||||
success: boolean;
|
||||
apiKeys: Array<{ id: string; name: string; createdAt: string }>;
|
||||
}
|
||||
|
||||
interface PostRequest {
|
||||
action: 'revoke' | 'regenerate' | 'create';
|
||||
name: string;
|
||||
}
|
||||
interface PostResponse {
|
||||
success: boolean;
|
||||
apiKey?: string;
|
||||
id?: string;
|
||||
error?: string;
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
'use client';
|
||||
import { UniversalForm } from '@/components/app/UniversalForm/UniversalForm';
|
||||
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>
|
||||
<CardTitle>General Settings</CardTitle>
|
||||
<CardDescription>Edit your bot settings!</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<UniversalForm
|
||||
formRef={formRef}
|
||||
fields={[
|
||||
{
|
||||
name: 'from',
|
||||
type: 'hidden',
|
||||
value: props.id,
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: 'name',
|
||||
type: 'text',
|
||||
label: 'Bot Name',
|
||||
placeholder: 'Enter bot name',
|
||||
required: true,
|
||||
value: props.displayName,
|
||||
},
|
||||
{
|
||||
name: 'slug',
|
||||
type: 'text',
|
||||
label: 'Bot Slug',
|
||||
placeholder: 'Enter bot slug',
|
||||
required: true,
|
||||
value: props.slug,
|
||||
},
|
||||
{
|
||||
name: 'description',
|
||||
type: 'textarea',
|
||||
label: 'Description',
|
||||
placeholder: 'Enter bot description',
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
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';
|
||||
import { ApiKeys } from '@/app/(ui)/(protected)/settings/bot/[slug]/apikeys';
|
||||
import Link from 'next/link';
|
||||
import { ArrowLeft } from 'lucide-react';
|
||||
|
||||
export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
|
||||
const { user } = await validateRequest();
|
||||
const { slug } = await params;
|
||||
const bot = await getBotBySlug(slug);
|
||||
|
||||
if (!user || !bot || !can(user, 'update', 'bot', { bot })) {
|
||||
redirect('/settings/bot');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={'container mx-auto py-6 space-y-6'}>
|
||||
<Link href={'/settings/bot'} className="text-sm text-muted-foreground hover:underline flex items-center gap-2">
|
||||
<ArrowLeft className='size-4' /> Back to Bot Accounts
|
||||
</Link>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className={'flex items-center space-x-4'}>
|
||||
<Image
|
||||
src={bot.pfpUrl}
|
||||
alt={'Bot Avatar'}
|
||||
width={48}
|
||||
height={48}
|
||||
className="rounded-full"
|
||||
/>
|
||||
<div className={'flex flex-col'}>
|
||||
<h1 className="text-3xl font-bold tracking-tight">{bot.displayName}</h1>
|
||||
<p className="text-muted-foreground">Manage your bot account settings</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full gap-4 flex-col md:flex-row *:w-1/2">
|
||||
<GeneralSettings {...bot} />
|
||||
<ApiKeys slug={slug} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
'use client';
|
||||
|
||||
import { UniversalForm } from '@/components/app/UniversalForm/UniversalForm';
|
||||
import { createBot } from '@/lib/form/actions';
|
||||
import { Bot } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export default function Page() {
|
||||
const router = useRouter();
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background">
|
||||
<div className="flex h-full w-full flex-col items-center justify-center px-4 py-12">
|
||||
<div className="mb-8 text-center">
|
||||
<div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary shadow-lg">
|
||||
<Bot className="h-8 w-8 text-primary-foreground" />
|
||||
</div>
|
||||
<h1 className="mb-2 text-3xl font-bold text-foreground">Create Bot Account</h1>
|
||||
<p className="text-muted-foreground max-w-xl">
|
||||
Create an automated bot account to provide custom functionality for your community.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="w-full max-w-md bg-card rounded-xl p-8 border border-border">
|
||||
<UniversalForm
|
||||
fields={[
|
||||
{
|
||||
name: 'name',
|
||||
type: 'text',
|
||||
label: 'Bot Name',
|
||||
placeholder: 'Enter bot name',
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: 'slug',
|
||||
type: 'text',
|
||||
label: 'Bot Slug',
|
||||
placeholder: 'Enter bot slug',
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: 'description',
|
||||
type: 'textarea',
|
||||
label: 'Description',
|
||||
placeholder: 'Enter bot description',
|
||||
},
|
||||
]}
|
||||
schemaName={'createBot'}
|
||||
action={createBot}
|
||||
onActionComplete={(res) => {
|
||||
router.push(`/settings/bot/${res.slug}`);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/*
|
||||
<p className="mt-6 text-sm text-muted-foreground text-center max-w-md">
|
||||
Your bot will be created with chat permissions. You can configure advanced settings and
|
||||
permissions after creation.
|
||||
</p>
|
||||
*/}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
88
apps/web/src/app/(ui)/(protected)/settings/bot/page.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import Link from 'next/link';
|
||||
import { Plus, Bot, Calendar, Hash } from 'lucide-react';
|
||||
import { redirect } from 'next/navigation';
|
||||
import Image from 'next/image';
|
||||
|
||||
export default async function Page() {
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
redirect('/');
|
||||
}
|
||||
|
||||
const bots = await prisma.user.findFirst({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
botAccounts: true,
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="container mx-auto py-6 space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Bot Accounts</h1>
|
||||
<p className="text-muted-foreground">Manage your automated bot accounts</p>
|
||||
</div>
|
||||
<Link href="/settings/bot/create">
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Create Bot
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{bots?.botAccounts.length ? (
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{bots.botAccounts.map((bot) => (
|
||||
<Link href={`/settings/bot/${bot.slug}`} key={bot.id}>
|
||||
<Card key={bot.id} className="hover:shadow-md transition-shadow">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Image src={bot.pfpUrl} alt={'Bot Avatar'} width={32} height={32} className="rounded-full" />
|
||||
<CardTitle className="text-lg">{bot.displayName}</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex items-center space-x-2 text-sm text-muted-foreground">
|
||||
<Hash className="h-4 w-4" />
|
||||
<span>{bot.slug}</span>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2 text-sm text-muted-foreground">
|
||||
<Calendar className="h-4 w-4" />
|
||||
<span>{new Date(bot.createdAt).toLocaleDateString()}</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Card className="text-center py-8">
|
||||
<CardContent className="space-y-4">
|
||||
<Bot className="mx-auto h-12 w-12 text-muted-foreground" />
|
||||
<div>
|
||||
<CardTitle>No bot accounts yet</CardTitle>
|
||||
<CardDescription className="mt-2">
|
||||
Get started by creating your first bot account
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Link href="/settings/bot/create">
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Create Your First Bot
|
||||
</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
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,
|
||||
}: {
|
||||
params: Promise<{ channelName: string }>;
|
||||
}) {
|
||||
const { channelName } = await params;
|
||||
const { user } = await validateRequest();
|
||||
|
||||
if (!user) {
|
||||
redirect('/auth/hackclub');
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { name: channelName },
|
||||
include: {
|
||||
owner: true,
|
||||
managers: true,
|
||||
chatModerators: true,
|
||||
chatModeratorBots: true,
|
||||
streamInfo: true,
|
||||
streamKey: true,
|
||||
chatSettings: true,
|
||||
followers: {
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
slack_id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
personalFor: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
redirect('/');
|
||||
}
|
||||
|
||||
const isOwner = channel.ownerId === user.id;
|
||||
|
||||
if (!can(user, 'update', 'channel', { channel })) {
|
||||
redirect('/');
|
||||
}
|
||||
|
||||
const ownerPersonalChannel = await resolvePersonalChannel(channel.ownerId);
|
||||
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}
|
||||
isPersonal={channel.personalFor !== null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
'use client'
|
||||
|
||||
import { UniversalForm } from "@/components/app/UniversalForm/UniversalForm";
|
||||
import { createChannel } from "@/lib/form/actions";
|
||||
import { Hash } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
function CreateChannelPage() {
|
||||
const router = useRouter();
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background">
|
||||
<div className="flex h-full w-full flex-col items-center justify-center px-4 py-12">
|
||||
<div className="mb-8 text-center">
|
||||
<div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary shadow-lg">
|
||||
<Hash className="h-8 w-8 text-primary-foreground" />
|
||||
</div>
|
||||
<h1 className="mb-2 text-3xl font-bold text-foreground">
|
||||
Create New Channel
|
||||
</h1>
|
||||
<p className="text-muted-foreground max-w-xl">
|
||||
IRL hackathons, game streams, and more are allowed! Create another channel apart from your personal one to diversify your content.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="w-full max-w-md bg-card rounded-xl shadow-xl p-8 border border-border">
|
||||
<UniversalForm
|
||||
fields={[
|
||||
{ label: "Channel Name", name: "name", type: "text", placeholder: "Enter channel name" },
|
||||
]}
|
||||
schemaName="createChannel"
|
||||
action={createChannel}
|
||||
onActionComplete={(r) => {
|
||||
const channelName = r.channel;
|
||||
if (channelName) {
|
||||
router.push(`/${channelName}`);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p className="mt-6 text-sm text-muted-foreground text-center max-w-md">
|
||||
Your channel will be ready to go live immediately after creation. You can always customize settings later.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default CreateChannelPage;
|
||||
18
apps/web/src/app/(ui)/(protected)/settings/channel/page.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import { resolvePersonalChannel } from '@/lib/auth/resolve';
|
||||
import { loadSearchParams } from '@/lib/nuqs/channelSettings';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default async function ChannelSettingsRedirector({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
|
||||
}) {
|
||||
const { tab } = await loadSearchParams(searchParams);
|
||||
const personalChannel = await resolvePersonalChannel();
|
||||
if (personalChannel) {
|
||||
return redirect(`/settings/channel/${personalChannel.name}?tab=${tab}`);
|
||||
}
|
||||
|
||||
// lil easter egg i doubt anyone will see
|
||||
return <p>erm</p>;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { notifyStreamToggle } from '@/lib/form/actions';
|
||||
|
||||
export default function NotifyToggle(props: Props) {
|
||||
const [toggled, setToggled] = useState(props.toggled);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const handleToggle = async () => {
|
||||
setIsLoading(true);
|
||||
notifyStreamToggle(props.channel).then((res) => {
|
||||
if (res.success) {
|
||||
setToggled(res.toggle!);
|
||||
}
|
||||
});
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
return <Switch checked={toggled} onCheckedChange={handleToggle} disabled={isLoading} />;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
channel: string;
|
||||
toggled: boolean;
|
||||
}
|
||||
72
apps/web/src/app/(ui)/(protected)/settings/follows/page.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import Link from 'next/link';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import NotifyToggle from './notifyToggle';
|
||||
|
||||
export default async function Page() {
|
||||
const { user } = await validateRequest();
|
||||
const following = await prisma.follow.findMany({
|
||||
where: {
|
||||
userId: user!.id,
|
||||
},
|
||||
include: {
|
||||
channel: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!following.length) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center w-full h-full">
|
||||
<h1 className="text-2xl font-bold">No channels followed</h1>
|
||||
<p className="text-muted-foreground">Go follow some first?</p>
|
||||
<Link href={'/'}>
|
||||
<Button>Back home</Button>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container py-10">
|
||||
<h1 className="text-2xl font-bold mb-6">Followed Channels</h1>
|
||||
<Table className="max-w-2xl mx-auto outline-surface bg-mantle rounded-md overflow-hidden">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Channel</TableHead>
|
||||
<TableHead className="w-[100px] text-center">Notifications</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{following.map((channel) => (
|
||||
<TableRow key={channel.id}>
|
||||
<TableCell className="font-medium">
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="h-9 w-9">
|
||||
<AvatarImage src={channel.channel.pfpUrl} alt={channel.channel.name} />
|
||||
<AvatarFallback>{channel.channel.name.charAt(0)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<Link href={`/${channel.channel.name}`} className="hover:underline">
|
||||
{channel.channel.name}
|
||||
</Link>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<NotifyToggle channel={channel.channel.name} toggled={channel.notifyStream} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
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 "@/lib/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,
|
||||
133
apps/web/src/app/(ui)/(public)/onboarding/page.client.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
'use client';
|
||||
|
||||
import { UniversalForm } from '@/components/app/UniversalForm/UniversalForm';
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from '@/components/ui/card';
|
||||
import { onboard } from '@/lib/form/actions';
|
||||
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();
|
||||
|
||||
return (
|
||||
<div className="min-h-[93vh] flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-2xl space-y-8">
|
||||
{/* welcome header */}
|
||||
<div className="text-center space-y-2">
|
||||
<div className="flex justify-center">
|
||||
<div className="relative">
|
||||
<Avatar className="h-20 w-20 border-4 border-primary/20">
|
||||
<AvatarImage src={user?.pfpUrl} alt={`@${user?.id}`} />
|
||||
<AvatarFallback className="text-2xl font-bold">
|
||||
{user?.id?.charAt(0)?.toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-3xl font-bold tracking-tight">
|
||||
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={BlahajHeart} alt=":blahaj-heart:" height={28} />
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* explanation */}
|
||||
<Card className="border-2 border-primary/10 bg-primary/5">
|
||||
<CardHeader className="pb-4">
|
||||
<CardTitle className="flex items-center gap-2 text-xl">
|
||||
<User className="h-5 w-5 text-primary" />
|
||||
Why do you need a personal channel?
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-primary/10 rounded-lg flex items-center justify-center">
|
||||
<Tv className="w-4 h-4 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-sm">Stream content</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Share your coding sessions and projects!
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-primary/10 rounded-lg flex items-center justify-center">
|
||||
<MessageSquare className="w-4 h-4 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-sm">Chat with others</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Connect with other Hack Clubbers and grow your audience
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-primary/10 rounded-lg flex items-center justify-center">
|
||||
<Heart className="w-4 h-4 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 p-4 bg-secondary/50 rounded-lg border border-muted">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<strong>Your personal channel</strong> is your home base on hctv.
|
||||
It's where your profile, streams, and content will live. You can always create
|
||||
additional channels later for different types of content!
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* form */}
|
||||
<Card className="shadow-lg">
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-xl">Choose Your Channel Username</CardTitle>
|
||||
<CardDescription>
|
||||
This will be your unique identifier on hctv. Choose something memorable!
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<UniversalForm
|
||||
fields={[
|
||||
{ name: 'userId', label: 'User ID', type: 'hidden', value: user?.id },
|
||||
{
|
||||
name: 'username',
|
||||
label: 'Channel Username',
|
||||
type: 'text',
|
||||
placeholder: 'e.g., yourname or yourname-codes',
|
||||
maxChars: 20,
|
||||
inputFilter: /[^a-z0-9_-]/g,
|
||||
},
|
||||
]}
|
||||
schemaName="onboard"
|
||||
action={onboard}
|
||||
onActionComplete={() => {
|
||||
window.location.href = '/';
|
||||
}}
|
||||
/>
|
||||
<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. Up to 20 characters. Must be unique across the platform.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
import { validateRequest } from "@/lib/auth";
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { redirect } from "next/navigation";
|
||||
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 />;
|
||||
55
apps/web/src/app/(ui)/(public)/page.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import LandingPage from '@/components/app/LandingPage/LandingPage';
|
||||
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 Link from 'next/link';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default async function Home() {
|
||||
const { user } = await validateRequest();
|
||||
if (user && !user?.hasOnboarded) {
|
||||
redirect('/onboarding');
|
||||
}
|
||||
|
||||
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 (!liveStreams.length && !offlineStreams.length) {
|
||||
return (
|
||||
<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-3 md:p-6">
|
||||
<StreamGrid liveStreams={liveStreams} offlineStreams={offlineStreams} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
73
apps/web/src/app/(ui)/layout.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { cookies } from 'next/headers';
|
||||
import '../globals.css';
|
||||
import Navbar from '@/components/app/NavBar/NavBar';
|
||||
import { SessionProvider } from '@/lib/providers/SessionProvider';
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
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 EditLivestream from '@/components/app/EditLivestream/EditLivestream';
|
||||
import { StreamInfoProvider } from '@/lib/providers/StreamInfoProvider';
|
||||
import { NextSSRPlugin } from "@uploadthing/react/next-ssr-plugin";
|
||||
import { extractRouterConfig } from 'uploadthing/server';
|
||||
import { ourFileRouter } from '@/lib/services/uploadthing/fileRouter';
|
||||
import { NuqsAdapter } from 'nuqs/adapters/next/app'
|
||||
import SonnerNewVersion from '@/components/app/SonnerNewVersion/SonnerNewVersion';
|
||||
import ConfirmDialogProvider from '@/lib/providers/ConfirmProvider';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'hackclub.tv',
|
||||
description: "Hack Club's livestreaming platform",
|
||||
};
|
||||
|
||||
export default async function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
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="flex h-screen flex-col">
|
||||
<SessionProvider value={sessionData}>
|
||||
<ThemeProvider
|
||||
attribute="class"
|
||||
defaultTheme="system"
|
||||
enableSystem
|
||||
disableTransitionOnChange
|
||||
>
|
||||
<SonnerNewVersion />
|
||||
<NextSSRPlugin
|
||||
routerConfig={extractRouterConfig(ourFileRouter)}
|
||||
/>
|
||||
<ConfirmDialogProvider defaultOptions={{
|
||||
cancelButton: {
|
||||
variant: 'outline',
|
||||
},
|
||||
}}>
|
||||
<NuqsAdapter>
|
||||
<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 min-h-0 min-w-0">
|
||||
{/* pt-16 for navbar height */}
|
||||
<Sidebar className="pt-16" />
|
||||
<main className="flex-1 min-w-0">{children}</main>
|
||||
</div>
|
||||
<Toaster />
|
||||
</StreamInfoProvider>
|
||||
</SidebarProvider>
|
||||
</NuqsAdapter>
|
||||
</ConfirmDialogProvider>
|
||||
</ThemeProvider>
|
||||
</SessionProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
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;
|
||||
}
|
||||