90 Commits

Author SHA1 Message Date
Никита Круглицкий
31460598ba server
All checks were successful
Deploy / deploy (push) Successful in 24s
2025-10-16 22:23:30 +06:00
Никита Круглицкий
4c368458a9 server
All checks were successful
Deploy / deploy (push) Successful in 44s
2025-10-09 23:56:49 +06:00
Никита Круглицкий
aa31e7ad0c server
Some checks failed
Deploy / deploy (push) Failing after 8s
2025-10-09 23:52:08 +06:00
Никита Круглицкий
7b4be60099 server
Some checks failed
Deploy / deploy (push) Failing after 9s
2025-10-09 23:51:17 +06:00
Никита Круглицкий
d5915a9d40 fix migrations
All checks were successful
Deploy / deploy (push) Successful in 45s
2025-10-09 23:19:26 +06:00
Никита Круглицкий
7d4fdfb2e6 add migrations
All checks were successful
Deploy / deploy (push) Successful in 40s
2025-10-09 22:58:48 +06:00
Никита Круглицкий
ad71b15f81 update
All checks were successful
Deploy / deploy (push) Successful in 20s
2025-10-09 22:54:34 +06:00
Никита Круглицкий
a49fe5fc53 update
Some checks failed
Deploy / deploy (push) Failing after 41s
2025-10-09 22:53:20 +06:00
Никита Круглицкий
8f2b9861c2 update
All checks were successful
Deploy / deploy (push) Successful in 49s
2025-10-09 22:47:51 +06:00
Никита Круглицкий
adcc5b65a6 update
All checks were successful
Deploy / deploy (push) Successful in 19s
2025-10-09 22:40:28 +06:00
Никита Круглицкий
b8a21a1451 update
Some checks failed
Deploy / deploy (push) Failing after 13s
2025-10-09 22:37:02 +06:00
Никита Круглицкий
c0969c4494 update
Some checks failed
Deploy / deploy (push) Failing after 15s
2025-10-09 22:35:05 +06:00
Никита Круглицкий
bb48e52a99 update
Some checks failed
Deploy / deploy (push) Failing after 4m2s
2025-10-09 22:29:42 +06:00
Никита Круглицкий
6ada2c3fbd update
All checks were successful
Deploy / deploy (push) Successful in 43s
2025-10-09 06:23:13 +06:00
Никита Круглицкий
e2064dba6c front update
All checks were successful
Deploy / deploy (push) Successful in 38s
2025-10-09 06:14:35 +06:00
Никита Круглицкий
fc43c8df96 server update
Some checks failed
Deploy / deploy (push) Failing after 15s
2025-10-09 06:14:24 +06:00
Никита Круглицкий
6b6a66eef4 server update
All checks were successful
Deploy / deploy (push) Successful in 43s
2025-10-09 06:09:28 +06:00
Никита Круглицкий
5ca3a47d40 front update
All checks were successful
Deploy / deploy (push) Successful in 39s
2025-10-09 04:48:02 +06:00
Никита Круглицкий
484e61f337 front update
All checks were successful
Deploy / deploy (push) Successful in 40s
2025-10-09 04:45:09 +06:00
Никита Круглицкий
196aa36970 front update
All checks were successful
Deploy / deploy (push) Successful in 43s
2025-10-09 04:42:34 +06:00
Никита Круглицкий
7cd4ff72d4 #4
All checks were successful
Deploy / deploy (push) Successful in 45s
2025-10-07 06:13:54 +06:00
Никита Круглицкий
1339a48da0 #4 2025-10-07 06:13:42 +06:00
Никита Круглицкий
ea55b99116 #4
Some checks failed
Deploy / deploy (push) Failing after 7s
2025-10-07 05:39:40 +06:00
Никита Круглицкий
fbbb2b9b8e #4
All checks were successful
Deploy / deploy (push) Successful in 44s
2025-10-06 23:14:32 +06:00
Никита Круглицкий
87b4c1489e #4
All checks were successful
Deploy / deploy (push) Successful in 43s
2025-10-06 23:03:06 +06:00
Никита Круглицкий
d224ccc52e #4
All checks were successful
Deploy / deploy (push) Successful in 45s
2025-10-06 22:52:47 +06:00
Никита Круглицкий
fb5b42e9db front update
All checks were successful
Deploy / deploy (push) Successful in 1m38s
2025-10-05 21:43:28 +06:00
Никита Круглицкий
1ea3b2d376 #4
All checks were successful
Deploy / deploy (push) Successful in 44s
2025-10-05 21:36:28 +06:00
Никита Круглицкий
c370a455bd #4
All checks were successful
Deploy / deploy (push) Successful in 42s
2025-10-05 07:29:41 +06:00
Никита Круглицкий
189404e22c #4
All checks were successful
Deploy / deploy (push) Successful in 44s
2025-10-04 23:59:48 +06:00
Никита Круглицкий
80c53a079b #4
All checks were successful
Deploy / deploy (push) Successful in 44s
2025-10-04 22:44:55 +06:00
Никита Круглицкий
e6a274cc9d #6
All checks were successful
Deploy / deploy (push) Successful in 1m6s
2025-10-04 02:53:42 +06:00
Никита Круглицкий
c365f3e885 #4
All checks were successful
Deploy / deploy (push) Successful in 44s
2025-10-03 02:36:38 +06:00
Никита Круглицкий
7cecf0641f #4
All checks were successful
Deploy / deploy (push) Successful in 29s
2025-10-03 02:05:50 +06:00
Никита Круглицкий
423fa3b62a #4
All checks were successful
Deploy / deploy (push) Successful in 33s
2025-10-03 02:01:12 +06:00
Никита Круглицкий
0a8015528d #4
All checks were successful
Deploy / deploy (push) Successful in 30s
2025-10-03 01:53:36 +06:00
Никита Круглицкий
c9feff7224 №4
All checks were successful
Deploy / deploy (push) Successful in 30s
2025-10-02 23:57:54 +06:00
Никита Круглицкий
7294e56778 №4
All checks were successful
Deploy / deploy (push) Successful in 22s
2025-10-02 23:55:04 +06:00
Никита Круглицкий
8e19f55dc0 №4
All checks were successful
Deploy / deploy (push) Successful in 3m59s
2025-10-02 23:39:59 +06:00
Никита Круглицкий
a01f8857ab #2 update
All checks were successful
Deploy / deploy (push) Successful in 49s
2025-10-02 04:38:33 +06:00
Никита Круглицкий
e66493b733 #2 update
All checks were successful
Deploy / deploy (push) Successful in 45s
2025-10-02 04:33:29 +06:00
Никита Круглицкий
496e2ec4ef #2 update
All checks were successful
Deploy / deploy (push) Successful in 44s
2025-10-02 04:29:43 +06:00
Никита Круглицкий
c442e1aa47 #2 #3 update
All checks were successful
Deploy / deploy (push) Successful in 48s
2025-10-02 04:22:10 +06:00
Никита Круглицкий
6d4076969e #2 update
All checks were successful
Deploy / deploy (push) Successful in 23s
2025-10-02 03:54:35 +06:00
Никита Круглицкий
b24a30314f #2 update
All checks were successful
Deploy / deploy (push) Successful in 13s
2025-10-02 03:47:50 +06:00
Никита Круглицкий
aa257565fb #2 update 2025-10-02 03:47:30 +06:00
Никита Круглицкий
fac2870604 #2 update
Some checks failed
Deploy / deploy (push) Has been cancelled
2025-10-02 03:31:49 +06:00
Никита Круглицкий
5cdf7f13a6 #2 update
All checks were successful
Deploy / deploy (push) Successful in 20s
2025-10-02 03:16:25 +06:00
Никита Круглицкий
4edd8287b4 #3 update
All checks were successful
Deploy / deploy (push) Successful in 20s
2025-10-02 00:09:06 +06:00
Никита Круглицкий
d7d4df3d51 #3 update
All checks were successful
Deploy / deploy (push) Successful in 27s
2025-10-02 00:07:35 +06:00
Никита Круглицкий
7f74b14f2c #3 update
Some checks failed
Deploy / deploy (push) Failing after 12s
2025-10-02 00:04:30 +06:00
Никита Круглицкий
3645d033b4 #3 update 2025-10-02 00:03:36 +06:00
Никита Круглицкий
72d2f84cce #3 update
All checks were successful
Deploy / deploy (push) Successful in 29s
2025-10-02 00:00:58 +06:00
Никита Круглицкий
d2b52c476a #3 update
All checks were successful
Deploy / deploy (push) Successful in 26s
2025-10-01 23:59:59 +06:00
Никита Круглицкий
198c04a616 #3 update
All checks were successful
Deploy / deploy (push) Successful in 27s
2025-10-01 23:58:25 +06:00
Никита Круглицкий
86f9ccb5cd #3 update
All checks were successful
Deploy / deploy (push) Successful in 29s
2025-10-01 23:57:19 +06:00
Никита Круглицкий
e201aed526 #3 update
All checks were successful
Deploy / deploy (push) Successful in 30s
2025-10-01 23:56:13 +06:00
Никита Круглицкий
8f24f6c1e9 #3 update
All checks were successful
Deploy / deploy (push) Successful in 29s
2025-10-01 23:50:19 +06:00
Никита Круглицкий
270b186f06 #3 update
All checks were successful
Deploy / deploy (push) Successful in 31s
2025-10-01 23:47:48 +06:00
Никита Круглицкий
cd1c023d03 #3 update
All checks were successful
Deploy / deploy (push) Successful in 31s
2025-10-01 23:24:27 +06:00
Никита Круглицкий
8d987c00a8 #3 update
All checks were successful
Deploy / deploy (push) Successful in 30s
2025-10-01 23:15:05 +06:00
Никита Круглицкий
56b3b3a5b5 #3 update
All checks were successful
Deploy / deploy (push) Successful in 31s
2025-10-01 23:10:09 +06:00
Никита Круглицкий
3558944c3f #3 update
All checks were successful
Deploy / deploy (push) Successful in 29s
2025-10-01 22:58:15 +06:00
Никита Круглицкий
45acafb06c #2 #3 update 2025-10-01 22:56:42 +06:00
Никита Круглицкий
ea3f9f2876 #3 update
All checks were successful
Deploy / server (push) Successful in 18s
Deploy / client (push) Successful in 28s
2025-10-01 21:58:05 +06:00
Никита Круглицкий
3323287872 #3 update
All checks were successful
Deploy / server (push) Successful in 15s
Deploy / client (push) Successful in 49s
2025-10-01 21:56:04 +06:00
Никита Круглицкий
5f5ddc0186 #2 #3 update
Some checks failed
Deploy / server (push) Successful in 3m50s
Deploy / client (push) Failing after 49s
2025-10-01 21:47:51 +06:00
Никита Круглицкий
3b7d5f7934 #3 update
Some checks failed
Deploy / server (push) Successful in 21s
Deploy / client (push) Failing after 34s
2025-10-01 21:45:55 +06:00
Никита Круглицкий
a85ec48203 #3 update
Some checks failed
Deploy / server (push) Successful in 16s
Deploy / client (push) Failing after 39s
2025-10-01 21:40:35 +06:00
Никита Круглицкий
514849a3bb #3 update
Some checks failed
Deploy / server (push) Successful in 18s
Deploy / client (push) Failing after 53s
2025-10-01 21:37:25 +06:00
Никита Круглицкий
c0898d0df2 #2, #3 update
Some checks failed
Deploy / server (push) Successful in 4m5s
Deploy / client (push) Failing after 36s
2025-10-01 21:31:16 +06:00
Никита Круглицкий
6110a17533 #2 update
All checks were successful
Deploy / server (push) Successful in 15s
2025-10-01 20:50:08 +06:00
Никита Круглицкий
b6f9b60dea #2 update
All checks were successful
Deploy / server (push) Successful in 26s
2025-10-01 20:48:52 +06:00
Никита Круглицкий
7066d89440 #2 update
All checks were successful
Deploy / server (push) Successful in 15s
2025-10-01 20:42:25 +06:00
Никита Круглицкий
e1c9e3969d #2 update
All checks were successful
Deploy / server (push) Successful in 19s
2025-10-01 20:38:48 +06:00
Никита Круглицкий
07c7c4b9f4 #2 update
All checks were successful
Deploy / server (push) Successful in 3m1s
2025-10-01 20:18:15 +06:00
Никита Круглицкий
98d8e76484 #2 update
All checks were successful
Deploy / server (push) Successful in 20s
2025-10-01 20:14:18 +06:00
Никита Круглицкий
892d7ffb5d #2 update
All checks were successful
Deploy / server (push) Successful in 14s
2025-10-01 20:11:37 +06:00
Никита Круглицкий
e33dbde806 #2 update
Some checks failed
Deploy / server (push) Failing after 12s
2025-10-01 20:10:47 +06:00
Никита Круглицкий
2ef8a428d9 #2 update
Some checks failed
Deploy / server (push) Failing after 4m9s
2025-10-01 20:05:45 +06:00
Никита Круглицкий
a88515f349 #2 update
Some checks failed
Deploy / server (push) Failing after 18s
2025-10-01 20:04:42 +06:00
Никита Круглицкий
46c76269bd #2 update
Some checks failed
Deploy / server (push) Failing after 22s
2025-10-01 19:41:05 +06:00
Никита Круглицкий
20baa6c384 #2 update
Some checks failed
Deploy / server (push) Failing after 2m12s
2025-10-01 19:29:30 +06:00
Никита Круглицкий
81d40001fa #2 update
Some checks failed
Deploy / server (push) Failing after 28s
2025-10-01 19:27:57 +06:00
Никита Круглицкий
b077ae3f24 #2 update
Some checks failed
Deploy / server (push) Failing after 4m5s
2025-10-01 19:18:10 +06:00
Никита Круглицкий
931a5206b6 #2 update
Some checks failed
Deploy / server (push) Failing after 19s
2025-10-01 19:16:31 +06:00
Никита Круглицкий
a030614032 #2 update
Some checks failed
Deploy / server (push) Failing after 37s
2025-10-01 19:15:21 +06:00
Никита Круглицкий
9119951905 #2 update
Some checks failed
Deploy / server (push) Failing after 18s
2025-10-01 19:14:00 +06:00
Никита Круглицкий
f324c60f69 #2 update
Some checks failed
Deploy / server (push) Failing after 17s
2025-10-01 19:09:56 +06:00
Никита Круглицкий
831efd4849 #2 update 2025-10-01 19:09:49 +06:00
59 changed files with 7825 additions and 333 deletions

