Compare commits
150 Commits
20e1cb28b7
...
v0.2.7
| Author | SHA1 | Date | |
|---|---|---|---|
| a4bd6705b6 | |||
| 723048c72a | |||
| 06ea0cd488 | |||
| 007d3ddda7 | |||
| 33cdaebada | |||
| 9650ea63fc | |||
| db59b85bd2 | |||
| 3f6f3b739e | |||
| b33a896117 | |||
| 01ae1b5011 | |||
| 0ac69610f2 | |||
| c4489b58c9 | |||
| c19bef73e0 | |||
| c573d2277a | |||
| 3006a82a0f | |||
| a68aa78ae1 | |||
| ba9f51bd5e | |||
| 89a3eac2b9 | |||
| 01de23a036 | |||
| aef93ef821 | |||
| 72f46df4d1 | |||
| 50c56e87ff | |||
| a7d65f0e3c | |||
| 649b49a732 | |||
| b887b69997 | |||
| 687a2958c0 | |||
| a7fe94abec | |||
| adb539350f | |||
| d870b7c1f1 | |||
| edd5a69cd4 | |||
| 6343f1de4d | |||
| 3f581ea8e9 | |||
| 10bfcf0727 | |||
| 6b5383ba24 | |||
| 6b5d669f64 | |||
| 40d66d356b | |||
| c665c19cf3 | |||
| b05a7324d6 | |||
| e8cbf6e146 | |||
| 472fa8d907 | |||
| ddc43e4b42 | |||
| 8d02eb380d | |||
| 4c70dce568 | |||
| 76f0ec74b5 | |||
|
|
e3d0106d8f | ||
|
|
e2068dd89a | ||
|
|
a2f845f228 | ||
|
|
1a497d402d | ||
|
|
924bbd4285 | ||
|
|
58d37ee02b | ||
|
|
ba12d413dc | ||
|
|
f525d1afe5 | ||
|
|
75fe5b0b8c | ||
|
|
39e877bbe9 | ||
|
|
fe205531e0 | ||
|
|
1ef0df7afb | ||
|
|
a0bd6f92e9 | ||
|
|
511cb76888 | ||
|
|
a433e1982b | ||
|
|
ec67be8aa6 | ||
|
|
31460598ba | ||
|
|
4c368458a9 | ||
|
|
aa31e7ad0c | ||
|
|
7b4be60099 | ||
|
|
d5915a9d40 | ||
|
|
7d4fdfb2e6 | ||
|
|
ad71b15f81 | ||
|
|
a49fe5fc53 | ||
|
|
8f2b9861c2 | ||
|
|
adcc5b65a6 | ||
|
|
b8a21a1451 | ||
|
|
c0969c4494 | ||
|
|
bb48e52a99 | ||
|
|
6ada2c3fbd | ||
|
|
e2064dba6c | ||
|
|
fc43c8df96 | ||
|
|
6b6a66eef4 | ||
|
|
5ca3a47d40 | ||
|
|
484e61f337 | ||
|
|
196aa36970 | ||
|
|
7cd4ff72d4 | ||
|
|
1339a48da0 | ||
|
|
ea55b99116 | ||
|
|
fbbb2b9b8e | ||
|
|
87b4c1489e | ||
|
|
d224ccc52e | ||
|
|
fb5b42e9db | ||
|
|
1ea3b2d376 | ||
|
|
c370a455bd | ||
|
|
189404e22c | ||
|
|
80c53a079b | ||
|
|
e6a274cc9d | ||
|
|
c365f3e885 | ||
|
|
7cecf0641f | ||
|
|
423fa3b62a | ||
|
|
0a8015528d | ||
|
|
c9feff7224 | ||
|
|
7294e56778 | ||
|
|
8e19f55dc0 | ||
|
|
a01f8857ab | ||
|
|
e66493b733 | ||
|
|
496e2ec4ef | ||
|
|
c442e1aa47 | ||
|
|
6d4076969e | ||
|
|
b24a30314f | ||
|
|
aa257565fb | ||
|
|
fac2870604 | ||
|
|
5cdf7f13a6 | ||
|
|
4edd8287b4 | ||
|
|
d7d4df3d51 | ||
|
|
7f74b14f2c | ||
|
|
3645d033b4 | ||
|
|
72d2f84cce | ||
|
|
d2b52c476a | ||
|
|
198c04a616 | ||
|
|
86f9ccb5cd | ||
|
|
e201aed526 | ||
|
|
8f24f6c1e9 | ||
|
|
270b186f06 | ||
|
|
cd1c023d03 | ||
|
|
8d987c00a8 | ||
|
|
56b3b3a5b5 | ||
|
|
3558944c3f | ||
|
|
45acafb06c | ||
|
|
ea3f9f2876 | ||
|
|
3323287872 | ||
|
|
5f5ddc0186 | ||
|
|
3b7d5f7934 | ||
|
|
a85ec48203 | ||
|
|
514849a3bb | ||
|
|
c0898d0df2 | ||
|
|
6110a17533 | ||
|
|
b6f9b60dea | ||
|
|
7066d89440 | ||
|
|
e1c9e3969d | ||
|
|
07c7c4b9f4 | ||
|
|
98d8e76484 | ||
|
|
892d7ffb5d | ||
|
|
e33dbde806 | ||
|
|
2ef8a428d9 | ||
|
|
a88515f349 | ||
|
|
46c76269bd | ||
|
|
20baa6c384 | ||
|
|
81d40001fa | ||
|
|
b077ae3f24 | ||
|
|
931a5206b6 | ||
|
|
a030614032 | ||
|
|
9119951905 | ||
|
|
f324c60f69 | ||
|
|
831efd4849 |
82
.gitea/workflows/deploy-client.yml
Normal file
82
.gitea/workflows/deploy-client.yml
Normal file
@@ -0,0 +1,82 @@
|
||||
name: Deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
# tags:
|
||||
# - "v[0-9]+.[0-9]+.[0-9]+"
|
||||
|
||||
# paths:
|
||||
# - ".gitea/workflows/deploy-client.yml"
|
||||
# - "client/**"
|
||||
|
||||
jobs:
|
||||
publish-windows:
|
||||
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-windows-builder \
|
||||
-f ./client/Dockerfile.windows \
|
||||
./client \
|
||||
--build-arg COMMIT_SHA=${{ gitea.sha }} \
|
||||
--build-arg API_BASE_URL=${{ vars.API_BASE_URL }} \
|
||||
--build-arg TAURI_SIGNING_PRIVATE_KEY=${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
|
||||
docker create --name chad-client-windows-container chad-client-windows-builder
|
||||
mkdir -p artifacts
|
||||
docker cp chad-client-windows-container:/artifacts artifacts/
|
||||
docker rm chad-client-windows-container
|
||||
ls -la artifacts
|
||||
|
||||
- name: Publish
|
||||
uses: akkuman/gitea-release-action@v1
|
||||
with:
|
||||
files: |
|
||||
artifacts/**
|
||||
draft: true
|
||||
|
||||
# publish-web:
|
||||
# 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 -f ./client/Dockerfile.web ./client --build-arg COMMIT_SHA=${{ gitea.sha }} --build-arg API_BASE_URL=${{ vars.API_BASE_URL }}
|
||||
|
||||
# - 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
|
||||
@@ -4,9 +4,12 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
paths:
|
||||
- '.gitea/workflows/deploy-server.yml'
|
||||
- 'server/**'
|
||||
|
||||
jobs:
|
||||
server:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
@@ -21,6 +24,9 @@ jobs:
|
||||
ssh-strict: 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
|
||||
run: docker build -t chad-server ./server
|
||||
|
||||
@@ -32,9 +38,12 @@ jobs:
|
||||
docker run -d \
|
||||
--name chad-server \
|
||||
--network traefik \
|
||||
--volume /home/koptilnya/services/chad/data:/app/data \
|
||||
-p 40000-40100:40000-40100/udp \
|
||||
--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.tls=true" \
|
||||
--label "traefik.http.routers.chad-server.tls.certresolver=myresolver" \
|
||||
--label "traefik.http.services.chad-server.loadbalancer.server.port=80" \
|
||||
chad-server:latest
|
||||
2
client/.gitattributes
vendored
Normal file
2
client/.gitattributes
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/.yarn/releases/** binary
|
||||
/.yarn/plugins/** binary
|
||||
6
client/.gitignore
vendored
6
client/.gitignore
vendored
@@ -23,9 +23,15 @@ logs
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/sdks
|
||||
!.yarn/versions
|
||||
|
||||
scripts/release.ps1
|
||||
.tauri
|
||||
|
||||
updater.json
|
||||
|
||||
Binary file not shown.
942
client/.yarn/releases/yarn-4.12.0.cjs
vendored
Normal file
942
client/.yarn/releases/yarn-4.12.0.cjs
vendored
Normal file
File diff suppressed because one or more lines are too long
@@ -1 +1,3 @@
|
||||
nodeLinker: node-modules
|
||||
|
||||
yarnPath: .yarn/releases/yarn-4.12.0.cjs
|
||||
|
||||
27
client/Dockerfile.web
Normal file
27
client/Dockerfile.web
Normal file
@@ -0,0 +1,27 @@
|
||||
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
|
||||
ARG API_BASE_URL
|
||||
|
||||
ENV COMMIT_SHA=$COMMIT_SHA \
|
||||
API_BASE_URL=$API_BASE_URL
|
||||
|
||||
RUN yarn generate
|
||||
|
||||
FROM nginx:stable-alpine
|
||||
|
||||
COPY --from=builder /app/.output/public /usr/share/nginx/html
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
48
client/Dockerfile.windows
Normal file
48
client/Dockerfile.windows
Normal file
@@ -0,0 +1,48 @@
|
||||
# === Build ===
|
||||
FROM node:lts AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# RUN corepack enable yarn && yarn set version stable
|
||||
|
||||
COPY package.json yarn.lock .yarnrc.yml ./
|
||||
COPY .yarn ./.yarn
|
||||
|
||||
RUN yarn install --immutable
|
||||
COPY . .
|
||||
|
||||
ARG COMMIT_SHA=unknown
|
||||
ARG API_BASE_URL
|
||||
ARG TAURI_SIGNING_PRIVATE_KEY
|
||||
|
||||
ENV COMMIT_SHA=$COMMIT_SHA \
|
||||
API_BASE_URL=$API_BASE_URL \
|
||||
TAURI_SIGNING_PRIVATE_KEY=$TAURI_SIGNING_PRIVATE_KEY \
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD=
|
||||
|
||||
RUN apt update && apt install -y --no-install-recommends \
|
||||
nsis \
|
||||
clang \
|
||||
lld \
|
||||
llvm \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
|
||||
|
||||
ENV PATH=/root/.cargo/bin:$PATH
|
||||
|
||||
RUN rustup target add x86_64-pc-windows-msvc
|
||||
|
||||
RUN cargo install --locked cargo-xwin
|
||||
|
||||
RUN yarn tauri build --runner cargo-xwin --target x86_64-pc-windows-msvc
|
||||
|
||||
RUN node scripts/generate-updater.mjs
|
||||
|
||||
# === Artifacts ===
|
||||
FROM scratch AS artifacts
|
||||
|
||||
COPY --from=builder /app/updater.json ./artifacts
|
||||
COPY --from=builder /app/src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/ ./artifacts
|
||||
|
||||
CMD ["true"]
|
||||
@@ -1,13 +1,13 @@
|
||||
<template>
|
||||
<h1>yo</h1>
|
||||
<pre>{{ connected }}</pre>
|
||||
<audio v-for="(s, i) in streams" :key="i" :ref="(el) => onAudioRef(el, s)" autoplay controls />
|
||||
<NuxtLayout>
|
||||
<NuxtPage />
|
||||
</NuxtLayout>
|
||||
|
||||
<PrimeToast position="bottom-center" />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
const { connected, streams } = useMediasoup()
|
||||
|
||||
function onAudioRef(ref: Element, stream: MediaStream) {
|
||||
(ref as HTMLAudioElement).srcObject = stream
|
||||
}
|
||||
<script setup lang="ts">
|
||||
console.group('Build Info')
|
||||
console.log(`COMMIT_SHA: ${__COMMIT_SHA__}`)
|
||||
console.groupEnd()
|
||||
</script>
|
||||
|
||||
13
client/app/assets/styles/main.scss
Normal file
13
client/app/assets/styles/main.scss
Normal file
@@ -0,0 +1,13 @@
|
||||
|
||||
html,
|
||||
body {
|
||||
font-family: 'Inter', sans-serif;
|
||||
font-size: 16px;
|
||||
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#__nuxt {
|
||||
height: 100%;
|
||||
}
|
||||
1
client/app/assets/styles/primeicons.css
Normal file
1
client/app/assets/styles/primeicons.css
Normal file
@@ -0,0 +1 @@
|
||||
@import 'primeicons/primeicons.css';
|
||||
2
client/app/assets/styles/tailwind.css
Normal file
2
client/app/assets/styles/tailwind.css
Normal file
@@ -0,0 +1,2 @@
|
||||
@import "tailwindcss";
|
||||
@import "tailwindcss-primeui";
|
||||
28
client/app/components.d.ts
vendored
Normal file
28
client/app/components.d.ts
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
/* 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']
|
||||
PrimeFloatLabel: typeof import('primevue/floatlabel')['default']
|
||||
PrimeInputText: typeof import('primevue/inputtext')['default']
|
||||
PrimeMenu: typeof import('primevue/menu')['default']
|
||||
PrimePanel: typeof import('primevue/panel')['default']
|
||||
PrimePassword: typeof import('primevue/password')['default']
|
||||
PrimeProgressBar: typeof import('primevue/progressbar')['default']
|
||||
PrimeSelectButton: typeof import('primevue/selectbutton')['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']
|
||||
}
|
||||
}
|
||||
25
client/app/components/AppHeader.vue
Normal file
25
client/app/components/AppHeader.vue
Normal 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>
|
||||
106
client/app/components/ClientRow.vue
Normal file
106
client/app/components/ClientRow.vue
Normal file
@@ -0,0 +1,106 @@
|
||||
<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.displayName }}
|
||||
</div>
|
||||
<div v-if="client.username !== client.displayName" class="mt-1 text-xs leading-5 text-muted-color">
|
||||
{{ client.username }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PrimeBadge v-if="audioConsumerPaused" severity="info" value="Muted" />
|
||||
<PrimeBadge v-if="isMe" severity="secondary" value="You" />
|
||||
|
||||
<template v-if="!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 { me } = useClients()
|
||||
|
||||
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 isMe = computed(() => {
|
||||
return me.value && props.client.userId === me.value.userId
|
||||
})
|
||||
|
||||
const audioConsumer = computed(() => {
|
||||
if (isMe.value)
|
||||
return undefined
|
||||
|
||||
const consumers = getClientConsumers(props.client.socketId)
|
||||
|
||||
return consumers.find(consumer => consumer.track.kind === 'audio')
|
||||
})
|
||||
|
||||
const audioConsumerPaused = computed(() => {
|
||||
if (isMe.value)
|
||||
return false
|
||||
|
||||
const consumers = getClientConsumers(props.client.socketId)
|
||||
|
||||
return consumers.find(consumer => consumer.track.kind === 'audio')?.paused
|
||||
})
|
||||
|
||||
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>
|
||||
91
client/app/composables/use-app.ts
Normal file
91
client/app/composables/use-app.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { getVersion } from '@tauri-apps/api/app'
|
||||
|
||||
import { computedAsync, 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 isTauri = computed(() => '__TAURI_INTERNALS__' in window)
|
||||
|
||||
const version = computedAsync(() => isTauri.value ? getVersion() : 'web', '-')
|
||||
|
||||
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.pauseProducer('microphone')
|
||||
}
|
||||
else {
|
||||
if (outputMuted.value) {
|
||||
outputMuted.value = false
|
||||
}
|
||||
await mediasoup.resumeProducer('microphone')
|
||||
}
|
||||
|
||||
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,
|
||||
inputMuted,
|
||||
muteInput,
|
||||
unmuteInput,
|
||||
toggleInput,
|
||||
outputMuted,
|
||||
muteOutput,
|
||||
unmuteOutput,
|
||||
toggleOutput,
|
||||
version,
|
||||
isTauri,
|
||||
}
|
||||
})
|
||||
59
client/app/composables/use-audio-context.ts
Normal file
59
client/app/composables/use-audio-context.ts
Normal 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,
|
||||
}
|
||||
}
|
||||
69
client/app/composables/use-auth.ts
Normal file
69
client/app/composables/use-auth.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import chadApi from '#shared/chad-api'
|
||||
import { createGlobalState } from '@vueuse/core'
|
||||
|
||||
interface Me {
|
||||
id: string
|
||||
username: string
|
||||
displayName: string
|
||||
}
|
||||
|
||||
export const useAuth = createGlobalState(() => {
|
||||
const me = shallowRef<Me>()
|
||||
|
||||
function setMe(value: Me | undefined): void {
|
||||
me.value = value
|
||||
}
|
||||
|
||||
async function login(username: string, password: string): Promise<void> {
|
||||
try {
|
||||
const result = await chadApi<Me>('/login', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
username,
|
||||
password,
|
||||
},
|
||||
})
|
||||
|
||||
setMe(result)
|
||||
|
||||
await navigateTo('/')
|
||||
}
|
||||
catch {}
|
||||
}
|
||||
|
||||
async function register(username: string, password: string): Promise<void> {
|
||||
try {
|
||||
const result = await chadApi<Me>('/register', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
username,
|
||||
password,
|
||||
},
|
||||
})
|
||||
|
||||
setMe(result)
|
||||
|
||||
await navigateTo('/')
|
||||
}
|
||||
catch {}
|
||||
}
|
||||
|
||||
async function logout(): Promise<void> {
|
||||
try {
|
||||
await chadApi('/logout', { method: 'POST' })
|
||||
|
||||
setMe(undefined)
|
||||
|
||||
await navigateTo({ name: 'Login' })
|
||||
}
|
||||
catch {}
|
||||
}
|
||||
|
||||
return {
|
||||
me: readonly(me),
|
||||
setMe,
|
||||
login,
|
||||
register,
|
||||
logout,
|
||||
}
|
||||
})
|
||||
66
client/app/composables/use-clients.ts
Normal file
66
client/app/composables/use-clients.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import type { ChadClient, UpdatedClient } from '#shared/types'
|
||||
import { createGlobalState } from '@vueuse/core'
|
||||
|
||||
export const useClients = createGlobalState(() => {
|
||||
const auth = useAuth()
|
||||
const signaling = useSignaling()
|
||||
const toast = useToast()
|
||||
|
||||
const clients = shallowRef<ChadClient[]>([])
|
||||
|
||||
const me = computed(() => clients.value.find(client => client.userId === auth.me.value?.id))
|
||||
|
||||
watch(signaling.socket, (socket) => {
|
||||
if (!socket)
|
||||
return
|
||||
|
||||
socket.on('clientChanged', (clientId: ChadClient['socketId'], updatedClient: UpdatedClient) => {
|
||||
const client = getClient(clientId)
|
||||
updateClient(clientId, updatedClient)
|
||||
|
||||
if (client && client.displayName !== updatedClient.displayName)
|
||||
toast.add({ severity: 'info', summary: `${client.displayName} is now ${updatedClient.displayName}`, closable: false, life: 1000 })
|
||||
})
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
clients.value = []
|
||||
})
|
||||
})
|
||||
|
||||
function getClient(clientId: ChadClient['socketId']) {
|
||||
return clients.value.find(client => client.socketId === clientId)
|
||||
}
|
||||
|
||||
function addClient(...client: ChadClient[]) {
|
||||
clients.value.push(...client)
|
||||
|
||||
triggerRef(clients)
|
||||
}
|
||||
|
||||
function removeClient(clientId: ChadClient['socketId']) {
|
||||
clients.value = clients.value.filter(client => client.socketId !== clientId)
|
||||
}
|
||||
|
||||
function updateClient(clientId: ChadClient['socketId'], updatedClient: UpdatedClient) {
|
||||
const clientIdx = clients.value.findIndex(client => client.socketId === clientId)
|
||||
|
||||
if (clientIdx === -1)
|
||||
return
|
||||
|
||||
clients.value[clientIdx] = {
|
||||
...clients.value[clientIdx],
|
||||
...updatedClient,
|
||||
} as ChadClient
|
||||
|
||||
triggerRef(clients)
|
||||
}
|
||||
|
||||
return {
|
||||
me,
|
||||
clients,
|
||||
getClient,
|
||||
addClient,
|
||||
removeClient,
|
||||
updateClient,
|
||||
}
|
||||
})
|
||||
@@ -1,122 +1,376 @@
|
||||
import type { Socket } from 'socket.io-client'
|
||||
import { createGlobalState } from '@vueuse/core'
|
||||
import type { ChadClient } from '#shared/types'
|
||||
import { createSharedComposable } from '@vueuse/core'
|
||||
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 socket: Socket = io('http://localhost:1337', {
|
||||
transports: ['websocket'],
|
||||
})
|
||||
type ProducerType = 'microphone' | 'camera' | 'share'
|
||||
|
||||
const initializing = ref(false)
|
||||
const connected = ref(false)
|
||||
const streams = shallowRef<MediaStream[]>([])
|
||||
let device: mediasoupClient.Device
|
||||
let sendTransport: mediasoupClient.types.Transport
|
||||
let recvTransport: mediasoupClient.types.Transport
|
||||
const ICE_SERVERS: RTCIceServer[] = [
|
||||
{ urls: 'stun:stun.l.google.com:19302' },
|
||||
{ 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' },
|
||||
]
|
||||
|
||||
socket.on('newProducer', async ({ producerId }) => {
|
||||
const params = await socket.emitWithAck('consume', {
|
||||
producerId,
|
||||
transportId: recvTransport.id,
|
||||
rtpCapabilities: device.rtpCapabilities,
|
||||
})
|
||||
export const useMediasoup = createSharedComposable(() => {
|
||||
const toast = useToast()
|
||||
|
||||
if (params?.error) {
|
||||
console.error('consume error:', params.error)
|
||||
const signaling = useSignaling()
|
||||
const { addClient, removeClient } = useClients()
|
||||
const preferences = usePreferences()
|
||||
const { me } = useAuth()
|
||||
|
||||
const device = shallowRef<mediasoupClient.Device>()
|
||||
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 cameraProducer = 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
|
||||
}
|
||||
|
||||
const consumer = await recvTransport.consume(params)
|
||||
const stream = new MediaStream([consumer.track])
|
||||
socket.on('authenticated', async () => {
|
||||
if (!signaling.socket.value)
|
||||
return
|
||||
|
||||
streams.value.push(stream)
|
||||
triggerRef(streams)
|
||||
device.value = new mediasoupClient.Device()
|
||||
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() {
|
||||
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) => {
|
||||
sendTransport.value.on('connect', async ({ dtlsParameters }, callback, errback) => {
|
||||
try {
|
||||
await socket.emitWithAck('connectTransport', {
|
||||
transportId: sendTransport.id,
|
||||
await signaling.socket.value!.emitWithAck('connectTransport', {
|
||||
transportId: sendTransport.value!.id,
|
||||
dtlsParameters,
|
||||
})
|
||||
|
||||
callback()
|
||||
}
|
||||
catch (err) {
|
||||
errback(err)
|
||||
catch (error) {
|
||||
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 {
|
||||
const { id } = await socket.emitWithAck('produce', {
|
||||
transportId: sendTransport.id,
|
||||
const { id } = await signaling.socket.value!.emitWithAck('produce', {
|
||||
transportId: sendTransport.value!.id,
|
||||
kind,
|
||||
rtpParameters,
|
||||
appData,
|
||||
})
|
||||
callback({ id })
|
||||
}
|
||||
catch (err) {
|
||||
errback(err)
|
||||
catch (error) {
|
||||
if (error instanceof Error) {
|
||||
errback(error)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function publishMic() {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
|
||||
const track = stream.getAudioTracks()[0]
|
||||
// Recv Transport
|
||||
{
|
||||
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 })
|
||||
}
|
||||
|
||||
async function createRecvTransport() {
|
||||
const params = await socket.emitWithAck('createTransport')
|
||||
recvTransport = device.createRecvTransport(params)
|
||||
|
||||
recvTransport.on('connect', async ({ dtlsParameters }, callback, errback) => {
|
||||
recvTransport.value.on('connect', async ({ dtlsParameters }, callback, errback) => {
|
||||
try {
|
||||
await socket.emitWithAck('connectTransport', {
|
||||
transportId: recvTransport.id,
|
||||
await signaling.socket.value!.emitWithAck('connectTransport', {
|
||||
transportId: recvTransport.value!.id,
|
||||
dtlsParameters,
|
||||
})
|
||||
|
||||
callback()
|
||||
}
|
||||
catch (err) {
|
||||
errback(err)
|
||||
catch (error) {
|
||||
if (error instanceof Error) {
|
||||
errback(error)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
(async () => {
|
||||
if (initializing.value || connected.value)
|
||||
const joinedClients = (await signaling.socket.value.emitWithAck('join', {
|
||||
rtpCapabilities: rtpCapabilities.value,
|
||||
}))
|
||||
|
||||
addClient(...joinedClients)
|
||||
|
||||
toast.add({ severity: 'success', summary: 'Joined', closable: false, life: 1000 })
|
||||
|
||||
await enableMic()
|
||||
})
|
||||
|
||||
socket.on('newPeer', (client) => {
|
||||
addClient(client)
|
||||
})
|
||||
|
||||
socket.on('peerClosed', (id) => {
|
||||
removeClient(id)
|
||||
})
|
||||
|
||||
socket.on(
|
||||
'newConsumer',
|
||||
async (
|
||||
{ id, producerId, kind, rtpParameters, socketId, appData, producerPaused },
|
||||
cb,
|
||||
) => {
|
||||
if (!recvTransport.value)
|
||||
return
|
||||
|
||||
initializing.value = true
|
||||
connected.value = false
|
||||
const consumer = await recvTransport.value.consume({
|
||||
id,
|
||||
producerId,
|
||||
kind,
|
||||
rtpParameters,
|
||||
streamId: `${socketId}-${appData.share ? 'share' : 'mic-webcam'}`,
|
||||
appData: { ...appData, socketId },
|
||||
})
|
||||
|
||||
await loadDevice()
|
||||
await createSendTransport()
|
||||
await createRecvTransport()
|
||||
await publishMic()
|
||||
if (producerPaused)
|
||||
consumer.pause()
|
||||
|
||||
initializing.value = false
|
||||
connected.value = true
|
||||
})()
|
||||
consumer.on('transportclose', () => {
|
||||
if (consumers.value.delete(consumer.id))
|
||||
triggerRef(consumers)
|
||||
})
|
||||
|
||||
consumers.value.set(consumer.id, consumer)
|
||||
triggerRef(consumers)
|
||||
|
||||
cb()
|
||||
},
|
||||
)
|
||||
|
||||
socket.on(
|
||||
'consumerClosed',
|
||||
async (
|
||||
{ consumerId },
|
||||
) => {
|
||||
if (consumers.value.delete(consumerId))
|
||||
triggerRef(consumers)
|
||||
},
|
||||
)
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
device.value = undefined
|
||||
rtpCapabilities.value = undefined
|
||||
|
||||
sendTransport.value?.close()
|
||||
sendTransport.value = undefined
|
||||
|
||||
recvTransport.value?.close()
|
||||
recvTransport.value = undefined
|
||||
|
||||
micProducer.value = undefined
|
||||
cameraProducer.value = undefined
|
||||
shareProducer.value = undefined
|
||||
|
||||
consumers.value = new Map()
|
||||
producers.value = new Map()
|
||||
})
|
||||
|
||||
socket.on('consumerPaused', ({ consumerId }) => {
|
||||
const consumer = consumers.value.get(consumerId)
|
||||
|
||||
if (!consumer)
|
||||
return
|
||||
|
||||
consumer.pause()
|
||||
|
||||
console.log(consumerId)
|
||||
|
||||
triggerRef(consumers)
|
||||
})
|
||||
|
||||
socket.on('consumerResumed', ({ consumerId }) => {
|
||||
const consumer = consumers.value.get(consumerId)
|
||||
|
||||
if (!consumer)
|
||||
return
|
||||
|
||||
consumer.resume()
|
||||
|
||||
triggerRef(consumers)
|
||||
})
|
||||
}, { immediate: true, flush: 'sync' })
|
||||
|
||||
function getClientConsumers(socketId: ChadClient['socketId']) {
|
||||
return consumers.value.values().filter(consumer => consumer.appData.socketId === socketId)
|
||||
}
|
||||
|
||||
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 pauseProducer(type: ProducerType) {
|
||||
if (!signaling.socket.value)
|
||||
return
|
||||
|
||||
const producer = getProducerByType(type)
|
||||
|
||||
if (!producer)
|
||||
return
|
||||
|
||||
if (producer.paused)
|
||||
return
|
||||
|
||||
try {
|
||||
producer.pause()
|
||||
|
||||
await signaling.socket.value.emitWithAck('pauseProducer', {
|
||||
producerId: producer.id,
|
||||
})
|
||||
}
|
||||
catch {
|
||||
producer.resume()
|
||||
}
|
||||
}
|
||||
|
||||
async function resumeProducer(type: ProducerType) {
|
||||
if (!signaling.socket.value)
|
||||
return
|
||||
|
||||
const producer = getProducerByType(type)
|
||||
|
||||
if (!producer)
|
||||
return
|
||||
|
||||
try {
|
||||
producer.resume()
|
||||
|
||||
await signaling.socket.value.emitWithAck('resumeProducer', {
|
||||
producerId: producer.id,
|
||||
})
|
||||
}
|
||||
catch {
|
||||
producer.pause()
|
||||
}
|
||||
}
|
||||
|
||||
async function init() {
|
||||
signaling.connect()
|
||||
}
|
||||
|
||||
function getProducerByType(type: ProducerType) {
|
||||
switch (type) {
|
||||
case 'microphone':
|
||||
return micProducer.value
|
||||
case 'camera':
|
||||
return cameraProducer.value
|
||||
case 'share':
|
||||
return shareProducer.value
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
connected,
|
||||
streams,
|
||||
init,
|
||||
consumers,
|
||||
producers,
|
||||
sendTransport,
|
||||
recvTransport,
|
||||
rtpCapabilities,
|
||||
device,
|
||||
micProducer,
|
||||
cameraProducer,
|
||||
shareProducer,
|
||||
getClientConsumers,
|
||||
pauseProducer,
|
||||
resumeProducer,
|
||||
}
|
||||
})
|
||||
|
||||
22
client/app/composables/use-preferences.ts
Normal file
22
client/app/composables/use-preferences.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { createGlobalState, useDevicesList } from '@vueuse/core'
|
||||
|
||||
export const usePreferences = createGlobalState(() => {
|
||||
const inputDeviceId = shallowRef<MediaDeviceInfo['deviceId']>()
|
||||
const outputDeviceId = shallowRef<MediaDeviceInfo['deviceId']>()
|
||||
|
||||
const {
|
||||
ensurePermissions,
|
||||
permissionGranted,
|
||||
videoInputs,
|
||||
audioInputs,
|
||||
audioOutputs,
|
||||
} = useDevicesList()
|
||||
|
||||
return {
|
||||
inputDeviceId,
|
||||
outputDeviceId,
|
||||
videoInputs,
|
||||
audioInputs,
|
||||
audioOutputs,
|
||||
}
|
||||
})
|
||||
86
client/app/composables/use-signaling.ts
Normal file
86
client/app/composables/use-signaling.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import type { Socket } from 'socket.io-client'
|
||||
import { createSharedComposable } from '@vueuse/core'
|
||||
import { io } from 'socket.io-client'
|
||||
import { parseURL } from 'ufo'
|
||||
|
||||
export const useSignaling = createSharedComposable(() => {
|
||||
const toast = useToast()
|
||||
const { me } = useAuth()
|
||||
|
||||
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 })
|
||||
|
||||
watch(me, (me) => {
|
||||
if (!me) {
|
||||
socket.value?.close()
|
||||
socket.value = undefined
|
||||
}
|
||||
})
|
||||
|
||||
onScopeDispose(() => {
|
||||
socket.value?.close()
|
||||
socket.value = undefined
|
||||
})
|
||||
|
||||
function connect() {
|
||||
if (socket.value || !me.value)
|
||||
return
|
||||
|
||||
const { protocol, host, pathname } = parseURL(__API_BASE_URL__)
|
||||
|
||||
const uri = host ? `${protocol}//${host}` : ``
|
||||
|
||||
socket.value = io(`http://localhost:4000/webrtc`, {
|
||||
path: `/chad/ws`,
|
||||
transports: ['websocket'],
|
||||
// socket.value = io(`${uri}/webrtc`, {
|
||||
// path: `${pathname}/ws`,
|
||||
withCredentials: true,
|
||||
auth: {
|
||||
userId: me.value.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
socket,
|
||||
connected,
|
||||
connect,
|
||||
}
|
||||
})
|
||||
27
client/app/composables/use-updater.ts
Normal file
27
client/app/composables/use-updater.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import type { Update } from '@tauri-apps/plugin-updater'
|
||||
import { check } from '@tauri-apps/plugin-updater'
|
||||
import { createGlobalState } from '@vueuse/core'
|
||||
|
||||
export const useUpdater = createGlobalState(() => {
|
||||
const lastUpdate = shallowRef<Update>()
|
||||
|
||||
const checking = ref(false)
|
||||
|
||||
async function checkForUpdates() {
|
||||
try {
|
||||
checking.value = true
|
||||
|
||||
lastUpdate.value = (await check()) ?? undefined
|
||||
}
|
||||
finally {
|
||||
checking.value = false
|
||||
}
|
||||
|
||||
return lastUpdate.value
|
||||
}
|
||||
|
||||
return {
|
||||
lastUpdate,
|
||||
checkForUpdates,
|
||||
}
|
||||
})
|
||||
7
client/app/index.d.ts
vendored
Normal file
7
client/app/index.d.ts
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
declare module '#app' {
|
||||
interface PageMeta {
|
||||
auth?: boolean | 'guest'
|
||||
}
|
||||
}
|
||||
|
||||
export {}
|
||||
43
client/app/layouts/auth.vue
Normal file
43
client/app/layouts/auth.vue
Normal file
@@ -0,0 +1,43 @@
|
||||
<template>
|
||||
<div class="w-full h-full flex p-3">
|
||||
<img src="/chad-bg.webp" alt="Background" draggable="false" class="pointer-events-none absolute opacity-3 -z-1 block inset-0 object-contain w-full h-full">
|
||||
|
||||
<div v-auto-animate class="w-1/2 m-auto">
|
||||
<div class="text-center">
|
||||
<PrimeSelectButton v-model="tab" class="mb-6" :options="options" option-label="label" :allow-empty="false" />
|
||||
</div>
|
||||
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PrimeBadge class="fixed top-3 right-3 opacity-50" severity="secondary" :value="version" size="small" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const route = useRoute()
|
||||
const { version } = useApp()
|
||||
|
||||
const options = computed(() => {
|
||||
return [
|
||||
{
|
||||
label: 'Login',
|
||||
routeName: 'Login',
|
||||
},
|
||||
{
|
||||
label: 'Register',
|
||||
routeName: 'Register',
|
||||
|
||||
},
|
||||
]
|
||||
})
|
||||
|
||||
const tab = shallowRef(options.value.find(option => route.name === option.routeName))
|
||||
|
||||
watch(tab, (tab) => {
|
||||
if (!tab)
|
||||
return
|
||||
|
||||
navigateTo({ name: tab.routeName })
|
||||
})
|
||||
</script>
|
||||
3
client/app/layouts/blank.vue
Normal file
3
client/app/layouts/blank.vue
Normal file
@@ -0,0 +1,3 @@
|
||||
<template>
|
||||
<slot />
|
||||
</template>
|
||||
52
client/app/layouts/default.vue
Normal file
52
client/app/layouts/default.vue
Normal file
@@ -0,0 +1,52 @@
|
||||
<template>
|
||||
<div 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>
|
||||
|
||||
<div class="overflow-y-auto">
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="fixed top-3 right-3 inline-flex items-center gap-3">
|
||||
<PrimeBadge v-if="isTauri" class="opacity-50" severity="secondary" :value="version" size="small" />
|
||||
<PrimeBadge :severity="connected ? 'success' : 'danger' " />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const { clients, inputMuted, toggleInput, outputMuted, toggleOutput, version, isTauri } = useApp()
|
||||
const { connect, connected } = useSignaling()
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
const inPreferences = computed(() => {
|
||||
return route.name === 'Preferences'
|
||||
})
|
||||
|
||||
function onClickPreferences() {
|
||||
navigateTo(!inPreferences.value ? { name: 'Preferences' } : '/')
|
||||
}
|
||||
|
||||
connect()
|
||||
</script>
|
||||
20
client/app/middleware/00.updater.global.ts
Normal file
20
client/app/middleware/00.updater.global.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
export default defineNuxtRouteMiddleware(async (to, from) => {
|
||||
if (import.meta.dev || import.meta.server)
|
||||
return
|
||||
|
||||
const { isTauri } = useApp()
|
||||
|
||||
if (!isTauri.value)
|
||||
return
|
||||
|
||||
if (from?.name)
|
||||
return
|
||||
|
||||
const { checkForUpdates } = useUpdater()
|
||||
|
||||
const update = await checkForUpdates()
|
||||
|
||||
if (update) {
|
||||
return navigateTo({ name: 'Updating' })
|
||||
}
|
||||
})
|
||||
20
client/app/middleware/01.auth.global.ts
Normal file
20
client/app/middleware/01.auth.global.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import chadApi from '#shared/chad-api'
|
||||
|
||||
export default defineNuxtRouteMiddleware(async (to, from) => {
|
||||
const { me, setMe } = useAuth()
|
||||
|
||||
if (!me.value && !from?.name) {
|
||||
try {
|
||||
setMe(await chadApi('/me'))
|
||||
}
|
||||
catch {
|
||||
if (to.meta.auth !== 'guest') {
|
||||
return navigateTo({ name: 'Login' })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (me.value && to.meta.auth === 'guest') {
|
||||
return navigateTo('/')
|
||||
}
|
||||
})
|
||||
62
client/app/pages/index.vue
Normal file
62
client/app/pages/index.vue
Normal file
@@ -0,0 +1,62 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-3 p-3 pt-12">
|
||||
<PrimePanel header="Clients" toggleable collapsed :pt="{ content: { class: 'divide-y divide-surface-800 py-4' } }">
|
||||
<dl v-for="client in clients" :key="client.socketId" class="">
|
||||
<div v-for="(value, key) in client" :key="key" class="py-2">
|
||||
<dt class="font-bold">
|
||||
{{ key }}
|
||||
</dt>
|
||||
<dd class="pl-8">
|
||||
{{ value }}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</PrimePanel>
|
||||
|
||||
<PrimePanel header="Producers" toggleable collapsed :pt="{ content: { class: 'divide-y divide-surface-800 py-4' } }">
|
||||
<dl v-for="[_, producer] in Array.from(producers)" :key="producer.id" class="">
|
||||
<div v-for="key in ['id', 'paused']" :key="key" class="py-2">
|
||||
<dt class="font-bold">
|
||||
{{ key }}
|
||||
</dt>
|
||||
<dd class="pl-8">
|
||||
{{ producer[key] }}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</PrimePanel>
|
||||
|
||||
<PrimePanel header="Consumers" toggleable collapsed :pt="{ content: { class: 'divide-y divide-surface-800 py-4' } }">
|
||||
<dl v-for="[_, consumer] in Array.from(consumers)" :key="consumer.id" class="">
|
||||
<div v-for="key in ['id', 'paused']" :key="key" class="py-2">
|
||||
<dt class="font-bold">
|
||||
{{ key }}
|
||||
</dt>
|
||||
<dd class="pl-8">
|
||||
{{ consumer[key] }}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</PrimePanel>
|
||||
</div>
|
||||
|
||||
<!-- <div class="flex items-center justify-center p-3"> -->
|
||||
<!-- <PrimeCard> -->
|
||||
<!-- <template #subtitle> -->
|
||||
<!-- Important information -->
|
||||
<!-- </template> -->
|
||||
|
||||
<!-- <template #content> -->
|
||||
<!-- The chat is under development. -->
|
||||
<!-- </template> -->
|
||||
<!-- </PrimeCard> -->
|
||||
<!-- </div> -->
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const { clients } = useClients()
|
||||
const { producers, consumers } = useMediasoup()
|
||||
|
||||
definePageMeta({
|
||||
})
|
||||
</script>
|
||||
67
client/app/pages/login.vue
Normal file
67
client/app/pages/login.vue
Normal file
@@ -0,0 +1,67 @@
|
||||
<template>
|
||||
<PrimeCard>
|
||||
<template #content>
|
||||
<form @submit.prevent="submit">
|
||||
<div class="flex flex-col gap-3">
|
||||
<PrimeFloatLabel variant="on">
|
||||
<PrimeInputText id="username" v-model="username" size="large" autocomplete="off" fluid autofocus />
|
||||
<label for="username">Username</label>
|
||||
</PrimeFloatLabel>
|
||||
|
||||
<PrimeFloatLabel variant="on">
|
||||
<PrimePassword id="password" v-model="password" size="large" autocomplete="off" toggle-mask fluid :feedback="false" />
|
||||
<label for="password">Password</label>
|
||||
</PrimeFloatLabel>
|
||||
</div>
|
||||
|
||||
<PrimeButton
|
||||
class="mt-6"
|
||||
size="large"
|
||||
icon="pi pi-arrow-right"
|
||||
icon-pos="right"
|
||||
label="Let's go"
|
||||
:loading="submitting"
|
||||
:disabled="!valid"
|
||||
type="submit"
|
||||
fluid
|
||||
/>
|
||||
</form>
|
||||
</template>
|
||||
</PrimeCard>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
definePageMeta({
|
||||
name: 'Login',
|
||||
layout: 'auth',
|
||||
auth: 'guest',
|
||||
})
|
||||
|
||||
const { login } = useAuth()
|
||||
|
||||
const submitting = ref(false)
|
||||
|
||||
const username = ref<string>()
|
||||
const password = ref<string>()
|
||||
|
||||
const valid = computed(() => {
|
||||
if (!username.value)
|
||||
return false
|
||||
|
||||
if (!password.value)
|
||||
return false
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
async function submit() {
|
||||
if (!valid.value)
|
||||
return
|
||||
|
||||
submitting.value = true
|
||||
|
||||
await login(username.value!, password.value!)
|
||||
|
||||
submitting.value = false
|
||||
}
|
||||
</script>
|
||||
95
client/app/pages/preferences.vue
Normal file
95
client/app/pages/preferences.vue
Normal file
@@ -0,0 +1,95 @@
|
||||
<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="displayName" size="large" fluid autocomplete="off" />
|
||||
<label for="username">Username</label>
|
||||
</PrimeFloatLabel>
|
||||
|
||||
<PrimeButton label="Save" type="submit" :disabled="!valid" />
|
||||
</form>
|
||||
|
||||
<div v-if="isTauri" class="p-3">
|
||||
<PrimeButton label="Check for Updates" fluid severity="info" @click="onCheckForUpdates" />
|
||||
</div>
|
||||
|
||||
<div class="p-3">
|
||||
<PrimeButton label="Logout" fluid severity="danger" @click="logout()" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PrimeToast position="bottom-center" group="updater">
|
||||
<template #container="slotProps">
|
||||
<div class="p-3">
|
||||
<div class="font-medium text-lg mb-4">
|
||||
{{ slotProps.message.detail }}
|
||||
</div>
|
||||
<div class="flex gap-3">
|
||||
<PrimeButton size="small" label="Update now" @click="() => {}" />
|
||||
<PrimeButton size="small" label="Later" severity="secondary" outlined @click="slotProps.closeCallback()" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</PrimeToast>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
definePageMeta({
|
||||
name: 'Preferences',
|
||||
})
|
||||
|
||||
const { isTauri } = useApp()
|
||||
const { checkForUpdates } = useUpdater()
|
||||
const { me, setMe, logout } = useAuth()
|
||||
|
||||
const signaling = useSignaling()
|
||||
const toast = useToast()
|
||||
|
||||
const displayName = ref(me.value?.displayName || '')
|
||||
|
||||
const valid = computed(() => {
|
||||
if (!displayName.value || !me.value)
|
||||
return false
|
||||
|
||||
if (displayName.value === me.value.displayName)
|
||||
return false
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
async function onCheckForUpdates() {
|
||||
const update = await checkForUpdates()
|
||||
|
||||
toast.removeGroup('updater')
|
||||
|
||||
if (!update) {
|
||||
toast.add({ severity: 'success', summary: 'You are up to date', closable: false, life: 1000 })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
toast.add({
|
||||
group: 'updater',
|
||||
severity: 'info',
|
||||
detail: `Version ${update?.version ?? '1.0.1'} is available!`,
|
||||
closable: false,
|
||||
})
|
||||
|
||||
// asdasd
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!valid.value)
|
||||
return
|
||||
|
||||
const updatedMe = await signaling.socket.value?.emitWithAck('updateClient', {
|
||||
displayName: displayName.value,
|
||||
})
|
||||
|
||||
setMe({ ...me.value, displayName: updatedMe.displayName })
|
||||
|
||||
toast.add({ severity: 'success', summary: 'Saved', life: 1000, closable: false })
|
||||
}
|
||||
</script>
|
||||
74
client/app/pages/register.vue
Normal file
74
client/app/pages/register.vue
Normal file
@@ -0,0 +1,74 @@
|
||||
<template>
|
||||
<PrimeCard>
|
||||
<template #content>
|
||||
<form @submit.prevent="submit">
|
||||
<div class="flex flex-col gap-3">
|
||||
<PrimeFloatLabel variant="on">
|
||||
<PrimeInputText id="username" v-model="username" size="large" autocomplete="off" fluid autofocus />
|
||||
<label for="username">Username</label>
|
||||
</PrimeFloatLabel>
|
||||
|
||||
<PrimeFloatLabel variant="on">
|
||||
<PrimePassword id="password" v-model="password" size="large" autocomplete="off" toggle-mask fluid :feedback="false" />
|
||||
<label for="password">Password</label>
|
||||
</PrimeFloatLabel>
|
||||
|
||||
<PrimeFloatLabel variant="on">
|
||||
<PrimePassword id="repeatPassword" v-model="repeatPassword" size="large" autocomplete="off" toggle-mask fluid :feedback="false" />
|
||||
<label for="repeatPassword">Repeat password</label>
|
||||
</PrimeFloatLabel>
|
||||
</div>
|
||||
|
||||
<PrimeButton
|
||||
class="mt-6"
|
||||
size="large"
|
||||
label="Register"
|
||||
:loading="submitting"
|
||||
:disabled="!valid"
|
||||
type="submit"
|
||||
fluid
|
||||
/>
|
||||
</form>
|
||||
</template>
|
||||
</PrimeCard>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
definePageMeta({
|
||||
name: 'Register',
|
||||
layout: 'auth',
|
||||
auth: 'guest',
|
||||
})
|
||||
|
||||
const { register } = useAuth()
|
||||
|
||||
const submitting = ref(false)
|
||||
|
||||
const username = ref<string>()
|
||||
const password = ref<string>()
|
||||
const repeatPassword = ref<string>()
|
||||
|
||||
const valid = computed(() => {
|
||||
if (!username.value)
|
||||
return false
|
||||
|
||||
if (!password.value)
|
||||
return false
|
||||
|
||||
if (repeatPassword.value !== password.value)
|
||||
return false
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
async function submit() {
|
||||
if (!valid.value)
|
||||
return
|
||||
|
||||
submitting.value = true
|
||||
|
||||
await register(username.value!, password.value!)
|
||||
|
||||
submitting.value = false
|
||||
}
|
||||
</script>
|
||||
42
client/app/pages/updater.vue
Normal file
42
client/app/pages/updater.vue
Normal file
@@ -0,0 +1,42 @@
|
||||
<template>
|
||||
<div class="flex h-full">
|
||||
<div class="w-80 m-auto">
|
||||
<p class="text-center text-muted-color mb-4">
|
||||
Updating...
|
||||
</p>
|
||||
|
||||
<PrimeProgressBar mode="indeterminate" style="height: 8px;" />
|
||||
|
||||
<div class="flex items-center justify-center gap-2 mt-8">
|
||||
<PrimeBadge :value="lastUpdate.currentVersion" size="small" severity="secondary" />
|
||||
<i class="pi pi-arrow-right" style="font-size: 0.75rem;" />
|
||||
<PrimeBadge :value="lastUpdate.version" size="small" severity="contrast" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
definePageMeta({
|
||||
name: 'Updater',
|
||||
layout: 'blank',
|
||||
auth: false,
|
||||
middleware: () => {
|
||||
const { lastUpdate } = useUpdater()
|
||||
|
||||
if (!lastUpdate.value)
|
||||
return navigateTo('/')
|
||||
},
|
||||
})
|
||||
|
||||
const lastUpdate = useUpdater().lastUpdate.value!
|
||||
|
||||
;(async () => {
|
||||
try {
|
||||
await lastUpdate.downloadAndInstall()
|
||||
}
|
||||
catch {
|
||||
await navigateTo('/')
|
||||
}
|
||||
})()
|
||||
</script>
|
||||
@@ -5,6 +5,9 @@ export default antfu({
|
||||
css: true,
|
||||
},
|
||||
overrides: {
|
||||
typescript: {
|
||||
'no-console': 'off',
|
||||
},
|
||||
vue: {
|
||||
'vue/block-order': ['error', {
|
||||
order: ['template', 'script', 'style'],
|
||||
|
||||
2
client/globals.d.ts
vendored
Normal file
2
client/globals.d.ts
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
declare const __API_BASE_URL__: string
|
||||
declare const __COMMIT_SHA__: string
|
||||
@@ -1,15 +1,104 @@
|
||||
import { definePreset } from '@primeuix/themes'
|
||||
import Aura from '@primeuix/themes/aura'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
export default defineNuxtConfig({
|
||||
compatibilityDate: '2025-09-29',
|
||||
devtools: { enabled: true },
|
||||
devtools: { enabled: true, vueDevTools: true },
|
||||
ssr: false,
|
||||
devServer: {
|
||||
// host: '0',
|
||||
modules: [
|
||||
'@nuxt/fonts',
|
||||
'@primevue/nuxt-module',
|
||||
'@formkit/auto-animate/nuxt',
|
||||
],
|
||||
fonts: {
|
||||
provider: 'google',
|
||||
},
|
||||
primevue: {
|
||||
options: {
|
||||
theme: {
|
||||
preset: definePreset(Aura, {
|
||||
semantic: {
|
||||
transitionDuration: '150ms',
|
||||
primary: {
|
||||
50: '{zinc.50}',
|
||||
100: '{zinc.100}',
|
||||
200: '{zinc.200}',
|
||||
300: '{zinc.300}',
|
||||
400: '{zinc.400}',
|
||||
500: '{zinc.500}',
|
||||
600: '{zinc.600}',
|
||||
700: '{zinc.700}',
|
||||
800: '{zinc.800}',
|
||||
900: '{zinc.900}',
|
||||
950: '{zinc.950}',
|
||||
},
|
||||
},
|
||||
colorScheme: {
|
||||
light: {
|
||||
primary: {
|
||||
color: '{zinc.950}',
|
||||
inverseColor: '#ffffff',
|
||||
hoverColor: '{zinc.900}',
|
||||
activeColor: '{zinc.800}',
|
||||
},
|
||||
highlight: {
|
||||
background: '{zinc.950}',
|
||||
focusBackground: '{zinc.700}',
|
||||
color: '#ffffff',
|
||||
focusColor: '#ffffff',
|
||||
},
|
||||
},
|
||||
dark: {
|
||||
primary: {
|
||||
color: '{zinc.50}',
|
||||
inverseColor: '{zinc.950}',
|
||||
hoverColor: '{zinc.100}',
|
||||
activeColor: '{zinc.200}',
|
||||
},
|
||||
highlight: {
|
||||
background: 'rgba(250, 250, 250, .16)',
|
||||
focusBackground: 'rgba(250, 250, 250, .24)',
|
||||
color: 'rgba(255,255,255,.87)',
|
||||
focusColor: 'rgba(255,255,255,.87)',
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
components: {
|
||||
prefix: 'Prime',
|
||||
},
|
||||
},
|
||||
css: [
|
||||
'@/assets/styles/tailwind.css',
|
||||
'@/assets/styles/primeicons.css',
|
||||
'@/assets/styles/main.scss',
|
||||
],
|
||||
vite: {
|
||||
plugins: [
|
||||
tailwindcss(),
|
||||
],
|
||||
clearScreen: false,
|
||||
envPrefix: ['VITE_', 'TAURI_'],
|
||||
server: {
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:4000/chad',
|
||||
// target: 'https://api.koptilnya.xyz/chad',
|
||||
ws: true,
|
||||
changeOrigin: true,
|
||||
rewrite: (path) => {
|
||||
return path.replace(/^\/api/, '')
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
define: {
|
||||
__API_BASE_URL__: JSON.stringify(import.meta.env.API_BASE_URL || '/api'),
|
||||
__COMMIT_SHA__: JSON.stringify(import.meta.env.COMMIT_SHA || 'local'),
|
||||
},
|
||||
},
|
||||
ignore: ['**/src-tauri/**'],
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "nuxt-app",
|
||||
"name": "chad-client",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
@@ -10,19 +10,33 @@
|
||||
"postinstall": "nuxt prepare"
|
||||
},
|
||||
"dependencies": {
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@nuxt/fonts": "^0.11.4",
|
||||
"@primeuix/themes": "^1.2.5",
|
||||
"@tailwindcss/vite": "^4.1.14",
|
||||
"@tauri-apps/plugin-process": "~2",
|
||||
"@tauri-apps/plugin-updater": "~2",
|
||||
"@vueuse/core": "^13.9.0",
|
||||
"mediasoup-client": "^3.16.7",
|
||||
"nuxt": "^4.1.2",
|
||||
"nuxt": "^4.2.2",
|
||||
"postcss": "^8.5.6",
|
||||
"primeicons": "^7.0.0",
|
||||
"primevue": "^4.4.0",
|
||||
"socket.io-client": "^4.8.1",
|
||||
"typescript": "^5.9.3",
|
||||
"tailwindcss": "^4.1.14",
|
||||
"tailwindcss-primeui": "^0.6.1",
|
||||
"ufo": "^1.6.1",
|
||||
"vue": "^3.5.22",
|
||||
"vue-router": "^4.5.1"
|
||||
},
|
||||
"packageManager": "yarn@4.10.3",
|
||||
"packageManager": "yarn@4.12.0",
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^5.4.1",
|
||||
"@primevue/nuxt-module": "^4.4.0",
|
||||
"@tauri-apps/cli": "^2.8.4",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
|
||||
BIN
client/public/chad-bg.webp
Normal file
BIN
client/public/chad-bg.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 71 KiB |
41
client/scripts/generate-updater.mjs
Normal file
41
client/scripts/generate-updater.mjs
Normal file
@@ -0,0 +1,41 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url)
|
||||
const __dirname = path.dirname(__filename)
|
||||
|
||||
const TAURI_CONF = path.resolve(__dirname, '../src-tauri/tauri.conf.json')
|
||||
const OUTPUT = path.resolve(__dirname, '../updater.json')
|
||||
|
||||
const PLATFORM = 'windows-x86_64'
|
||||
const BASE_URL = 'https://git.koptilnya.xyz/opti1337/chad/releases/download/latest'
|
||||
|
||||
const tauriConfRaw = fs.readFileSync(TAURI_CONF, 'utf8')
|
||||
const tauriConf = JSON.parse(tauriConfRaw)
|
||||
const version = tauriConf.version
|
||||
|
||||
const SIG_FILE = path.resolve(
|
||||
__dirname,
|
||||
`../src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/chad_${version}_x64-setup.exe.sig`,
|
||||
)
|
||||
|
||||
const signature = fs.readFileSync(SIG_FILE, 'utf8').trim()
|
||||
|
||||
const installerName = `chad_${version}_x64-setup.exe`
|
||||
|
||||
const updater = {
|
||||
pub_date: new Date().toISOString(),
|
||||
version,
|
||||
platforms: {
|
||||
[PLATFORM]: {
|
||||
url: `${BASE_URL}/${installerName}`,
|
||||
signature,
|
||||
},
|
||||
},
|
||||
notes: '',
|
||||
}
|
||||
|
||||
fs.writeFileSync(OUTPUT, JSON.stringify(updater, null, 2), 'utf8')
|
||||
|
||||
console.log('updater.json generated')
|
||||
4
client/server/plugins/extend-html.ts
Normal file
4
client/server/plugins/extend-html.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export default defineNitroPlugin((nitroApp) => {
|
||||
nitroApp.hooks.hook('render:html', (html, { event }) => {
|
||||
})
|
||||
})
|
||||
61
client/shared/chad-api.ts
Normal file
61
client/shared/chad-api.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { ToastEventBus } from 'primevue'
|
||||
|
||||
const instance = $fetch.create({
|
||||
baseURL: __API_BASE_URL__,
|
||||
credentials: 'include',
|
||||
retry: false,
|
||||
onResponseError({ response }) {
|
||||
if (!import.meta.client)
|
||||
return
|
||||
|
||||
const message = response._data.error || 'Something went wrong'
|
||||
|
||||
ToastEventBus.emit('add', { severity: 'error', summary: 'Error', detail: message, closable: false, life: 3000 })
|
||||
},
|
||||
})
|
||||
|
||||
// function instance(url: string, request: Request) {
|
||||
// console.log(url)
|
||||
// return fetch({
|
||||
// url: `https://api.koptilnya.xyz${url}`,
|
||||
// credentials: 'include',
|
||||
// method: 'GET',
|
||||
// headers: {
|
||||
// 'Accept': 'application/json',
|
||||
// 'Content-Type': 'application/json',
|
||||
// ...request.headers,
|
||||
// },
|
||||
// ...request,
|
||||
// body: request.body ? JSON.stringify(request.body) : undefined,
|
||||
// })
|
||||
// }
|
||||
|
||||
// async function instance(url: string, options: Partial<Request> = {}) {
|
||||
// const response = await fetch(`https://api.koptilnya.xyz/chad${url}`, {
|
||||
// method: options.method || 'GET',
|
||||
// headers: {
|
||||
// 'Content-Type': 'application/json',
|
||||
// ...(options.headers || {}),
|
||||
// },
|
||||
// body: JSON.stringify(options.body ?? {}),
|
||||
// responseType: 2,
|
||||
// credentials: 'include',
|
||||
// })
|
||||
//
|
||||
// const data = await response.json()
|
||||
//
|
||||
// if (response.status >= 400) {
|
||||
// if (!import.meta.client)
|
||||
// return
|
||||
//
|
||||
// const message = data?.error || 'Something went wrong'
|
||||
//
|
||||
// ToastEventBus.emit('add', { severity: 'error', summary: 'Error', detail: message, closable: false, life: 3000 })
|
||||
//
|
||||
// throw new Error(`HTTP ${response.status}: ${data?.message || 'Ошибка'}`)
|
||||
// }
|
||||
//
|
||||
// return data
|
||||
// }
|
||||
|
||||
export default instance
|
||||
10
client/shared/types.ts
Normal file
10
client/shared/types.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
export interface ChadClient {
|
||||
socketId: string
|
||||
userId: string
|
||||
username: string
|
||||
displayName: string
|
||||
inputMuted?: boolean
|
||||
outputMuted?: boolean
|
||||
}
|
||||
|
||||
export type UpdatedClient = Omit<ChadClient, 'socketId' | 'userId' | 'isMe'>
|
||||
846
client/src-tauri/Cargo.lock
generated
846
client/src-tauri/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,8 @@
|
||||
[package]
|
||||
name = "app"
|
||||
version = "0.1.0"
|
||||
description = "A Tauri App"
|
||||
authors = ["you"]
|
||||
description = "WW додепчик"
|
||||
authors = ["KPTL"]
|
||||
license = ""
|
||||
repository = ""
|
||||
edition = "2021"
|
||||
@@ -23,3 +23,8 @@ serde = { version = "1.0", features = ["derive"] }
|
||||
log = "0.4"
|
||||
tauri = { version = "2.8.5", features = [] }
|
||||
tauri-plugin-log = "2"
|
||||
tauri-plugin-process = "2"
|
||||
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||
tauri-plugin-single-instance = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
|
||||
10
client/src-tauri/Info.plist
Normal file
10
client/src-tauri/Info.plist
Normal 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>
|
||||
14
client/src-tauri/capabilities/desktop.json
Normal file
14
client/src-tauri/capabilities/desktop.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"identifier": "desktop-capability",
|
||||
"platforms": [
|
||||
"macOS",
|
||||
"windows",
|
||||
"linux"
|
||||
],
|
||||
"windows": [
|
||||
"main"
|
||||
],
|
||||
"permissions": [
|
||||
"updater:default"
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_process::init())
|
||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||
.plugin(tauri_plugin_single_instance::init(|_, _, _| {
|
||||
}))
|
||||
.setup(|app| {
|
||||
if cfg!(debug_assertions) {
|
||||
app.handle().plugin(
|
||||
|
||||
@@ -1,31 +1,39 @@
|
||||
{
|
||||
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
|
||||
"productName": "chad",
|
||||
"version": "0.1.0",
|
||||
"identifier": "com.tauri.dev",
|
||||
"version": "0.2.7",
|
||||
"identifier": "xyz.koptilnya.chad",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
"frontendDist": "../.output/public",
|
||||
"devUrl": "http://localhost:3000",
|
||||
"beforeDevCommand": "yarn dev",
|
||||
"beforeBuildCommand": "yarn build"
|
||||
"beforeBuildCommand": "yarn generate"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"maximizable": false,
|
||||
"label": "main",
|
||||
"title": "Chad",
|
||||
"width": 800,
|
||||
"height": 600,
|
||||
"resizable": false,
|
||||
"fullscreen": false
|
||||
"fullscreen": false,
|
||||
"center": true,
|
||||
"theme": "Dark",
|
||||
"additionalBrowserArgs": "--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection --autoplay-policy=no-user-gesture-required",
|
||||
"incognito": false
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
"csp": null,
|
||||
"capabilities": []
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"createUpdaterArtifacts": true,
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"targets": ["nsis"],
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
@@ -33,5 +41,13 @@
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
},
|
||||
"plugins": {
|
||||
"updater": {
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEU3MzkxMzM3RkQ3NTg4QUQKUldTdGlIWDlOeE01NStIak9VbmZTTm9HY2NyNUQrVXB5ZEdIN1BkK2lhYW9zWkNCQnZQSjRmelIK",
|
||||
"endpoints": [
|
||||
"https://git.koptilnya.xyz/opti1337/chad/releases/download/latest/updater.json"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
3899
client/yarn.lock
3899
client/yarn.lock
File diff suppressed because it is too large
Load Diff
3
server/.gitignore
vendored
3
server/.gitignore
vendored
@@ -15,3 +15,6 @@ node_modules
|
||||
|
||||
#!.yarn/cache
|
||||
.pnp.*
|
||||
|
||||
.env*
|
||||
*.db
|
||||
|
||||
1
server/.yarnrc.yml
Normal file
1
server/.yarnrc.yml
Normal file
@@ -0,0 +1 @@
|
||||
nodeLinker: node-modules
|
||||
@@ -1,11 +1,17 @@
|
||||
FROM node:22-alpine
|
||||
FROM node:22
|
||||
WORKDIR /app
|
||||
RUN corepack enable
|
||||
COPY package.json yarn.lock ./
|
||||
RUN apk add --no-cache python3
|
||||
RUN yarn install
|
||||
COPY package.json yarn.lock .yarnrc.yml ./
|
||||
RUN apt update && apt install --yes python3 python3-pip build-essential
|
||||
RUN yarn set version latest
|
||||
RUN yarn install --frozen-lockfile
|
||||
COPY . .
|
||||
|
||||
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
|
||||
CMD ["node", "index.mjs"]
|
||||
|
||||
CMD yarn db:deploy && yarn start
|
||||
|
||||
34
server/auth/lucia.ts
Normal file
34
server/auth/lucia.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { PrismaAdapter } from '@lucia-auth/adapter-prisma'
|
||||
import { Lucia } from 'lucia'
|
||||
import prisma from '../prisma/client.ts'
|
||||
|
||||
declare module 'lucia' {
|
||||
interface Register {
|
||||
Lucia: typeof Lucia
|
||||
UserId: string
|
||||
DatabaseUserAttributes: DatabaseUserAttributes
|
||||
}
|
||||
}
|
||||
|
||||
interface DatabaseUserAttributes {
|
||||
id: string
|
||||
displayName: string
|
||||
username: string
|
||||
}
|
||||
|
||||
export const auth = new Lucia(new PrismaAdapter(prisma.session, prisma.user), {
|
||||
sessionCookie: {
|
||||
attributes: {
|
||||
sameSite: 'none',
|
||||
},
|
||||
},
|
||||
getUserAttributes: ({ id, displayName, username }) => {
|
||||
return {
|
||||
id,
|
||||
displayName,
|
||||
username,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
export type Auth = typeof auth
|
||||
10
server/eslint.config.mjs
Normal file
10
server/eslint.config.mjs
Normal file
@@ -0,0 +1,10 @@
|
||||
import antfu from '@antfu/eslint-config'
|
||||
|
||||
export default antfu({
|
||||
typescript: {
|
||||
overrides: {
|
||||
'no-console': 'off',
|
||||
'n/prefer-global/process': 'off',
|
||||
},
|
||||
},
|
||||
})
|
||||
145
server/index.mjs
145
server/index.mjs
@@ -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);
|
||||
@@ -1,13 +1,38 @@
|
||||
{
|
||||
"name": "server",
|
||||
"scripts": {
|
||||
"start": "node index.mjs"
|
||||
"start": "ts-node --transpile-only server.ts",
|
||||
"db:deploy": "npx prisma migrate deploy && npx prisma generate"
|
||||
},
|
||||
"type": "module",
|
||||
"packageManager": "yarn@4.10.3",
|
||||
"dependencies": {
|
||||
"cors": "^2.8.5",
|
||||
"express": "^5.1.0",
|
||||
"@fastify/autoload": "^6.3.1",
|
||||
"@fastify/cookie": "^11.0.2",
|
||||
"@fastify/cors": "^11.1.0",
|
||||
"@lucia-auth/adapter-prisma": "^4.0.1",
|
||||
"@prisma/client": "^6.17.0",
|
||||
"bcrypt": "^6.0.0",
|
||||
"consola": "^3.4.2",
|
||||
"dotenv": "^17.2.3",
|
||||
"fastify": "^5.6.1",
|
||||
"fastify-plugin": "^5.1.0",
|
||||
"lucia": "^3.2.2",
|
||||
"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/ws": "^8",
|
||||
"eslint": "^9.36.0",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.18.0"
|
||||
}
|
||||
}
|
||||
|
||||
45
server/plugins/auth.ts
Normal file
45
server/plugins/auth.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import type { Session, User } from 'lucia'
|
||||
import fp from 'fastify-plugin'
|
||||
import { auth } from '../auth/lucia.ts'
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
user: User | null
|
||||
session: Session | null
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(async (fastify) => {
|
||||
fastify.decorateRequest('user', null)
|
||||
fastify.decorateRequest('session', null)
|
||||
|
||||
fastify.addHook('preHandler', async (req, reply) => {
|
||||
try {
|
||||
const sessionId = auth.readSessionCookie(req.headers.cookie ?? '')
|
||||
|
||||
if (!sessionId)
|
||||
return
|
||||
|
||||
const { session, user } = await auth.validateSession(sessionId ?? '')
|
||||
|
||||
if (session && session.fresh) {
|
||||
const cookie = auth.createSessionCookie(session.id)
|
||||
|
||||
reply.setCookie(cookie.name, cookie.value, cookie.attributes)
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
const blank = auth.createBlankSessionCookie()
|
||||
|
||||
reply.setCookie(blank.name, blank.value, blank.attributes)
|
||||
}
|
||||
|
||||
req.user = user
|
||||
req.session = session
|
||||
}
|
||||
catch {
|
||||
req.user = null
|
||||
req.session = null
|
||||
}
|
||||
})
|
||||
})
|
||||
29
server/plugins/mediasoup-router.ts
Normal file
29
server/plugins/mediasoup-router.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import type * as mediasoup from 'mediasoup'
|
||||
import fp from 'fastify-plugin'
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
mediasoupRouter: mediasoup.types.Router
|
||||
}
|
||||
}
|
||||
|
||||
export default fp<mediasoup.types.RouterOptions>(
|
||||
async (fastify, opts) => {
|
||||
const router = await fastify.mediasoupWorker.createRouter(opts)
|
||||
|
||||
fastify.decorate('mediasoupRouter', router)
|
||||
},
|
||||
{ name: 'mediasoup-router', dependencies: ['mediasoup-worker'] },
|
||||
)
|
||||
|
||||
export const autoConfig: mediasoup.types.RouterOptions = {
|
||||
mediaCodecs: [
|
||||
{
|
||||
kind: 'audio',
|
||||
mimeType: 'audio/opus',
|
||||
clockRate: 48000,
|
||||
channels: 2,
|
||||
parameters: { useinbandfec: 1, stereo: 1 },
|
||||
},
|
||||
],
|
||||
}
|
||||
23
server/plugins/mediasoup-worker.ts
Normal file
23
server/plugins/mediasoup-worker.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { consola } from 'consola'
|
||||
import fp from 'fastify-plugin'
|
||||
import * as mediasoup from 'mediasoup'
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
mediasoupWorker: mediasoup.types.Worker
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(
|
||||
async (fastify) => {
|
||||
const worker = await mediasoup.createWorker()
|
||||
worker.on('died', () => {
|
||||
consola.error('[Mediasoup]', 'Worker died, exiting...')
|
||||
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
fastify.decorate('mediasoupWorker', worker)
|
||||
},
|
||||
{ name: 'mediasoup-worker' },
|
||||
)
|
||||
39
server/plugins/socket.ts
Normal file
39
server/plugins/socket.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import type { ServerOptions } from 'socket.io'
|
||||
import fp from 'fastify-plugin'
|
||||
import { Server } from 'socket.io'
|
||||
import registerWebrtcSocket from '../socket/webrtc.ts'
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
io: Server
|
||||
}
|
||||
}
|
||||
|
||||
export default fp<Partial<ServerOptions>>(
|
||||
async (fastify, opts) => {
|
||||
fastify.decorate('io', new Server(fastify.server, opts))
|
||||
|
||||
fastify.addHook('preClose', () => {
|
||||
fastify.io.disconnectSockets(true)
|
||||
})
|
||||
|
||||
fastify.addHook('onClose', async (fastify: FastifyInstance) => {
|
||||
await fastify.io.close()
|
||||
})
|
||||
|
||||
fastify.ready(() => {
|
||||
registerWebrtcSocket(fastify.io, fastify.mediasoupRouter)
|
||||
})
|
||||
},
|
||||
{ name: 'socket-io', dependencies: ['mediasoup-worker', 'mediasoup-router'] },
|
||||
)
|
||||
|
||||
export const autoConfig: Partial<ServerOptions> = {
|
||||
path: '/chad/ws',
|
||||
cors: {
|
||||
origin: process.env.CORS_ORIGIN || '*',
|
||||
methods: ['GET', 'POST'],
|
||||
credentials: true,
|
||||
},
|
||||
}
|
||||
7
server/prisma/client.ts
Normal file
7
server/prisma/client.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
const client = new PrismaClient({
|
||||
log: ['query', 'error', 'warn'],
|
||||
})
|
||||
|
||||
export default client
|
||||
12
server/prisma/migrations/20251009115816_init/migration.sql
Normal file
12
server/prisma/migrations/20251009115816_init/migration.sql
Normal 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");
|
||||
@@ -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
|
||||
);
|
||||
3
server/prisma/migrations/migration_lock.toml
Normal file
3
server/prisma/migrations/migration_lock.toml
Normal 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"
|
||||
30
server/prisma/schema.prisma
Normal file
30
server/prisma/schema.prisma
Normal file
@@ -0,0 +1,30 @@
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
// output = "./generated/client"
|
||||
}
|
||||
|
||||
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])
|
||||
}
|
||||
118
server/routes/auth.ts
Normal file
118
server/routes/auth.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import bcrypt from 'bcrypt'
|
||||
import { z } from 'zod'
|
||||
import { auth } from '../auth/lucia.ts'
|
||||
import prisma from '../prisma/client.ts'
|
||||
|
||||
export default function (fastify: FastifyInstance) {
|
||||
fastify.post('/register', async (req, reply) => {
|
||||
try {
|
||||
const schema = z.object({
|
||||
username: z.string().min(1),
|
||||
password: z.string().min(6),
|
||||
})
|
||||
const input = schema.parse(req.body)
|
||||
|
||||
const hashed = await bcrypt.hash(input.password, 10)
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
username: input.username,
|
||||
password: hashed,
|
||||
displayName: input.username,
|
||||
},
|
||||
})
|
||||
|
||||
const session = await auth.createSession(user.id, {})
|
||||
const cookie = auth.createSessionCookie(session.id)
|
||||
|
||||
reply.setCookie(cookie.name, cookie.value, cookie.attributes)
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
displayName: user.displayName,
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
fastify.log.error(err)
|
||||
reply.code(400)
|
||||
|
||||
if (err instanceof z.ZodError) {
|
||||
reply.send({ error: z.prettifyError(err) })
|
||||
}
|
||||
else {
|
||||
reply.send({ error: err.message })
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
fastify.post('/login', async (req, reply) => {
|
||||
try {
|
||||
const schema = z.object({
|
||||
username: z.string().min(1),
|
||||
password: z.string(),
|
||||
})
|
||||
const input = schema.parse(req.body)
|
||||
|
||||
const user = await prisma.user.findFirst({
|
||||
where: { username: input.username },
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
return reply.code(404).send({ error: 'Incorrect username or password' })
|
||||
}
|
||||
|
||||
const validPassword = await bcrypt.compare(input.password, user.password)
|
||||
if (!validPassword) {
|
||||
return reply.code(404).send({ error: 'Incorrect username or password' })
|
||||
}
|
||||
|
||||
const session = await auth.createSession(user.id, {})
|
||||
const cookie = auth.createSessionCookie(session.id)
|
||||
|
||||
reply.setCookie(cookie.name, cookie.value, cookie.attributes)
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
displayName: user.displayName,
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
fastify.log.error(err)
|
||||
reply.code(400)
|
||||
|
||||
if (err instanceof z.ZodError) {
|
||||
reply.send({ error: z.prettifyError(err) })
|
||||
}
|
||||
else {
|
||||
reply.send({ error: err.message })
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
fastify.get('/me', async (req, reply) => {
|
||||
if (req.user) {
|
||||
return req.user
|
||||
}
|
||||
|
||||
reply.code(401).send(false)
|
||||
})
|
||||
|
||||
fastify.post('/logout', async (req, reply) => {
|
||||
try {
|
||||
if (req.session)
|
||||
await auth.invalidateSession(req.session.id)
|
||||
|
||||
const blank = auth.createBlankSessionCookie()
|
||||
|
||||
reply.setCookie(blank.name, blank.value, blank.attributes)
|
||||
|
||||
return true
|
||||
}
|
||||
catch (err) {
|
||||
fastify.log.error(err)
|
||||
reply.code(400).send({ error: err.message })
|
||||
}
|
||||
})
|
||||
}
|
||||
48
server/server.ts
Normal file
48
server/server.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import FastifyAutoLoad from '@fastify/autoload'
|
||||
import FastifyCookie from '@fastify/cookie'
|
||||
import FastifyCors from '@fastify/cors'
|
||||
import Fastify from 'fastify'
|
||||
import prisma from './prisma/client.ts'
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url)
|
||||
const __dirname = dirname(__filename)
|
||||
|
||||
const fastify = Fastify({
|
||||
logger: true,
|
||||
})
|
||||
|
||||
fastify.register(FastifyCors, {
|
||||
origin: [
|
||||
'http://localhost:3000',
|
||||
'http://tauri.localhost',
|
||||
],
|
||||
credentials: true,
|
||||
})
|
||||
|
||||
fastify.register(FastifyCookie)
|
||||
|
||||
fastify.register(FastifyAutoLoad, {
|
||||
dir: join(__dirname, 'plugins'),
|
||||
})
|
||||
|
||||
fastify.register(FastifyAutoLoad, {
|
||||
dir: join(__dirname, 'routes'),
|
||||
options: { prefix: 'chad' },
|
||||
})
|
||||
|
||||
;(async () => {
|
||||
const port = process.env.PORT ? Number(process.env.PORT) : 4000
|
||||
|
||||
try {
|
||||
await fastify.listen({ port, host: '0.0.0.0' })
|
||||
|
||||
await prisma.$connect()
|
||||
fastify.log.info('Testing DB Connection. OK')
|
||||
}
|
||||
catch (err) {
|
||||
fastify.log.error(err)
|
||||
process.exit(1)
|
||||
}
|
||||
})()
|
||||
597
server/socket/webrtc.ts
Normal file
597
server/socket/webrtc.ts
Normal file
@@ -0,0 +1,597 @@
|
||||
import type { User } from '@prisma/client'
|
||||
import type { types } from 'mediasoup'
|
||||
import type { Namespace, RemoteSocket, Socket, Server as SocketServer } from 'socket.io'
|
||||
import { consola } from 'consola'
|
||||
import prisma from '../prisma/client.ts'
|
||||
|
||||
interface ChadClient {
|
||||
socketId: string
|
||||
userId: User['id']
|
||||
username: User['username']
|
||||
displayName: User['displayName']
|
||||
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: {
|
||||
rtpCapabilities: types.RtpCapabilities
|
||||
},
|
||||
cb: EventCallback<ChadClient[]>
|
||||
) => 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, 'socketId' | 'userId'>>,
|
||||
cb: EventCallback<ChadClient>
|
||||
) => void
|
||||
}
|
||||
|
||||
interface ServerToClientEvents {
|
||||
authenticated: () => void
|
||||
newPeer: (arg: ChadClient) => void
|
||||
producers: (arg: ProducerShort[]) => void
|
||||
newConsumer: (
|
||||
arg: {
|
||||
socketId: 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['socketId'], client: ChadClient) => void
|
||||
}
|
||||
|
||||
interface InterServerEvent {}
|
||||
|
||||
interface SocketData {
|
||||
joined: boolean
|
||||
userId: User['id']
|
||||
username: User['username']
|
||||
displayName: User['displayName']
|
||||
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>
|
||||
}
|
||||
|
||||
type SomeSocket = Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvent, SocketData> | RemoteSocket<ServerToClientEvents, SocketData>
|
||||
|
||||
export default function (io: SocketServer, router: types.Router) {
|
||||
const namespace: Namespace<ClientToServerEvents, ServerToClientEvents, InterServerEvent, SocketData> = io.of('/webrtc')
|
||||
|
||||
namespace.on('connection', async (socket) => {
|
||||
consola.info('[WebRtc]', 'Client connected', socket.id)
|
||||
|
||||
socket.data.joined = false
|
||||
|
||||
socket.data.inputMuted = false
|
||||
socket.data.outputMuted = false
|
||||
|
||||
socket.data.transports = new Map()
|
||||
socket.data.producers = new Map()
|
||||
socket.data.consumers = new Map()
|
||||
|
||||
const { id, username, displayName } = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: socket.handshake.auth.userId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
displayName: true,
|
||||
},
|
||||
})
|
||||
|
||||
socket.data.userId = id
|
||||
socket.data.username = username
|
||||
socket.data.displayName = displayName
|
||||
|
||||
socket.emit('authenticated')
|
||||
|
||||
socket.on('join', async ({ rtpCapabilities }, cb) => {
|
||||
if (socket.data.joined) {
|
||||
consola.error('[WebRtc]', 'Already joined')
|
||||
cb({ error: 'Already joined' })
|
||||
}
|
||||
|
||||
socket.data.joined = true
|
||||
socket.data.rtpCapabilities = rtpCapabilities
|
||||
|
||||
const joinedSockets = await getJoinedSockets()
|
||||
|
||||
cb(joinedSockets.map(socketToClient))
|
||||
|
||||
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: types.IceState) => {
|
||||
if (iceState === 'disconnected' || iceState === 'closed') {
|
||||
consola.info('[WebRtc]', '[WebRtcTransport]', `"icestatechange" event [iceState:${iceState}], closing peer`, transport.id)
|
||||
|
||||
socket.disconnect()
|
||||
}
|
||||
})
|
||||
|
||||
transport.on('dtlsstatechange', (dtlsState: types.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
|
||||
}
|
||||
|
||||
if (producer.paused)
|
||||
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', async (updatedClient, cb) => {
|
||||
if (updatedClient.displayName) {
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: socket.data.userId,
|
||||
},
|
||||
data: {
|
||||
displayName: updatedClient.displayName,
|
||||
},
|
||||
})
|
||||
|
||||
socket.data.displayName = updatedClient.displayName
|
||||
}
|
||||
|
||||
if (updatedClient.inputMuted) {
|
||||
socket.data.inputMuted = updatedClient.inputMuted
|
||||
}
|
||||
|
||||
if (updatedClient.outputMuted) {
|
||||
socket.data.outputMuted = updatedClient.outputMuted
|
||||
}
|
||||
|
||||
cb(socketToClient(socket))
|
||||
|
||||
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: SomeSocket,
|
||||
producerSocket: SomeSocket,
|
||||
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: types.ConsumerScore) => {
|
||||
consumerSocket.emit('consumerScore', { consumerId: consumer.id, score })
|
||||
})
|
||||
|
||||
try {
|
||||
await consumerSocket.emitWithAck(
|
||||
'newConsumer',
|
||||
{
|
||||
socketId: 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: SomeSocket): ChadClient {
|
||||
return {
|
||||
socketId: socket.id,
|
||||
userId: socket.data.userId,
|
||||
username: socket.data.username,
|
||||
displayName: socket.data.displayName,
|
||||
inputMuted: socket.data.inputMuted,
|
||||
outputMuted: socket.data.outputMuted,
|
||||
}
|
||||
}
|
||||
}
|
||||
12
server/tsconfig.json
Normal file
12
server/tsconfig.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2016",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "nodenext",
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"allowImportingTsExtensions": true
|
||||
}
|
||||
}
|
||||
4812
server/yarn.lock
4812
server/yarn.lock
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user