View File

@@ -0,0 +1,43 @@
name: Deploy
on:
push:
branches:
- master
paths:
- '.gitea/workflows/deploy-client.yml'
- 'client/**'
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Keyscan
run: |
ssh-keyscan git.koptilnya.xyz >> ~/.ssh/known_hosts
- name: Checkout
uses: actions/checkout@v4
with:
ssh-key: ${{ secrets.SSH_PRIVATE_KEY }}
ssh-strict: false
persist-credentials: false
- name: Build
run: docker build -t chad-client ./client --build-arg COMMIT_SHA=${{ gitea.sha }}
- name: Stop old container
run: docker rm -f chad-client || true
- name: Run
run: |
docker run -d \
--name chad-client \
--network traefik \
--label "traefik.enable=true" \
--label "traefik.http.routers.chad-client.rule=Host(\`chad.koptilnya.xyz\`)" \
--label "traefik.http.routers.chad-client.entrypoints=websecure" \
--label "traefik.http.routers.chad-client.tls.certresolver=myresolver" \
--label "traefik.http.services.chad-client.loadbalancer.server.port=80" \
chad-client:latest

View File

@@ -4,9 +4,12 @@ on:
push: push:
branches: branches:
- master - master
paths:
- '.gitea/workflows/deploy-server.yml'
- 'server/**'
jobs: jobs:
server: deploy:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@@ -21,6 +24,9 @@ jobs:
ssh-strict: false ssh-strict: false
persist-credentials: false persist-credentials: false
# - name: Backup DB
# run: cp /home/koptilnya/services/chad/data/database.db /home/koptilnya/services/chad/database-$(date+"%d-%m-%Y").db
- name: Build - name: Build
run: docker build -t chad-server ./server run: docker build -t chad-server ./server
@@ -32,9 +38,12 @@ jobs:
docker run -d \ docker run -d \
--name chad-server \ --name chad-server \
--network traefik \ --network traefik \
--volume /home/koptilnya/services/chad/data:/app/data \
-p 40000-40100:40000-40100/udp \
--label "traefik.enable=true" \ --label "traefik.enable=true" \
--label "traefik.http.routers.chad-server.rule=Host(`api.koptilnya.xyz`) && PathPrefix(`/chad`)" --label "traefik.http.routers.chad-server.rule=Host(\`api.koptilnya.xyz\`) && PathPrefix(\`/chad\`)" \
--label "traefik.http.routers.chad-server.entrypoints=websecure" \ --label "traefik.http.routers.chad-server.entrypoints=websecure" \
--label "traefik.http.routers.chad-server.tls=true" \
--label "traefik.http.routers.chad-server.tls.certresolver=myresolver" \ --label "traefik.http.routers.chad-server.tls.certresolver=myresolver" \
--label "traefik.http.services.chad-server.loadbalancer.server.port=80" \ --label "traefik.http.services.chad-server.loadbalancer.server.port=80" \
chad-server:latest chad-server:latest

Binary file not shown.

24
client/Dockerfile Normal file
View File

@@ -0,0 +1,24 @@
FROM node:lts-alpine AS builder
WORKDIR /app
RUN corepack enable
RUN yarn set version stable
COPY package.json yarn.lock .yarnrc.yml ./
RUN yarn install
COPY . .
ARG COMMIT_SHA=unknown
ENV COMMIT_SHA=$COMMIT_SHA
RUN yarn generate
FROM nginx:stable-alpine
COPY --from=builder /app/.output/public /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

View File

@@ -1,13 +1,7 @@
<template> <template>
<h1>yo</h1> <NuxtLayout>
<pre>{{ connected }}</pre> <NuxtPage />
<audio v-for="(s, i) in streams" :key="i" :ref="(el) => onAudioRef(el, s)" autoplay controls /> </NuxtLayout>
<PrimeToast position="bottom-center" />
</template> </template>
<script lang="ts" setup>
const { connected, streams } = useMediasoup()
function onAudioRef(ref: Element, stream: MediaStream) {
(ref as HTMLAudioElement).srcObject = stream
}
</script>

View File

@@ -0,0 +1,13 @@
html,
body {
font-family: 'Inter', sans-serif;
font-size: 16px;
height: 100%;
overflow: hidden;
}
#__nuxt {
height: 100%;
}

View File

@@ -0,0 +1 @@
@import 'primeicons/primeicons.css';

View File

@@ -0,0 +1,2 @@
@import "tailwindcss";
@import "tailwindcss-primeui";

25
client/app/components.d.ts vendored Normal file
View File

@@ -0,0 +1,25 @@
/* eslint-disable */
// @ts-nocheck
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
// biome-ignore lint: disable
export {}
/* prettier-ignore */
declare module 'vue' {
export interface GlobalComponents {
PrimeAvatar: typeof import('primevue/avatar')['default']
PrimeBadge: typeof import('primevue/badge')['default']
PrimeButton: typeof import('primevue/button')['default']
PrimeButtonGroup: typeof import('primevue/buttongroup')['default']
PrimeCard: typeof import('primevue/card')['default']
PrimeFieldset: typeof import('primevue/fieldset')['default']
PrimeFloatLabel: typeof import('primevue/floatlabel')['default']
PrimeInputText: typeof import('primevue/inputtext')['default']
PrimeMenu: typeof import('primevue/menu')['default']
PrimeSlider: typeof import('primevue/slider')['default']
PrimeToast: typeof import('primevue/toast')['default']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
}
}

View File

@@ -0,0 +1,25 @@
<template>
<div
class="flex items-center justify-between gap-2 border-b-2 border-surface-800 px-3 py-3"
:class="{
'bg-surface-950': !secondary,
'bg-surface-900': secondary,
}"
style="height: 75px;"
>
<slot name="left">
<h1>
{{ title }}
</h1>
</slot>
<slot name="right" />
</div>
</template>
<script setup lang="ts">
defineProps<{
title: string
secondary?: boolean
}>()
</script>

View File

@@ -0,0 +1,89 @@
<template>
<div class="py-3">
<div class="flex items-center gap-3 ">
<PrimeAvatar
icon="pi pi-user"
size="small"
/>
<div class="flex-1">
<div class="text-sm leading-5 font-medium text-color whitespace-nowrap overflow-ellipsis">
{{ client.username }}
</div>
<div class="mt-1 text-xs leading-5 text-muted-color">
{{ client.id }}
</div>
</div>
<PrimeBadge v-if="client.isMe && inputMuted" severity="info" value="Muted" />
<PrimeBadge v-if="client.isMe" severity="secondary" value="You" />
<template v-if="!client.isMe">
<PrimeButton icon="pi pi-ellipsis-h" text size="small" severity="contrast" @click="menuRef?.toggle" />
<PrimeMenu ref="menu" popup :model="menuItems" style="translate: calc(-100% + 2rem) 0.5rem">
<template #start>
<div class="px-4 py-3">
<div class="flex justify-between">
<span>Volume</span>
<span>{{ volume }}</span>
</div>
<PrimeSlider v-model="volume" class="mt-4" :min="0" :max="1000" :step="volume < 200 ? 5 : 25" />
</div>
</template>
</PrimeMenu>
</template>
</div>
</div>
</template>
<script setup lang="ts">
import type { ChadClient } from '#shared/types'
import type { MenuItem } from 'primevue/menuitem'
const props = defineProps<{
client: ChadClient
}>()
const { inputMuted, outputMuted } = useApp()
const { getClientConsumers } = useMediasoup()
const menuRef = useTemplateRef<HTMLAudioElement>('menu')
const volume = ref(100)
const menuItems: MenuItem[] = [
{
label: 'Mute',
icon: 'pi pi-headphones',
},
{
label: 'DM',
icon: 'pi pi-comment',
disabled: true,
},
]
const audioConsumer = computed(() => {
const consumers = getClientConsumers(props.client.id)
return consumers.find(consumer => consumer.track.kind === 'audio')
})
const audioTrack = computed(() => {
return audioConsumer.value?.track
})
const { setGain } = useAudioContext(audioTrack)
watch(volume, (volume) => {
if (outputMuted.value)
return
setGain(volume * 0.01)
})
watch(outputMuted, (outputMuted) => {
setGain(outputMuted ? 0 : (volume.value * 0.01))
})
</script>

View File

@@ -0,0 +1,86 @@
import { createGlobalState } from '@vueuse/core'
import { useClients } from '~/composables/use-clients'
export const useApp = createGlobalState(() => {
const { clients } = useClients()
const mediasoup = useMediasoup()
const toast = useToast()
const inputMuted = ref(false)
const outputMuted = ref(false)
const previousInputMuted = ref(inputMuted.value)
const me = computed(() => clients.value.find(client => client.isMe))
function muteInput() {
inputMuted.value = true
}
function unmuteInput() {
inputMuted.value = false
}
function toggleInput() {
if (inputMuted.value)
unmuteInput()
else
muteInput()
}
function muteOutput() {
outputMuted.value = true
}
function unmuteOutput() {
outputMuted.value = false
}
function toggleOutput() {
if (outputMuted.value)
unmuteOutput()
else
muteOutput()
}
watch(inputMuted, async (inputMuted) => {
if (inputMuted) {
await mediasoup.muteMic()
}
else {
if (outputMuted.value) {
outputMuted.value = false
}
await mediasoup.unmuteMic()
}
const toastText = inputMuted ? 'Microphone muted' : 'Microphone activated'
toast.add({ severity: 'info', summary: toastText, closable: false, life: 1000 })
})
watch(outputMuted, (outputMuted) => {
if (outputMuted) {
previousInputMuted.value = inputMuted.value
muteInput()
}
else {
inputMuted.value = previousInputMuted.value
}
const toastText = outputMuted ? 'Sound muted' : 'Sound resumed'
toast.add({ severity: 'info', summary: toastText, closable: false, life: 1000 })
})
return {
clients,
me,
inputMuted,
muteInput,
unmuteInput,
toggleInput,
outputMuted,
muteOutput,
unmuteOutput,
toggleOutput,
}
})

View File

@@ -0,0 +1,59 @@
import { useEventListener } from '@vueuse/core'
export default function useAudioContext(audioTrack: Ref<MediaStreamTrack | undefined>) {
const ctx = new (window.AudioContext || window.webkitAudioContext)()
const stream = new MediaStream()
const sourceNode = shallowRef<MediaStreamAudioSourceNode>()
const gainNode = ctx.createGain()
let hackExecuted = false
watch(audioTrack, (track, prevTrack) => {
if (prevTrack)
stream.removeTrack(prevTrack)
if (!track)
return
stream.addTrack(track)
if (!hackExecuted) {
const audioEl = new Audio()
audioEl.srcObject = stream
audioEl.muted = true
hackExecuted = true
}
sourceNode.value = ctx.createMediaStreamSource(stream)
connect()
}, { immediate: true })
useEventListener(document, 'click', async () => {
if (ctx.state === 'suspended') {
await ctx.resume()
}
connect()
}, { once: true })
function connect() {
if (!sourceNode.value || ctx.state === 'suspended')
return
sourceNode.value.connect(gainNode)
gainNode.connect(ctx.destination)
ctx.resume()
}
function setGain(value: number) {
gainNode.gain.value = value
}
return {
setGain,
}
}

View File

@@ -0,0 +1,58 @@
import type { ChadClient, UpdatedClient } from '#shared/types'
import { createGlobalState } from '@vueuse/core'
export const useClients = createGlobalState(() => {
const signaling = useSignaling()
const toast = useToast()
const clients = shallowRef<ChadClient[]>([])
watch(signaling.socket, (socket) => {
if (!socket)
return
socket.on('clientChanged', (clientId: ChadClient['id'], updatedClient: UpdatedClient) => {
const client = getClient(clientId)
updateClient(clientId, updatedClient)
if (updatedClient.username)
toast.add({ severity: 'info', summary: `${client?.username} is now ${updatedClient.username}`, closable: false, life: 1000 })
})
})
function getClient(clientId: ChadClient['id']) {
return clients.value.find(client => client.id === clientId)
}
function addClient(...client: ChadClient[]) {
clients.value.push(...client)
triggerRef(clients)
}
function removeClient(clientId: ChadClient['id']) {
clients.value = clients.value.filter(client => client.id !== clientId)
}
function updateClient(clientId: ChadClient['id'], updatedClient: UpdatedClient) {
const clientIdx = clients.value.findIndex(client => client.id === clientId)
if (clientIdx === -1)
return
clients.value[clientIdx] = {
...clients.value[clientIdx],
...updatedClient,
} as ChadClient
triggerRef(clients)
}
return {
clients,
getClient,
addClient,
removeClient,
updateClient,
}
})

View File

@@ -1,122 +1,337 @@
import type { Socket } from 'socket.io-client' import type { ChadClient, RemoteClient } from '#shared/types'
import { createGlobalState } from '@vueuse/core' import { createSharedComposable } from '@vueuse/core'
import * as mediasoupClient from 'mediasoup-client' import * as mediasoupClient from 'mediasoup-client'
import { io } from 'socket.io-client' import { usePreferences } from '~/composables/use-preferences'
import { useSignaling } from '~/composables/use-signaling'
export const useMediasoup = createGlobalState(() => { const ICE_SERVERS: RTCIceServer[] = [
const socket: Socket = io('http://localhost:1337', { { urls: 'stun:stun.l.google.com:19302' },
transports: ['websocket'], { urls: 'stun:stun.l.google.com:5349' },
}) { urls: 'stun:stun1.l.google.com:3478' },
{ urls: 'stun:stun1.l.google.com:5349' },
{ urls: 'stun:stun2.l.google.com:19302' },
{ urls: 'stun:stun2.l.google.com:5349' },
{ urls: 'stun:stun3.l.google.com:3478' },
{ urls: 'stun:stun3.l.google.com:5349' },
{ urls: 'stun:stun4.l.google.com:19302' },
{ urls: 'stun:stun4.l.google.com:5349' },
]
const initializing = ref(false) export const useMediasoup = createSharedComposable(() => {
const connected = ref(false) const toast = useToast()
const streams = shallowRef<MediaStream[]>([])
let device: mediasoupClient.Device
let sendTransport: mediasoupClient.types.Transport
let recvTransport: mediasoupClient.types.Transport
socket.on('newProducer', async ({ producerId }) => { const signaling = useSignaling()
const params = await socket.emitWithAck('consume', { const { addClient, removeClient } = useClients()
producerId, const preferences = usePreferences()
transportId: recvTransport.id,
rtpCapabilities: device.rtpCapabilities,
})
if (params?.error) { const device = shallowRef<mediasoupClient.Device>()
console.error('consume error:', params.error) const rtpCapabilities = shallowRef<mediasoupClient.types.RtpCapabilities>()
const sendTransport = shallowRef<mediasoupClient.types.Transport>()
const recvTransport = shallowRef<mediasoupClient.types.Transport>()
const micProducer = shallowRef<mediasoupClient.types.Producer>()
const webcamProducer = shallowRef<mediasoupClient.types.Producer>()
const shareProducer = shallowRef<mediasoupClient.types.Producer>()
const consumers = shallowRef<Map<string, mediasoupClient.types.Consumer>>(new Map())
const producers = shallowRef<Map<string, mediasoupClient.types.Producer>>(new Map())
watch(signaling.socket, (socket) => {
if (!socket)
return return
}
const consumer = await recvTransport.consume(params) socket.on('connect', async () => {
const stream = new MediaStream([consumer.track]) if (!signaling.socket.value)
return
streams.value.push(stream) device.value = new mediasoupClient.Device()
triggerRef(streams) rtpCapabilities.value = await signaling.socket.value.emitWithAck('getRtpCapabilities')
await device.value.load({ routerRtpCapabilities: rtpCapabilities.value! })
// Send transport
{
const transportInfo = await signaling.socket.value.emitWithAck('createTransport', { producing: true, consuming: false })
sendTransport.value = device.value.createSendTransport({
...transportInfo,
iceServers: [
...ICE_SERVERS,
...(transportInfo.iceServers ?? []),
],
}) })
async function loadDevice() { sendTransport.value.on('connect', async ({ dtlsParameters }, callback, errback) => {
device = new mediasoupClient.Device()
const rtpCapabilities = await socket.emitWithAck('getRtpCapabilities')
await device.load({ routerRtpCapabilities: rtpCapabilities })
}
async function createSendTransport() {
const params = await socket.emitWithAck('createTransport')
sendTransport = device.createSendTransport(params)
sendTransport.on('connect', async ({ dtlsParameters }, callback, errback) => {
try { try {
await socket.emitWithAck('connectTransport', { await signaling.socket.value!.emitWithAck('connectTransport', {
transportId: sendTransport.id, transportId: sendTransport.value!.id,
dtlsParameters, dtlsParameters,
}) })
callback() callback()
} }
catch (err) { catch (error) {
errback(err) if (error instanceof Error) {
errback(error)
}
} }
}) })
sendTransport.on('produce', async ({ kind, rtpParameters }, callback, errback) => { sendTransport.value.on('produce', async ({ kind, rtpParameters, appData }, callback, errback) => {
try { try {
const { id } = await socket.emitWithAck('produce', { const { id } = await signaling.socket.value!.emitWithAck('produce', {
transportId: sendTransport.id, transportId: sendTransport.value!.id,
kind, kind,
rtpParameters, rtpParameters,
appData,
}) })
callback({ id }) callback({ id })
} }
catch (err) { catch (error) {
errback(err) if (error instanceof Error) {
errback(error)
}
} }
}) })
} }
async function publishMic() { // Recv Transport
const stream = await navigator.mediaDevices.getUserMedia({ audio: true }) {
const track = stream.getAudioTracks()[0] const transportInfo = await signaling.socket.value.emitWithAck('createTransport', { producing: false, consuming: true })
recvTransport.value = device.value.createRecvTransport({
...transportInfo,
iceServers: [
...ICE_SERVERS,
...(transportInfo.iceServers ?? []),
],
})
await sendTransport.produce({ track }) recvTransport.value.on('connect', async ({ dtlsParameters }, callback, errback) => {
}
async function createRecvTransport() {
const params = await socket.emitWithAck('createTransport')
recvTransport = device.createRecvTransport(params)
recvTransport.on('connect', async ({ dtlsParameters }, callback, errback) => {
try { try {
await socket.emitWithAck('connectTransport', { await signaling.socket.value!.emitWithAck('connectTransport', {
transportId: recvTransport.id, transportId: recvTransport.value!.id,
dtlsParameters, dtlsParameters,
}) })
callback() callback()
} }
catch (err) { catch (error) {
errback(err) if (error instanceof Error) {
errback(error)
}
} }
}) })
} }
(async () => { const joinedClients = (await signaling.socket.value.emitWithAck('join', {
if (initializing.value || connected.value) username: preferences.username.value,
rtpCapabilities: rtpCapabilities.value,
})).map(transformClient)
addClient(...joinedClients)
toast.add({ severity: 'success', summary: 'Joined', closable: false, life: 1000 })
await enableMic()
})
socket.on('newPeer', (client) => {
addClient(transformClient(client))
})
socket.on('peerClosed', (id) => {
removeClient(id)
})
socket.on(
'newConsumer',
async (
{ id, producerId, kind, rtpParameters, peerId: clientId, appData },
cb,
) => {
if (!recvTransport.value)
return return
initializing.value = true const consumer = await recvTransport.value.consume({
connected.value = false id,
producerId,
kind,
rtpParameters,
streamId: `${clientId}-${appData.share ? 'share' : 'mic-webcam'}`,
appData: { ...appData, clientId },
})
await loadDevice() consumer.on('transportclose', () => {
await createSendTransport() consumers.value.delete(consumer.id)
await createRecvTransport() triggerRef(consumers)
await publishMic() })
initializing.value = false consumers.value.set(consumer.id, consumer)
connected.value = true triggerRef(consumers)
})()
cb()
},
)
socket.on(
'consumerClosed',
async (
{ consumerId },
) => {
const consumer = consumers.value.get(consumerId)
if (!consumer)
return
consumers.value.delete(consumer.id)
triggerRef(consumers)
},
)
socket.on('disconnect', () => {
sendTransport.value?.close()
sendTransport.value = undefined
recvTransport.value?.close()
recvTransport.value = undefined
})
}, { immediate: true, flush: 'sync' })
function getClientConsumers(clientId: ChadClient['id']) {
return consumers.value.values().filter(consumer => consumer.appData.clientId === clientId)
}
async function enableMic() {
if (micProducer.value)
return
if (!device.value || !sendTransport.value)
return
if (!device.value.canProduce('audio'))
return
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
autoGainControl: false,
noiseSuppression: true,
echoCancellation: false,
channelCount: 2,
},
})
const track = stream.getAudioTracks()[0]
if (!track)
return
micProducer.value = await sendTransport.value.produce({
track,
codecOptions: {
opusStereo: true,
opusDtx: true, // Меньше пакетов летит когда тишина
opusFec: false, // Фиксит пакет лос
},
})
producers.value.set(micProducer.value.id, micProducer.value)
triggerRef(producers)
micProducer.value.on('transportclose', () => {
micProducer.value = undefined
})
micProducer.value.on('trackended', () => {
disableMic()
})
}
async function disableMic() {
if (!signaling.socket.value || !micProducer.value)
return
producers.value.delete(micProducer.value.id)
triggerRef(producers)
try {
micProducer.value.close()
await signaling.socket.value.emitWithAck('closeProducer', {
producerId: micProducer.value.id,
})
}
catch {
}
micProducer.value = undefined
}
async function muteMic() {
if (!signaling.socket.value || !micProducer.value)
return
try {
micProducer.value.pause()
await signaling.socket.value.emitWithAck('pauseProducer', {
producerId: micProducer.value.id,
})
}
catch {
}
}
async function unmuteMic() {
if (!signaling.socket.value || !micProducer.value)
return
try {
micProducer.value.resume()
await signaling.socket.value.emitWithAck('resumeProducer', {
producerId: micProducer.value.id,
})
}
catch {
}
}
async function init() {
signaling.connect()
}
function transformClient(client: RemoteClient): ChadClient {
return {
...client,
isMe: client.id === signaling.socket.value!.id,
}
}
function dispose() {
device.value = undefined
rtpCapabilities.value = undefined
sendTransport.value = undefined
recvTransport.value = undefined
micProducer.value = undefined
webcamProducer.value = undefined
shareProducer.value = undefined
consumers.value = new Map()
producers.value = new Map()
}
return { return {
connected, init,
streams, consumers,
producers,
sendTransport,
recvTransport,
rtpCapabilities,
device,
micProducer,
webcamProducer,
shareProducer,
getClientConsumers,
muteMic,
unmuteMic,
} }
}) })

View File

@@ -0,0 +1,14 @@
import { createGlobalState, useLocalStorage } from '@vueuse/core'
export const usePreferences = createGlobalState(() => {
const username = useLocalStorage<string>('username', '')
const audioDevice = shallowRef()
const videoDevice = shallowRef()
return {
username,
audioDevice,
videoDevice,
}
})

View File

@@ -0,0 +1,67 @@
import type { Socket } from 'socket.io-client'
import { createSharedComposable } from '@vueuse/core'
import { io } from 'socket.io-client'
export const useSignaling = createSharedComposable(() => {
const toast = useToast()
const socket = shallowRef<Socket>()
const connected = ref(false)
watch(socket, (socket, prevSocket) => {
if (prevSocket) {
prevSocket.close()
}
if (!socket) {
return
}
if (import.meta.dev) {
socket.onAny((event, ...args) => {
console.info('[onAny]', event, args)
})
socket.onAnyOutgoing((event, ...args) => {
console.info('[onAnyOutgoing]', event, args)
})
}
socket.on('connect', async () => {
connected.value = true
})
socket.on('disconnect', async () => {
connected.value = false
})
}, { immediate: true, flush: 'sync' })
watch(connected, (connected) => {
if (connected)
toast.add({ severity: 'success', summary: 'Connected', closable: false, life: 1000 })
else
toast.add({ severity: 'error', summary: 'Disconnected', closable: false, life: 1000 })
}, { immediate: true })
onScopeDispose(() => {
socket.value?.close()
})
function connect() {
if (socket.value)
return
socket.value = io('https://api.koptilnya.xyz/webrtc', {
// socket.value = io('http://127.0.0.1:4000/webrtc', {
path: '/chad/ws',
transports: ['websocket'],
})
}
return {
socket,
connected,
connect,
}
})

View File

@@ -0,0 +1,5 @@
<template>
<div class="w-full h-full flex justify-center items-center p-3">
<slot />
</div>
</template>

View File

@@ -0,0 +1,46 @@
<template>
<div v-auto-animate class="grid grid-cols-2 h-screen">
<div class="flex flex-col shadow-xl shadow-surface-950 overflow-y-hidden">
<AppHeader title="Шальные сиськи 18+">
<template #right>
<PrimeButtonGroup class="ml-auto">
<PrimeButton
icon="pi pi-microphone" size="large" :severity="inputMuted ? 'contrast' : 'secondary'"
:outlined="!inputMuted" @click="toggleInput"
/>
<PrimeButton
icon="pi pi-headphones" size="large" :severity="outputMuted ? 'contrast' : 'secondary'"
:outlined="!outputMuted" @click="toggleOutput"
/>
</PrimeButtonGroup>
<PrimeButton icon="pi pi-cog" size="large" :text="!inPreferences" :severity="inPreferences ? 'contrast' : 'secondary'" @click="onClickPreferences" />
</template>
</AppHeader>
<div v-auto-animate class="p-3 overflow-y-auto flex-1 bg-surface-900 overflow-hidden divide-y divide-surface-800">
<ClientRow v-for="client of clients" :key="client.id" :client="client" />
</div>
</div>
<slot />
</div>
<PrimeBadge class="fixed top-3 right-3" severity="success" />
</template>
<script setup lang="ts">
import { vAutoAnimate } from '@formkit/auto-animate'
const { clients, inputMuted, toggleInput, outputMuted, toggleOutput } = useApp()
const route = useRoute()
const inPreferences = computed(() => {
return route.name === 'Preferences'
})
function onClickPreferences() {
navigateTo(!inPreferences.value ? { name: 'Preferences' } : '/')
}
</script>

View File

@@ -0,0 +1,5 @@
export default defineNuxtRouteMiddleware((to, from) => {
console.group('Build Info')
console.log(`COMMIT_SHA: ${__COMMIT_SHA__}`)
console.groupEnd()
})

View File

@@ -0,0 +1,18 @@
export default defineNuxtRouteMiddleware((to, from) => {
const { username } = usePreferences()
if (!username.value && to.name !== 'Login') {
return navigateTo({ name: 'Login' })
}
if (!username.value)
return
const { init } = useMediasoup()
init()
if (to.path === 'Login') {
return navigateTo('/')
}
})

View File

@@ -0,0 +1,11 @@
<template>
<div class="flex items-center justify-center p-3">
<PrimeFieldset legend="Important information">
The chat is under development.
</PrimeFieldset>
</div>
</template>
<script setup lang="ts">
const { clients, inputMuted, toggleInput, outputMuted, toggleOutput } = useApp()
</script>

View File

@@ -0,0 +1,34 @@
<template>
<PrimeCard class="w-2/5">
<template #content>
<form class="flex flex-col gap-3" @submit.prevent="submit">
<PrimeFloatLabel variant="on">
<PrimeInputText id="username" v-model="localUsername" size="large" class="w-full" />
<label for="username">Username</label>
</PrimeFloatLabel>
<PrimeButton size="large" icon="pi pi-arrow-right" icon-pos="right" label="Let's go" :disabled="!localUsername" type="submit" />
</form>
</template>
</PrimeCard>
</template>
<script lang="ts" setup>
definePageMeta({
name: 'Login',
layout: 'auth',
})
const { username } = usePreferences()
const localUsername = ref<typeof username.value>()
async function submit() {
if (!localUsername.value)
return
username.value = localUsername.value
await navigateTo('/')
}
</script>

View File

@@ -0,0 +1,39 @@
<template>
<div>
<AppHeader title="Preferences" secondary />
<form class="flex flex-col gap-3 p-3" @submit.prevent="save">
<PrimeFloatLabel variant="on">
<PrimeInputText id="username" v-model="localUsername" size="large" class="w-full" />
<label for="username">Username</label>
</PrimeFloatLabel>
<PrimeButton label="Save" type="submit" :disabled="!localUsername || localUsername === username" />
</form>
</div>
</template>
<script setup lang="ts">
definePageMeta({
name: 'Preferences',
})
const signaling = useSignaling()
const { username } = usePreferences()
const toast = useToast()
const localUsername = ref(username.value)
async function save() {
if (!localUsername.value || localUsername.value === username.value)
return
username.value = localUsername.value
await signaling.socket.value?.emitWithAck('updateClient', {
username: username.value,
})
toast.add({ severity: 'success', summary: 'Saved', life: 1000, closable: false })
}
</script>

View File

@@ -5,6 +5,9 @@ export default antfu({
css: true, css: true,
}, },
overrides: { overrides: {
typescript: {
'no-console': 'off',
},
vue: { vue: {
'vue/block-order': ['error', { 'vue/block-order': ['error', {
order: ['template', 'script', 'style'], order: ['template', 'script', 'style'],

1
client/globals.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
declare const __COMMIT_SHA__: string

View File

@@ -1,16 +1,44 @@
import Aura from '@primeuix/themes/aura'
import tailwindcss from '@tailwindcss/vite'
export default defineNuxtConfig({ export default defineNuxtConfig({
compatibilityDate: '2025-09-29', compatibilityDate: '2025-09-29',
devtools: { enabled: true }, devtools: { enabled: true, vueDevTools: true },
ssr: false, ssr: false,
modules: [
'@nuxt/fonts',
'@primevue/nuxt-module',
],
primevue: {
options: {
theme: {
preset: Aura,
},
},
components: {
prefix: 'Prime',
},
},
css: [
'@/assets/styles/tailwind.css',
'@/assets/styles/primeicons.css',
'@/assets/styles/main.scss',
],
devServer: { devServer: {
// host: '0', // host: '0',
}, },
vite: { vite: {
plugins: [
tailwindcss(),
],
clearScreen: false, clearScreen: false,
envPrefix: ['VITE_', 'TAURI_'], envPrefix: ['VITE_', 'TAURI_'],
server: { server: {
strictPort: true, strictPort: true,
}, },
define: {
__COMMIT_SHA__: JSON.stringify(process.env.COMMIT_SHA || 'local'),
},
}, },
ignore: ['**/src-tauri/**'], ignore: ['**/src-tauri/**'],
}) })

View File

@@ -1,5 +1,5 @@
{ {
"name": "nuxt-app", "name": "chad-client",
"type": "module", "type": "module",
"private": true, "private": true,
"scripts": { "scripts": {
@@ -10,19 +10,30 @@
"postinstall": "nuxt prepare" "postinstall": "nuxt prepare"
}, },
"dependencies": { "dependencies": {
"@formkit/auto-animate": "^0.9.0",
"@nuxt/fonts": "^0.11.4",
"@primeuix/themes": "^1.2.5",
"@tailwindcss/vite": "^4.1.14",
"@vueuse/core": "^13.9.0", "@vueuse/core": "^13.9.0",
"mediasoup-client": "^3.16.7", "mediasoup-client": "^3.16.7",
"nuxt": "^4.1.2", "nuxt": "^4.1.2",
"postcss": "^8.5.6",
"primeicons": "^7.0.0",
"primevue": "^4.4.0",
"socket.io-client": "^4.8.1", "socket.io-client": "^4.8.1",
"typescript": "^5.9.3", "tailwindcss": "^4.1.14",
"tailwindcss-primeui": "^0.6.1",
"vue": "^3.5.22", "vue": "^3.5.22",
"vue-router": "^4.5.1" "vue-router": "^4.5.1"
}, },
"packageManager": "yarn@4.10.3", "packageManager": "yarn@4.10.3",
"devDependencies": { "devDependencies": {
"@antfu/eslint-config": "^5.4.1", "@antfu/eslint-config": "^5.4.1",
"@primevue/nuxt-module": "^4.4.0",
"@tauri-apps/cli": "^2.8.4", "@tauri-apps/cli": "^2.8.4",
"eslint": "^9.36.0", "eslint": "^9.36.0",
"eslint-plugin-format": "^1.0.2" "eslint-plugin-format": "^1.0.2",
"sass-embedded": "^1.93.2",
"typescript": "^5.9.3"
} }
} }

12
client/shared/types.ts Normal file
View File

@@ -0,0 +1,12 @@
export interface RemoteClient {
id: string
username: string
}
export interface ChadClient extends RemoteClient {
isMe: boolean
inputMuted?: boolean
outputMuted?: boolean
}
export type UpdatedClient = Omit<ChadClient, 'id' | 'isMe'>

View File

@@ -94,6 +94,7 @@ dependencies = [
"tauri", "tauri",
"tauri-build", "tauri-build",
"tauri-plugin-log", "tauri-plugin-log",
"tauri-plugin-single-instance",
] ]
[[package]] [[package]]
@@ -102,6 +103,137 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
[[package]]
name = "async-broadcast"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
dependencies = [
"event-listener",
"event-listener-strategy",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "async-channel"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
dependencies = [
"concurrent-queue",
"event-listener-strategy",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "async-executor"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "497c00e0fd83a72a79a39fcbd8e3e2f055d6f6c7e025f3b3d91f4f8e76527fb8"
dependencies = [
"async-task",
"concurrent-queue",
"fastrand",
"futures-lite",
"pin-project-lite",
"slab",
]
[[package]]
name = "async-io"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
dependencies = [
"autocfg",
"cfg-if",
"concurrent-queue",
"futures-io",
"futures-lite",
"parking",
"polling",
"rustix",
"slab",
"windows-sys 0.61.1",
]
[[package]]
name = "async-lock"
version = "3.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fd03604047cee9b6ce9de9f70c6cd540a0520c813cbd49bae61f33ab80ed1dc"
dependencies = [
"event-listener",
"event-listener-strategy",
"pin-project-lite",
]
[[package]]
name = "async-process"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
dependencies = [
"async-channel",
"async-io",
"async-lock",
"async-signal",
"async-task",
"blocking",
"cfg-if",
"event-listener",
"futures-lite",
"rustix",
]
[[package]]
name = "async-recursion"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.106",
]
[[package]]
name = "async-signal"
version = "0.2.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43c070bbf59cd3570b6b2dd54cd772527c7c3620fce8be898406dd3ed6adc64c"
dependencies = [
"async-io",
"async-lock",
"atomic-waker",
"cfg-if",
"futures-core",
"futures-io",
"rustix",
"signal-hook-registry",
"slab",
"windows-sys 0.61.1",
]
[[package]]
name = "async-task"
version = "4.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
[[package]]
name = "async-trait"
version = "0.1.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.106",
]
[[package]] [[package]]
name = "atk" name = "atk"
version = "0.18.2" version = "0.18.2"
@@ -218,6 +350,19 @@ dependencies = [
"objc2 0.6.2", "objc2 0.6.2",
] ]
[[package]]
name = "blocking"
version = "1.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21"
dependencies = [
"async-channel",
"async-task",
"futures-io",
"futures-lite",
"piper",
]
[[package]] [[package]]
name = "borsh" name = "borsh"
version = "1.5.7" version = "1.5.7"
@@ -460,6 +605,15 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "concurrent-queue"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
dependencies = [
"crossbeam-utils",
]
[[package]] [[package]]
name = "convert_case" name = "convert_case"
version = "0.4.0" version = "0.4.0"
@@ -791,6 +945,33 @@ version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"
[[package]]
name = "endi"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3d8a32ae18130a3c84dd492d4215c3d913c3b07c6b63c2eb3eb7ff1101ab7bf"
[[package]]
name = "enumflags2"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
dependencies = [
"enumflags2_derive",
"serde",
]
[[package]]
name = "enumflags2_derive"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.106",
]
[[package]] [[package]]
name = "env_filter" name = "env_filter"
version = "0.1.3" version = "0.1.3"
@@ -818,6 +999,43 @@ dependencies = [
"typeid", "typeid",
] ]
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.1",
]
[[package]]
name = "event-listener"
version = "5.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab"
dependencies = [
"concurrent-queue",
"parking",
"pin-project-lite",
]
[[package]]
name = "event-listener-strategy"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
dependencies = [
"event-listener",
"pin-project-lite",
]
[[package]]
name = "fastrand"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]] [[package]]
name = "fdeflate" name = "fdeflate"
version = "0.3.7" version = "0.3.7"
@@ -952,6 +1170,19 @@ version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6"
[[package]]
name = "futures-lite"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
dependencies = [
"fastrand",
"futures-core",
"futures-io",
"parking",
"pin-project-lite",
]
[[package]] [[package]]
name = "futures-macro" name = "futures-macro"
version = "0.3.31" version = "0.3.31"
@@ -1325,6 +1556,12 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
[[package]] [[package]]
name = "hex" name = "hex"
version = "0.4.3" version = "0.4.3"
@@ -1796,6 +2033,12 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "linux-raw-sys"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
[[package]] [[package]]
name = "litemap" name = "litemap"
version = "0.8.0" version = "0.8.0"
@@ -1957,6 +2200,19 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "nix"
version = "0.30.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6"
dependencies = [
"bitflags 2.9.4",
"cfg-if",
"cfg_aliases",
"libc",
"memoffset",
]
[[package]] [[package]]
name = "nodrop" name = "nodrop"
version = "0.1.14" version = "0.1.14"
@@ -2267,6 +2523,16 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]]
name = "ordered-stream"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
dependencies = [
"futures-core",
"pin-project-lite",
]
[[package]] [[package]]
name = "pango" name = "pango"
version = "0.18.3" version = "0.18.3"
@@ -2292,6 +2558,12 @@ dependencies = [
"system-deps", "system-deps",
] ]
[[package]]
name = "parking"
version = "2.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
[[package]] [[package]]
name = "parking_lot" name = "parking_lot"
version = "0.12.4" version = "0.12.4"
@@ -2467,6 +2739,17 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "piper"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96c8c490f422ef9a4efd2cb5b42b76c8613d7e7dfc1caf667b8a3350a5acc066"
dependencies = [
"atomic-waker",
"fastrand",
"futures-io",
]
[[package]] [[package]]
name = "pkg-config" name = "pkg-config"
version = "0.3.32" version = "0.3.32"
@@ -2499,6 +2782,20 @@ dependencies = [
"miniz_oxide", "miniz_oxide",
] ]
[[package]]
name = "polling"
version = "3.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
dependencies = [
"cfg-if",
"concurrent-queue",
"hermit-abi",
"pin-project-lite",
"rustix",
"windows-sys 0.61.1",
]
[[package]] [[package]]
name = "potential_utf" name = "potential_utf"
version = "0.1.3" version = "0.1.3"
@@ -2907,6 +3204,19 @@ dependencies = [
"semver", "semver",
] ]
[[package]]
name = "rustix"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e"
dependencies = [
"bitflags 2.9.4",
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.1",
]
[[package]] [[package]]
name = "rustversion" name = "rustversion"
version = "1.0.22" version = "1.0.22"
@@ -3207,6 +3517,15 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "signal-hook-registry"
version = "1.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2a4719bff48cee6b39d12c020eeb490953ad2443b7055bd0b21fca26bd8c28b"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "simd-adler32" name = "simd-adler32"
version = "0.3.7" version = "0.3.7"
@@ -3307,6 +3626,12 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]] [[package]]
name = "string_cache" name = "string_cache"
version = "0.8.9" version = "0.8.9"
@@ -3621,6 +3946,21 @@ dependencies = [
"time", "time",
] ]
[[package]]
name = "tauri-plugin-single-instance"
version = "2.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb9cac815bf11c4a80fb498666bcdad66d65b89e3ae24669e47806febb76389c"
dependencies = [
"serde",
"serde_json",
"tauri",
"thiserror 2.0.17",
"tracing",
"windows-sys 0.60.2",
"zbus",
]
[[package]] [[package]]
name = "tauri-runtime" name = "tauri-runtime"
version = "2.8.0" version = "2.8.0"
@@ -3721,6 +4061,19 @@ dependencies = [
"toml 0.9.7", "toml 0.9.7",
] ]
[[package]]
name = "tempfile"
version = "3.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16"
dependencies = [
"fastrand",
"getrandom 0.3.3",
"once_cell",
"rustix",
"windows-sys 0.61.1",
]
[[package]] [[package]]
name = "tendril" name = "tendril"
version = "0.4.3" version = "0.4.3"
@@ -4008,9 +4361,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0"
dependencies = [ dependencies = [
"pin-project-lite", "pin-project-lite",
"tracing-attributes",
"tracing-core", "tracing-core",
] ]
[[package]]
name = "tracing-attributes"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.106",
]
[[package]] [[package]]
name = "tracing-core" name = "tracing-core"
version = "0.1.34" version = "0.1.34"
@@ -4060,6 +4425,17 @@ version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f"
[[package]]
name = "uds_windows"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89daebc3e6fd160ac4aa9fc8b3bf71e1f74fbf92367ae71fb83a037e8bf164b9"
dependencies = [
"memoffset",
"tempfile",
"winapi",
]
[[package]] [[package]]
name = "unic-char-property" name = "unic-char-property"
version = "0.9.0" version = "0.9.0"
@@ -4993,6 +5369,66 @@ dependencies = [
"synstructure", "synstructure",
] ]
[[package]]
name = "zbus"
version = "5.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d07e46d035fb8e375b2ce63ba4e4ff90a7f73cf2ffb0138b29e1158d2eaadf7"
dependencies = [
"async-broadcast",
"async-executor",
"async-io",
"async-lock",
"async-process",
"async-recursion",
"async-task",
"async-trait",
"blocking",
"enumflags2",
"event-listener",
"futures-core",
"futures-lite",
"hex",
"nix",
"ordered-stream",
"serde",
"serde_repr",
"tracing",
"uds_windows",
"windows-sys 0.60.2",
"winnow 0.7.13",
"zbus_macros",
"zbus_names",
"zvariant",
]
[[package]]
name = "zbus_macros"
version = "5.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57e797a9c847ed3ccc5b6254e8bcce056494b375b511b3d6edcec0aeb4defaca"
dependencies = [
"proc-macro-crate 3.4.0",
"proc-macro2",
"quote",
"syn 2.0.106",
"zbus_names",
"zvariant",
"zvariant_utils",
]
[[package]]
name = "zbus_names"
version = "4.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7be68e64bf6ce8db94f63e72f0c7eb9a60d733f7e0499e628dfab0f84d6bcb97"
dependencies = [
"serde",
"static_assertions",
"winnow 0.7.13",
"zvariant",
]
[[package]] [[package]]
name = "zerocopy" name = "zerocopy"
version = "0.8.27" version = "0.8.27"
@@ -5066,3 +5502,43 @@ dependencies = [
"quote", "quote",
"syn 2.0.106", "syn 2.0.106",
] ]
[[package]]
name = "zvariant"
version = "5.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "999dd3be73c52b1fccd109a4a81e4fcd20fab1d3599c8121b38d04e1419498db"
dependencies = [
"endi",
"enumflags2",
"serde",
"winnow 0.7.13",
"zvariant_derive",
"zvariant_utils",
]
[[package]]
name = "zvariant_derive"
version = "5.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6643fd0b26a46d226bd90d3f07c1b5321fe9bb7f04673cb37ac6d6883885b68e"
dependencies = [
"proc-macro-crate 3.4.0",
"proc-macro2",
"quote",
"syn 2.0.106",
"zvariant_utils",
]
[[package]]
name = "zvariant_utils"
version = "3.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6949d142f89f6916deca2232cf26a8afacf2b9fdc35ce766105e104478be599"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 2.0.106",
"winnow 0.7.13",
]

View File

@@ -1,8 +1,8 @@
[package] [package]
name = "app" name = "app"
version = "0.1.0" version = "0.1.0"
description = "A Tauri App" description = "WW додепчик"
authors = ["you"] authors = ["KPTL"]
license = "" license = ""
repository = "" repository = ""
edition = "2021" edition = "2021"
@@ -23,3 +23,6 @@ serde = { version = "1.0", features = ["derive"] }
log = "0.4" log = "0.4"
tauri = { version = "2.8.5", features = [] } tauri = { version = "2.8.5", features = [] }
tauri-plugin-log = "2" tauri-plugin-log = "2"
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-single-instance = "2"

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSCameraUsageDescription</key>
<string>Request camera access for WebRTC</string>
<key>NSMicrophoneUsageDescription</key>
<string>Request microphone access for WebRTC</string>
</dict>
</plist>

View File

@@ -1,6 +1,11 @@
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() { pub fn run() {
tauri::Builder::default() tauri::Builder::default()
// .plugin(tauri_plugin_single_instance::init(|app, args, cwd| {
// app.get_webview_window("main")
// .expect("no main window")
// .set_focus();
// }))
.setup(|app| { .setup(|app| {
if cfg!(debug_assertions) { if cfg!(debug_assertions) {
app.handle().plugin( app.handle().plugin(

View File

@@ -2,30 +2,36 @@
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "chad", "productName": "chad",
"version": "0.1.0", "version": "0.1.0",
"identifier": "com.tauri.dev", "identifier": "xyz.koptilnya.chad",
"build": { "build": {
"frontendDist": "../dist", "frontendDist": "../.output/public",
"devUrl": "http://localhost:3000", "devUrl": "http://localhost:3000",
"beforeDevCommand": "yarn dev", "beforeDevCommand": "yarn dev",
"beforeBuildCommand": "yarn build" "beforeBuildCommand": "yarn generate"
}, },
"app": { "app": {
"windows": [ "windows": [
{ {
"maximizable": false,
"label": "main",
"title": "Chad", "title": "Chad",
"width": 800, "width": 800,
"height": 600, "height": 600,
"resizable": false, "resizable": false,
"fullscreen": false "fullscreen": false,
"center": true,
"theme": "Dark",
"additionalBrowserArgs": "--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection --autoplay-policy=no-user-gesture-required"
} }
], ],
"security": { "security": {
"csp": null "csp": null,
"capabilities": []
} }
}, },
"bundle": { "bundle": {
"active": true, "active": true,
"targets": "all", "targets": ["nsis"],
"icon": [ "icon": [
"icons/32x32.png", "icons/32x32.png",
"icons/128x128.png", "icons/128x128.png",

File diff suppressed because it is too large Load Diff

3
server/.gitignore vendored
View File

@@ -15,3 +15,6 @@ node_modules
#!.yarn/cache #!.yarn/cache
.pnp.* .pnp.*
.env*
*.db

1
server/.yarnrc.yml Normal file
View File

@@ -0,0 +1 @@
nodeLinker: node-modules

View File

@@ -1,11 +1,17 @@
FROM node:22-alpine FROM node:22
WORKDIR /app WORKDIR /app
RUN corepack enable RUN corepack enable
COPY package.json yarn.lock ./ COPY package.json yarn.lock .yarnrc.yml ./
RUN apk add --no-cache python3 RUN apt update && apt install --yes python3 python3-pip build-essential
RUN yarn install RUN yarn set version latest
RUN yarn install --frozen-lockfile
COPY . . COPY . .
ENV PORT=80 ENV PORT=80
ENV CORS_ORIGIN=chad.koptilnya.xyz
ENV ANNOUNCED_ADDRESS=91.144.171.182
ENV DATABASE_URL=file:../data/database.db
EXPOSE 80 EXPOSE 80
CMD ["node", "index.mjs"]
CMD yarn db:deploy && yarn start

7
server/auth/lucia.ts Normal file
View File

@@ -0,0 +1,7 @@
import { PrismaAdapter } from '@lucia-auth/adapter-prisma'
import { Lucia } from 'lucia'
import prisma from '../prisma/client'
export const auth = new Lucia<object, { username: string, displayName: string }>(new PrismaAdapter(prisma.session, prisma.user))
export type Auth = typeof auth

10
server/eslint.config.mjs Normal file
View File

@@ -0,0 +1,10 @@
import antfu from '@antfu/eslint-config'
export default antfu({
typescript: {
overrides: {
'no-console': 'off',
'n/prefer-global/process': 'off',
},
},
})

View File

@@ -1,145 +0,0 @@
import express from "express";
import http from "http";
import cors from "cors";
import { Server } from "socket.io";
import * as mediasoup from "mediasoup";
const app = express();
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: '*'
}
});
let worker;
let router;
const transports = new Map(); // socketId -> [transports]
const producers = new Map(); // socketId -> [producers]
const consumers = new Map(); // socketId -> [consumers]
async function createWorker() {
worker = await mediasoup.createWorker();
worker.on("died", () => {
console.error("mediasoup worker died, exiting...");
process.exit(1);
});
router = await worker.createRouter({
mediaCodecs: [
{
kind: "audio",
mimeType: "audio/opus",
clockRate: 48000,
channels: 2,
}
],
});
console.log("Mediasoup worker & router created");
}
createWorker();
io.on("connection", (socket) => {
console.log("Client connected:", socket.id);
socket.on("getRtpCapabilities", (cb) => {
cb(router.rtpCapabilities);
});
socket.on("createTransport", async (cb) => {
try {
const transport = await router.createWebRtcTransport({
listenIps: [{ ip: "0.0.0.0", announcedIp: "127.0.0.1" }],
enableUdp: true,
enableTcp: true,
preferUdp: true,
});
transports.set(socket.id, [...(transports.get(socket.id) || []), transport]);
cb({
id: transport.id,
iceParameters: transport.iceParameters,
iceCandidates: transport.iceCandidates,
dtlsParameters: transport.dtlsParameters,
});
transport.observer.on("close", () => {
console.log("transport closed", transport.id);
});
} catch (err) {
console.error("createTransport error:", err);
cb({ error: err.message });
}
});
socket.on("connectTransport", async ({ transportId, dtlsParameters }, cb) => {
const transport = transports.get(socket.id)?.find((t) => t.id === transportId);
if (!transport) return cb({ error: "transport not found" });
await transport.connect({ dtlsParameters });
cb({ connected: true });
});
socket.on("produce", async ({ transportId, kind, rtpParameters }, cb) => {
const transport = transports.get(socket.id)?.find((t) => t.id === transportId);
if (!transport) return cb({ error: "transport not found" });
const producer = await transport.produce({ kind, rtpParameters });
producers.set(socket.id, [...(producers.get(socket.id) || []), producer]);
cb({ id: producer.id });
socket.broadcast.emit("newProducer", { producerId: producer.id });
producer.observer.on("close", () => {
console.log("producer closed", producer.id);
});
});
socket.on("consume", async ({ producerId, transportId, rtpCapabilities }, cb) => {
try {
if (!router.canConsume({ producerId, rtpCapabilities })) {
return cb({ error: "cannot consume" });
}
const transport = transports.get(socket.id)?.find((t) => t.id === transportId);
if (!transport) return cb({ error: "transport not found" });
const consumer = await transport.consume({
producerId,
rtpCapabilities,
paused: false,
});
consumers.set(socket.id, [...(consumers.get(socket.id) || []), consumer]);
cb({
id: consumer.id,
producerId,
kind: consumer.kind,
rtpParameters: consumer.rtpParameters,
});
} catch (err) {
console.error("consume error:", err);
cb({ error: err.message });
}
});
socket.on("disconnect", () => {
console.log("Client disconnected:", socket.id);
transports.get(socket.id)?.forEach((t) => t.close());
producers.get(socket.id)?.forEach((p) => p.close());
consumers.get(socket.id)?.forEach((c) => c.close());
transports.delete(socket.id);
producers.delete(socket.id);
consumers.delete(socket.id);
});
});
server.listen(process.env.PORT || 3000);

47
server/index.ts Normal file
View File

@@ -0,0 +1,47 @@
import { createServer as createHttpServer } from 'node:http'
import { consola } from 'consola'
import cors from 'cors'
import express from 'express'
import * as mediasoup from 'mediasoup'
import { Server as SocketServer } from 'socket.io'
import { webrtcSocket } from './sockets'
(async () => {
const app = express()
app.use(cors())
const server = createHttpServer(app)
const worker = await mediasoup.createWorker()
worker.on('died', () => {
consola.error('[Mediasoup]', 'Worker died, exiting...')
process.exit(1)
})
const router = await worker.createRouter({
mediaCodecs: [
{
kind: 'audio',
mimeType: 'audio/opus',
clockRate: 48000,
channels: 2,
parameters: { useinbandfec: 1, stereo: 1 },
},
],
})
const io = new SocketServer(server, {
path: '/chad/ws',
cors: {
origin: process.env.CORS_ORIGIN || '*',
},
})
webrtcSocket(io, router)
server.listen(process.env.PORT || 4000, () => {
consola.success('[Server]', 'Server started!')
})
})()

View File

@@ -1,13 +1,38 @@
{ {
"name": "server", "name": "server",
"scripts": { "scripts": {
"start": "node index.mjs" "start": "ts-node --transpile-only server.ts",
"db:deploy": "npx prisma migrate deploy && npx prisma generate"
}, },
"packageManager": "yarn@4.10.3", "packageManager": "yarn@4.10.3",
"dependencies": { "dependencies": {
"@lucia-auth/adapter-prisma": "^4.0.1",
"@prisma/client": "^6.17.0",
"@trpc/server": "^11.6.0",
"bcrypt": "^6.0.0",
"consola": "^3.4.2",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^17.2.3",
"express": "^5.1.0", "express": "^5.1.0",
"lucia": "^3.2.2",
"mediasoup": "^3.19.3", "mediasoup": "^3.19.3",
"socket.io": "^4.8.1" "prisma": "^6.17.0",
"socket.io": "^4.8.1",
"ws": "^8.18.3",
"zod": "^4.1.12"
},
"devDependencies": {
"@antfu/eslint-config": "^5.4.1",
"@types/bcrypt": "^6",
"@types/cookie-parser": "^1",
"@types/express": "^5.0.3",
"@types/ws": "^8",
"eslint": "^9.36.0",
"ts-node": "^10.9.2",
"typescript": "^5.9.3"
},
"engines": {
"node": ">=22.18.0"
} }
} }

7
server/prisma/client.ts Normal file
View File

@@ -0,0 +1,7 @@
import { PrismaClient } from '@prisma/client'
const instance = new PrismaClient({
log: ['query', 'error', 'warn'],
})
export default instance

View File

@@ -0,0 +1,12 @@
-- CreateTable
CREATE TABLE "User" (
"id" TEXT NOT NULL PRIMARY KEY,
"username" TEXT NOT NULL,
"password" TEXT NOT NULL,
"displayName" TEXT NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL
);
-- CreateIndex
CREATE UNIQUE INDEX "User_username_key" ON "User"("username");

View File

@@ -0,0 +1,7 @@
-- CreateTable
CREATE TABLE "Session" (
"id" TEXT NOT NULL PRIMARY KEY,
"userId" TEXT NOT NULL,
"expiresAt" DATETIME NOT NULL,
CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);

View File

@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "sqlite"

View File

@@ -0,0 +1,29 @@
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id String @id @default(cuid())
username String @unique
password String
displayName String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Session Session[]
}
model Session {
id String @id
userId String
expiresAt DateTime
user User @relation(references: [id], fields: [userId], onDelete: Cascade)
@@index([userId])
}

61
server/server.ts Normal file
View File

@@ -0,0 +1,61 @@
import { createServer as createHttpServer } from 'node:http'
import { createExpressMiddleware } from '@trpc/server/adapters/express'
import { consola } from 'consola'
import cookieParser from 'cookie-parser'
import cors from 'cors'
import express from 'express'
import * as mediasoup from 'mediasoup'
import { Server as SocketServer } from 'socket.io'
import { createContext } from './trpc/context'
import { appRouter } from './trpc/routers'
import webrtcSocket from './webrtc/socket'
(async () => {
const app = express()
app.use(cors())
app.use(cookieParser())
app.use(express.json())
app.use(
'/chad/trpc',
createExpressMiddleware({
router: appRouter,
createContext,
}),
)
const server = createHttpServer(app)
const worker = await mediasoup.createWorker()
worker.on('died', () => {
consola.error('[Mediasoup]', 'Worker died, exiting...')
process.exit(1)
})
const router = await worker.createRouter({
mediaCodecs: [
{
kind: 'audio',
mimeType: 'audio/opus',
clockRate: 48000,
channels: 2,
parameters: { useinbandfec: 1, stereo: 1 },
},
],
})
const io = new SocketServer(server, {
path: '/chad/ws',
cors: {
origin: process.env.CORS_ORIGIN || '*',
},
})
webrtcSocket(io, router)
server.listen(process.env.PORT || 4000, () => {
console.log('✅ Server running')
})
})()

23
server/trpc/context.ts Normal file
View File

@@ -0,0 +1,23 @@
import type { CreateExpressContextOptions } from '@trpc/server/adapters/express'
import { auth } from '../auth/lucia'
export async function createContext({ res, req }: CreateExpressContextOptions) {
const sessionId = auth.readSessionCookie(req.headers.cookie ?? '')
if (!sessionId)
return { res, req }
const { session, user } = await auth.validateSession(sessionId)
if (session && session.fresh) {
res.appendHeader('Set-Cookie', auth.createSessionCookie(session.id).serialize())
}
if (!session) {
res.appendHeader('Set-Cookie', auth.createBlankSessionCookie().serialize())
}
return { res, req, session, user }
}
export type Context = Awaited<ReturnType<typeof createContext>>

15
server/trpc/router.ts Normal file
View File

@@ -0,0 +1,15 @@
import type { Context } from './context'
import { initTRPC } from '@trpc/server'
const t = initTRPC.context<Context>().create()
export const router = t.router
export const publicProcedure = t.procedure
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
if (!ctx.session?.fresh)
throw new Error('UNAUTHORIZED')
return next({ ctx: { ...ctx } })
})

View File

@@ -0,0 +1,74 @@
import { TRPCError } from '@trpc/server'
import bcrypt from 'bcrypt'
import { z } from 'zod'
import { auth } from '../../auth/lucia'
import client from '../../prisma/client'
import { protectedProcedure, publicProcedure, router } from '../router'
export const authRouter = router({
register: publicProcedure
.input(z.object({ username: z.string().min(1), password: z.string().min(6) }))
.mutation(async ({ input, ctx }) => {
const hashed = await bcrypt.hash(input.password, 10)
const user = await client.user.create({
data: {
username: input.username,
password: hashed,
displayName: input.username,
},
})
const session = await auth.createSession(user.id, {})
const cookie = auth.createSessionCookie(session.id)
ctx.res.setHeader('Set-Cookie', cookie.serialize())
return { user }
}),
login: publicProcedure
.input(z.object({ username: z.string().min(1), password: z.string() }))
.mutation(async ({ input, ctx }) => {
const user = await client.user.findFirst({
where: {
username: input.username,
},
})
if (!user) {
throw new TRPCError({
code: 'NOT_FOUND',
message: 'Incorrect username or password',
})
}
const validPassword = await bcrypt.compare(input.password, user.password)
if (!validPassword) {
throw new TRPCError({
code: 'NOT_FOUND',
message: 'Incorrect username or password',
})
}
const session = await auth.createSession(user.id, {})
const cookie = auth.createSessionCookie(session.id)
ctx.res.setHeader('Set-Cookie', cookie.serialize())
return { user }
}),
me: protectedProcedure.query(({ ctx }) => {
return ctx.user
}),
logout: publicProcedure.mutation(async ({ ctx }) => {
if (ctx.session)
await auth.invalidateSession(ctx.session.id)
ctx.res.setHeader('Set-Cookie', auth.createBlankSessionCookie().serialize())
return true
}),
})

View File

@@ -0,0 +1,10 @@
import { router } from '../router'
import { authRouter } from './auth'
// import { webrtcRouter } from './webrtc'
export const appRouter = router({
auth: authRouter,
// webrtc: webrtcRouter,
})
export type AppRouter = typeof appRouter

10
server/tsconfig.json Normal file
View File

@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}

565
server/webrtc/socket.ts Normal file
View File

@@ -0,0 +1,565 @@
import type { types } from 'mediasoup'
import type { Namespace, RemoteSocket, Socket, Server as SocketServer } from 'socket.io'
import { consola } from 'consola'
interface ChadClient {
id: string
username: string
inputMuted: boolean
outputMuted: boolean
}
interface ProducerShort {
producerId: types.Producer['id']
kind: types.MediaKind
}
interface ErrorCallbackResult {
error: string
}
interface SuccessCallbackResult {
ok: true
}
type EventCallback<T = SuccessCallbackResult> = (result: T | ErrorCallbackResult) => void
interface ClientToServerEvents {
join: (
options: {
username: string
rtpCapabilities: types.RtpCapabilities
},
cb: EventCallback<{ id: string, username: string }[]>
) => void
getRtpCapabilities: (
cb: EventCallback<types.RtpCapabilities>
) => void
createTransport: (
options: {
producing: boolean
consuming: boolean
},
cb: EventCallback<Pick<types.WebRtcTransport, 'id' | 'iceParameters' | 'iceCandidates' | 'dtlsParameters'>>
) => void
connectTransport: (
options: {
transportId: types.WebRtcTransport['id']
dtlsParameters: types.WebRtcTransport['dtlsParameters']
},
cb: EventCallback
) => void
produce: (
options: {
transportId: types.WebRtcTransport['id']
kind: types.MediaKind
rtpParameters: types.RtpParameters
},
cb: EventCallback<{ id: types.Producer['id'] }>
) => void
closeProducer: (
options: {
producerId: types.Producer['id']
},
cb: EventCallback
) => void
pauseProducer: (
options: {
producerId: types.Producer['id']
},
cb: EventCallback
) => void
resumeProducer: (
options: {
producerId: types.Producer['id']
},
cb: EventCallback
) => void
pauseConsumer: (
options: {
consumerId: types.Consumer['id']
},
cb: EventCallback
) => void
resumeConsumer: (
options: {
consumerId: types.Consumer['id']
},
cb: EventCallback
) => void
updateClient: (
options: Partial<Omit<ChadClient, 'id'>>,
cb: EventCallback
) => void
}
interface ServerToClientEvents {
newPeer: (arg: ChadClient) => void
producers: (arg: ProducerShort[]) => void
newConsumer: (
arg: {
peerId: string
producerId: types.Producer['id']
id: types.Consumer['id']
kind: types.MediaKind
rtpParameters: types.RtpParameters
type: types.ConsumerType
appData: types.Producer['appData']
producerPaused: types.Consumer['producerPaused']
},
cb: EventCallback
) => void
peerClosed: (arg: string) => void
consumerClosed: (arg: { consumerId: string }) => void
consumerPaused: (arg: { consumerId: string }) => void
consumerResumed: (arg: { consumerId: string }) => void
consumerScore: (arg: { consumerId: string, score: types.ConsumerScore }) => void
clientChanged: (clientId: ChadClient['id'], client: ChadClient) => void
}
interface InterServerEvent {}
interface SocketData {
joined: boolean
username: string
inputMuted: boolean
outputMuted: boolean
rtpCapabilities: types.RtpCapabilities
transports: Map<types.WebRtcTransport['id'], types.WebRtcTransport>
producers: Map<types.Producer['id'], types.Producer>
consumers: Map<types.Consumer['id'], types.Consumer>
}
export default function (io: SocketServer, router: types.Router) {
const namespace: Namespace<ClientToServerEvents, ServerToClientEvents, InterServerEvent, SocketData> = io.of('/webrtc')
namespace.on('connection', (socket) => {
consola.info('[WebRtc]', 'Client connected', socket.id)
socket.data.joined = false
socket.data.username = socket.id
socket.data.inputMuted = false
socket.data.outputMuted = false
socket.data.transports = new Map()
socket.data.producers = new Map()
socket.data.consumers = new Map()
socket.on('join', async ({ username, rtpCapabilities }, cb) => {
if (socket.data.joined) {
consola.error('[WebRtc]', 'Already joined')
cb({ error: 'Already joined' })
}
socket.data.joined = true
socket.data.username = username
socket.data.rtpCapabilities = rtpCapabilities
const joinedSockets = await getJoinedSockets()
cb(joinedSockets.map((s) => {
return {
id: s.id,
username: s.data.username,
}
}))
for (const joinedSocket of joinedSockets.filter(joinedSocket => joinedSocket.id !== socket.id)) {
for (const producer of joinedSocket.data.producers.values()) {
createConsumer(
socket,
joinedSocket,
producer,
)
}
}
socket.broadcast.emit('newPeer', socketToClient(socket))
})
socket.on('getRtpCapabilities', (cb) => {
cb(router.rtpCapabilities)
})
socket.on('createTransport', async ({ producing, consuming }, cb) => {
try {
const transport = await router.createWebRtcTransport({
listenInfos: [
{
protocol: 'udp',
ip: '0.0.0.0',
announcedAddress: process.env.ANNOUNCED_ADDRESS || '127.0.0.1',
portRange: {
min: 40000,
max: 40100,
},
},
],
enableUdp: true,
preferUdp: true,
appData: {
producing,
consuming,
},
})
socket.data.transports.set(transport.id, transport)
cb({
id: transport.id,
iceParameters: transport.iceParameters,
iceCandidates: transport.iceCandidates,
dtlsParameters: transport.dtlsParameters,
})
transport.on('icestatechange', (iceState) => {
if (iceState === 'disconnected' || iceState === 'closed') {
consola.info('[WebRtc]', '[WebRtcTransport]', `"icestatechange" event [iceState:${iceState}], closing peer`, transport.id)
socket.disconnect()
}
})
transport.on('dtlsstatechange', (dtlsState) => {
if (dtlsState === 'failed' || dtlsState === 'closed') {
consola.warn('WebRtcTransport "dtlsstatechange" event [dtlsState:%s], closing peer', dtlsState)
socket.disconnect()
}
})
}
catch (error) {
if (error instanceof Error) {
consola.error('[WebRtc]', '[createTransport]', error.message)
cb({ error: error.message })
}
}
})
socket.on('connectTransport', async ({ transportId, dtlsParameters }, cb) => {
const transport = socket.data.transports.get(transportId)
if (!transport) {
consola.error('[WebRtc]', '[connectTransport]', `Transport with id ${transportId} not found`)
cb({ error: 'Transport not found' })
return
}
try {
await transport.connect({ dtlsParameters })
cb({ ok: true })
}
catch (error) {
if (error instanceof Error) {
consola.error('[WebRtc]', '[connectTransport]', error.message)
cb({ error: error.message })
}
}
})
socket.on('produce', async ({ transportId, kind, rtpParameters }, cb) => {
if (!socket.data.joined) {
consola.error('Peer not joined yet')
cb({ error: 'Peer not joined yet' })
return
}
const transport = socket.data.transports.get(transportId)
if (!transport) {
consola.error('[WebRtc]', '[produce]', `Transport with id ${transportId} not found`)
cb({ error: 'Transport not found' })
return
}
try {
const producer = await transport.produce({ kind, rtpParameters, appData: { socketId: socket.id } })
socket.data.producers.set(producer.id, producer)
cb({ id: producer.id })
const otherSockets = await getJoinedSockets(socket.id)
for (const otherSocket of otherSockets) {
createConsumer(
otherSocket,
socket,
producer,
)
}
// TODO: Add into the AudioLevelObserver and ActiveSpeakerObserver.
// https://github.com/versatica/mediasoup-demo/blob/v3/server/lib/Room.js#L1276
}
catch (error) {
if (error instanceof Error) {
consola.error('[WebRtc]', '[produce]', error.message)
cb({ error: error.message })
}
}
})
socket.on('closeProducer', async ({ producerId }, cb) => {
if (!socket.data.joined) {
consola.error('Peer not joined yet')
cb({ error: 'Peer not joined yet' })
return
}
const producer = socket.data.producers.get(producerId)
if (!producer) {
consola.error(`producer with id "${producerId}" not found`)
cb({ error: `producer with id "${producerId}" not found` })
return
}
producer.close()
socket.data.producers.delete(producerId)
cb({ ok: true })
})
socket.on('pauseProducer', async ({ producerId }, cb) => {
if (!socket.data.joined) {
consola.error('Peer not joined yet')
cb({ error: 'Peer not joined yet' })
return
}
const producer = socket.data.producers.get(producerId)
if (!producer) {
consola.error(`producer with id "${producerId}" not found`)
cb({ error: `producer with id "${producerId}" not found` })
return
}
await producer.pause()
cb({ ok: true })
})
socket.on('resumeProducer', async ({ producerId }, cb) => {
if (!socket.data.joined) {
consola.error('Peer not joined yet')
cb({ error: 'Peer not joined yet' })
return
}
const producer = socket.data.producers.get(producerId)
if (!producer) {
consola.error(`producer with id "${producerId}" not found`)
cb({ error: `producer with id "${producerId}" not found` })
return
}
await producer.resume()
cb({ ok: true })
})
socket.on('pauseConsumer', async ({ consumerId }, cb) => {
if (!socket.data.joined) {
consola.error('Peer not joined yet')
cb({ error: 'Peer not joined yet' })
return
}
const consumer = socket.data.consumers.get(consumerId)
if (!consumer) {
consola.error(`consumer with id "${consumerId}" not found`)
cb({ error: `consumer with id "${consumerId}" not found` })
return
}
await consumer.pause()
cb({ ok: true })
})
socket.on('resumeConsumer', async ({ consumerId }, cb) => {
if (!socket.data.joined) {
consola.error('Peer not joined yet')
cb({ error: 'Peer not joined yet' })
return
}
const consumer = socket.data.consumers.get(consumerId)
if (!consumer) {
consola.error(`consumer with id "${consumerId}" not found`)
cb({ error: `consumer with id "${consumerId}" not found` })
return
}
await consumer.resume()
cb({ ok: true })
})
socket.on('updateClient', (updatedClient, cb) => {
if (updatedClient.username) {
socket.data.username = updatedClient.username
}
if (updatedClient.inputMuted) {
socket.data.inputMuted = updatedClient.inputMuted
}
if (updatedClient.outputMuted) {
socket.data.outputMuted = updatedClient.outputMuted
}
cb({ ok: true })
namespace.emit('clientChanged', socket.id, socketToClient(socket))
})
socket.on('disconnect', () => {
consola.info('Client disconnected:', socket.id)
if (socket.data.joined) {
socket.broadcast.emit('peerClosed', socket.id)
}
for (const transport of socket.data.transports.values()) {
transport.close()
}
})
})
async function getJoinedSockets(excludeId?: string) {
const sockets = await namespace.fetchSockets()
return sockets.filter(socket => socket.data.joined && (excludeId ? excludeId !== socket.id : true))
}
async function createConsumer(
consumerSocket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvent, SocketData>,
producerSocket: RemoteSocket<ServerToClientEvents, SocketData>,
producer: types.Producer,
) {
if (
!consumerSocket.data.rtpCapabilities
|| !router.canConsume(
{
producerId: producer.id,
rtpCapabilities: consumerSocket.data.rtpCapabilities,
},
)
) {
return
}
const transport = Array.from(consumerSocket.data.transports.values())
.find(t => t.appData.consuming)
if (!transport) {
consola.error('createConsumer() | Transport for consuming not found')
return
}
let consumer: types.Consumer
try {
consumer = await transport.consume(
{
producerId: producer.id,
rtpCapabilities: consumerSocket.data.rtpCapabilities,
// Enable NACK for OPUS.
enableRtx: true,
paused: true,
ignoreDtx: true,
},
)
}
catch (error) {
consola.error('_createConsumer() | transport.consume():%o', error)
return
}
consumerSocket.data.consumers.set(consumer.id, consumer)
consumer.on('transportclose', () => {
consumerSocket.data.consumers.delete(consumer.id)
})
consumer.on('producerclose', () => {
consumerSocket.data.consumers.delete(consumer.id)
consumerSocket.emit('consumerClosed', { consumerId: consumer.id })
})
consumer.on('producerpause', () => {
consumerSocket.emit('consumerPaused', { consumerId: consumer.id })
})
consumer.on('producerresume', () => {
consumerSocket.emit('consumerResumed', { consumerId: consumer.id })
})
consumer.on('score', (score) => {
consumerSocket.emit('consumerScore', { consumerId: consumer.id, score })
})
try {
await consumerSocket.emitWithAck(
'newConsumer',
{
peerId: producerSocket.id,
producerId: producer.id,
id: consumer.id,
kind: consumer.kind,
rtpParameters: consumer.rtpParameters,
type: consumer.type,
appData: producer.appData,
producerPaused: consumer.producerPaused,
},
)
await consumer.resume()
consumerSocket.emit(
'consumerScore',
{
consumerId: consumer.id,
score: consumer.score,
},
)
}
catch (error) {
consola.error('_createConsumer() | failed:%o', error)
}
}
function socketToClient(socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvent, SocketData>): ChadClient {
return {
id: socket.id,
username: socket.data.username,
inputMuted: socket.data.inputMuted,
outputMuted: socket.data.outputMuted,
}
}
}

File diff suppressed because it is too large Load Diff

4
yarn.lock Normal file
View File

@@ -0,0 +1,4 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1