Compare commits
30 Commits
7cd4ff72d4
...
0.2.4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
@@ -25,7 +25,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Build
|
||||
run: docker build -t chad-client ./client --build-arg COMMIT_SHA=${{ gitea.sha }}
|
||||
run: docker build -t chad-client ./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
|
||||
|
||||
@@ -24,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
|
||||
|
||||
@@ -35,6 +38,7 @@ 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\`)" \
|
||||
|
||||
5
client/.gitignore
vendored
5
client/.gitignore
vendored
@@ -28,4 +28,7 @@ logs
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/sdks
|
||||
!.yarn/versions
|
||||
!.yarn/versions
|
||||
|
||||
scripts/release.ps1
|
||||
.tauri
|
||||
Binary file not shown.
@@ -11,7 +11,10 @@ RUN yarn install
|
||||
COPY . .
|
||||
|
||||
ARG COMMIT_SHA=unknown
|
||||
ENV COMMIT_SHA=$COMMIT_SHA
|
||||
ARG API_BASE_URL
|
||||
|
||||
ENV COMMIT_SHA=$COMMIT_SHA \
|
||||
API_BASE_URL=$API_BASE_URL
|
||||
|
||||
RUN yarn generate
|
||||
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
<template>
|
||||
<NuxtPage />
|
||||
<NuxtLayout>
|
||||
<NuxtPage />
|
||||
</NuxtLayout>
|
||||
|
||||
<PrimeToast position="bottom-center" />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
const { consumers, producers } = useMediasoup()
|
||||
<script setup lang="ts">
|
||||
console.group('Build Info')
|
||||
console.log(`COMMIT_SHA: ${__COMMIT_SHA__}`)
|
||||
console.groupEnd()
|
||||
</script>
|
||||
|
||||
6
client/app/components.d.ts
vendored
6
client/app/components.d.ts
vendored
@@ -11,10 +11,16 @@ declare module 'vue' {
|
||||
PrimeAvatar: typeof import('primevue/avatar')['default']
|
||||
PrimeBadge: typeof import('primevue/badge')['default']
|
||||
PrimeButton: typeof import('primevue/button')['default']
|
||||
PrimeButtonGroup: typeof import('primevue/buttongroup')['default']
|
||||
PrimeCard: typeof import('primevue/card')['default']
|
||||
PrimeFieldset: typeof import('primevue/fieldset')['default']
|
||||
PrimeFloatLabel: typeof import('primevue/floatlabel')['default']
|
||||
PrimeInputText: typeof import('primevue/inputtext')['default']
|
||||
PrimeMenu: typeof import('primevue/menu')['default']
|
||||
PrimePassword: typeof import('primevue/password')['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>
|
||||
@@ -1,31 +1,39 @@
|
||||
<template>
|
||||
<div class="flex items-center gap-3 py-3">
|
||||
<PrimeAvatar icon="pi pi-user" size="small" />
|
||||
<div class="py-3">
|
||||
<div class="flex items-center gap-3 ">
|
||||
<PrimeAvatar
|
||||
icon="pi pi-user"
|
||||
size="small"
|
||||
/>
|
||||
|
||||
<div class="flex-1">
|
||||
<div class="text-sm leading-5 font-medium text-color whitespace-nowrap overflow-ellipsis">
|
||||
{{ client.username }}
|
||||
</div>
|
||||
<div class="mt-1 text-xs leading-5 text-muted-color">
|
||||
{{ client.id }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PrimeBadge severity="secondary" value="Muted" />
|
||||
|
||||
<PrimeButton icon="pi pi-ellipsis-h" text size="small" @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="100" :step="5" />
|
||||
<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="client.inputMuted" 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>
|
||||
</PrimeMenu>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -33,11 +41,16 @@
|
||||
import type { ChadClient } from '#shared/types'
|
||||
import type { MenuItem } from 'primevue/menuitem'
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
client: ChadClient
|
||||
}>()
|
||||
|
||||
const menuRef = useTemplateRef('menu')
|
||||
const { inputMuted, outputMuted } = useApp()
|
||||
const { getClientConsumers } = useMediasoup()
|
||||
const { me } = useClients()
|
||||
|
||||
const menuRef = useTemplateRef<HTMLAudioElement>('menu')
|
||||
|
||||
const volume = ref(100)
|
||||
|
||||
const menuItems: MenuItem[] = [
|
||||
@@ -51,4 +64,31 @@ const menuItems: MenuItem[] = [
|
||||
disabled: true,
|
||||
},
|
||||
]
|
||||
|
||||
const isMe = computed(() => {
|
||||
return me.value && props.client.userId === me.value.userId
|
||||
})
|
||||
|
||||
const audioConsumer = computed(() => {
|
||||
const consumers = getClientConsumers(props.client.id)
|
||||
|
||||
return consumers.find(consumer => consumer.track.kind === 'audio')
|
||||
})
|
||||
|
||||
const audioTrack = computed(() => {
|
||||
return audioConsumer.value?.track
|
||||
})
|
||||
|
||||
const { setGain } = useAudioContext(audioTrack)
|
||||
|
||||
watch(volume, (volume) => {
|
||||
if (outputMuted.value)
|
||||
return
|
||||
|
||||
setGain(volume * 0.01)
|
||||
})
|
||||
|
||||
watch(outputMuted, (outputMuted) => {
|
||||
setGain(outputMuted ? 0 : (volume.value * 0.01))
|
||||
})
|
||||
</script>
|
||||
|
||||
83
client/app/composables/use-app.ts
Normal file
83
client/app/composables/use-app.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { createGlobalState } from '@vueuse/core'
|
||||
import { useClients } from '~/composables/use-clients'
|
||||
|
||||
export const useApp = createGlobalState(() => {
|
||||
const { clients } = useClients()
|
||||
const mediasoup = useMediasoup()
|
||||
const toast = useToast()
|
||||
|
||||
const inputMuted = ref(false)
|
||||
const outputMuted = ref(false)
|
||||
|
||||
const previousInputMuted = ref(inputMuted.value)
|
||||
|
||||
function muteInput() {
|
||||
inputMuted.value = true
|
||||
}
|
||||
|
||||
function unmuteInput() {
|
||||
inputMuted.value = false
|
||||
}
|
||||
|
||||
function toggleInput() {
|
||||
if (inputMuted.value)
|
||||
unmuteInput()
|
||||
else
|
||||
muteInput()
|
||||
}
|
||||
|
||||
function muteOutput() {
|
||||
outputMuted.value = true
|
||||
}
|
||||
|
||||
function unmuteOutput() {
|
||||
outputMuted.value = false
|
||||
}
|
||||
|
||||
function toggleOutput() {
|
||||
if (outputMuted.value)
|
||||
unmuteOutput()
|
||||
else
|
||||
muteOutput()
|
||||
}
|
||||
|
||||
watch(inputMuted, async (inputMuted) => {
|
||||
if (inputMuted) {
|
||||
await mediasoup.muteMic()
|
||||
}
|
||||
else {
|
||||
if (outputMuted.value) {
|
||||
outputMuted.value = false
|
||||
}
|
||||
await mediasoup.unmuteMic()
|
||||
}
|
||||
|
||||
const toastText = inputMuted ? 'Microphone muted' : 'Microphone activated'
|
||||
toast.add({ severity: 'info', summary: toastText, closable: false, life: 1000 })
|
||||
})
|
||||
|
||||
watch(outputMuted, (outputMuted) => {
|
||||
if (outputMuted) {
|
||||
previousInputMuted.value = inputMuted.value
|
||||
muteInput()
|
||||
}
|
||||
else {
|
||||
inputMuted.value = previousInputMuted.value
|
||||
}
|
||||
|
||||
const toastText = outputMuted ? 'Sound muted' : 'Sound resumed'
|
||||
toast.add({ severity: 'info', summary: toastText, closable: false, life: 1000 })
|
||||
})
|
||||
|
||||
return {
|
||||
clients,
|
||||
inputMuted,
|
||||
muteInput,
|
||||
unmuteInput,
|
||||
toggleInput,
|
||||
outputMuted,
|
||||
muteOutput,
|
||||
unmuteOutput,
|
||||
toggleOutput,
|
||||
}
|
||||
})
|
||||
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('/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('/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,30 +0,0 @@
|
||||
import type { ChadClient } from '#shared/types'
|
||||
import { createGlobalState, useLocalStorage } from '@vueuse/core'
|
||||
|
||||
export const useGlobalState = createGlobalState(() => {
|
||||
const username = useLocalStorage<string>('username', '')
|
||||
|
||||
const clients = ref<ChadClient[]>([])
|
||||
|
||||
const me = computed(() => clients.value.find(client => client.isMe))
|
||||
|
||||
const clientByIdMap = computed(() => {
|
||||
return clients.value.reduce<Record<ChadClient['id'], ChadClient>>((result, client) => {
|
||||
result[client.id] = client
|
||||
|
||||
return result
|
||||
}, {})
|
||||
})
|
||||
|
||||
function reset() {
|
||||
clients.value = []
|
||||
}
|
||||
|
||||
return {
|
||||
username,
|
||||
me,
|
||||
clients,
|
||||
clientByIdMap,
|
||||
reset,
|
||||
}
|
||||
})
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { ChadClient, RemoteClient } from '#shared/types'
|
||||
import type { Socket } from 'socket.io-client'
|
||||
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'
|
||||
|
||||
const ICE_SERVERS: RTCIceServer[] = [
|
||||
{ urls: 'stun:stun.l.google.com:19302' },
|
||||
@@ -18,9 +18,12 @@ const ICE_SERVERS: RTCIceServer[] = [
|
||||
]
|
||||
|
||||
export const useMediasoup = createSharedComposable(() => {
|
||||
const state = useGlobalState()
|
||||
const toast = useToast()
|
||||
|
||||
const socket = shallowRef<Socket>()
|
||||
const signaling = useSignaling()
|
||||
const { addClient, removeClient } = useClients()
|
||||
const preferences = usePreferences()
|
||||
const { me } = useAuth()
|
||||
|
||||
const device = shallowRef<mediasoupClient.Device>()
|
||||
const rtpCapabilities = shallowRef<mediasoupClient.types.RtpCapabilities>()
|
||||
@@ -34,44 +37,115 @@ export const useMediasoup = createSharedComposable(() => {
|
||||
const consumers = shallowRef<Map<string, mediasoupClient.types.Consumer>>(new Map())
|
||||
const producers = shallowRef<Map<string, mediasoupClient.types.Producer>>(new Map())
|
||||
|
||||
watch(socket, (socket, prevSocket) => {
|
||||
if (prevSocket) {
|
||||
prevSocket.close()
|
||||
|
||||
dispose()
|
||||
}
|
||||
|
||||
if (!socket) {
|
||||
watch(signaling.socket, (socket) => {
|
||||
if (!socket)
|
||||
return
|
||||
}
|
||||
|
||||
socket.onAny((event, ...args) => {
|
||||
console.log('[onAny]', event, args)
|
||||
})
|
||||
socket.on('authenticated', async () => {
|
||||
if (!signaling.socket.value)
|
||||
return
|
||||
|
||||
socket.onAnyOutgoing((event, ...args) => {
|
||||
console.log('[onAnyOutgoing]', event, args)
|
||||
})
|
||||
device.value = new mediasoupClient.Device()
|
||||
rtpCapabilities.value = await signaling.socket.value.emitWithAck('getRtpCapabilities')
|
||||
|
||||
socket.on('connect', async () => {
|
||||
if (!state.username.value)
|
||||
state.username.value = socket.id!
|
||||
await device.value.load({ routerRtpCapabilities: rtpCapabilities.value! })
|
||||
|
||||
await join()
|
||||
// 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 ?? []),
|
||||
],
|
||||
})
|
||||
|
||||
sendTransport.value.on('connect', async ({ dtlsParameters }, callback, errback) => {
|
||||
try {
|
||||
await signaling.socket.value!.emitWithAck('connectTransport', {
|
||||
transportId: sendTransport.value!.id,
|
||||
dtlsParameters,
|
||||
})
|
||||
|
||||
callback()
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof Error) {
|
||||
errback(error)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
sendTransport.value.on('produce', async ({ kind, rtpParameters, appData }, callback, errback) => {
|
||||
try {
|
||||
const { id } = await signaling.socket.value!.emitWithAck('produce', {
|
||||
transportId: sendTransport.value!.id,
|
||||
kind,
|
||||
rtpParameters,
|
||||
appData,
|
||||
})
|
||||
callback({ id })
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof Error) {
|
||||
errback(error)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 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 ?? []),
|
||||
],
|
||||
})
|
||||
|
||||
recvTransport.value.on('connect', async ({ dtlsParameters }, callback, errback) => {
|
||||
try {
|
||||
await signaling.socket.value!.emitWithAck('connectTransport', {
|
||||
transportId: recvTransport.value!.id,
|
||||
dtlsParameters,
|
||||
})
|
||||
|
||||
callback()
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof Error) {
|
||||
errback(error)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
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) => {
|
||||
state.clients.value.push(transformClient(client))
|
||||
addClient(client)
|
||||
})
|
||||
|
||||
socket.on('peerClosed', (id) => {
|
||||
state.clients.value = state.clients.value.filter(client => client.id !== id)
|
||||
removeClient(id)
|
||||
})
|
||||
|
||||
socket.on(
|
||||
'newConsumer',
|
||||
async (
|
||||
{ id, producerId, kind, rtpParameters, peerId, appData, producerPaused },
|
||||
{ id, producerId, kind, rtpParameters, peerId: clientId, appData },
|
||||
cb,
|
||||
) => {
|
||||
if (!recvTransport.value)
|
||||
@@ -82,30 +156,18 @@ export const useMediasoup = createSharedComposable(() => {
|
||||
producerId,
|
||||
kind,
|
||||
rtpParameters,
|
||||
streamId: `${peerId}-${appData.share ? 'share' : 'mic-webcam'}`,
|
||||
appData: { ...appData, peerId },
|
||||
streamId: `${clientId}-${appData.share ? 'share' : 'mic-webcam'}`,
|
||||
appData: { ...appData, clientId },
|
||||
})
|
||||
|
||||
consumer.on('transportclose', () => {
|
||||
console.log('consumer on transportclose')
|
||||
consumers.value.delete(consumer.id)
|
||||
triggerRef(consumers)
|
||||
|
||||
const client = state.clientByIdMap.value[peerId as string]
|
||||
|
||||
if (!client)
|
||||
return
|
||||
|
||||
client.consumerIds = client.consumerIds.filter(id => id !== consumer.id)
|
||||
})
|
||||
|
||||
consumers.value.set(consumer.id, consumer)
|
||||
triggerRef(consumers)
|
||||
|
||||
console.log(consumer)
|
||||
|
||||
state.clientByIdMap.value[peerId]!.consumerIds.push(consumer.id)
|
||||
|
||||
cb()
|
||||
},
|
||||
)
|
||||
@@ -115,8 +177,6 @@ export const useMediasoup = createSharedComposable(() => {
|
||||
async (
|
||||
{ consumerId },
|
||||
) => {
|
||||
console.log('socket on consumerClosed')
|
||||
|
||||
const consumer = consumers.value.get(consumerId)
|
||||
|
||||
if (!consumer)
|
||||
@@ -124,116 +184,30 @@ export const useMediasoup = createSharedComposable(() => {
|
||||
|
||||
consumers.value.delete(consumer.id)
|
||||
triggerRef(consumers)
|
||||
|
||||
const client = state.clientByIdMap.value[(consumer.appData.peerId || consumer.appData.socketId) as string]
|
||||
|
||||
if (!client)
|
||||
return
|
||||
|
||||
client.consumerIds = client.consumerIds.filter(id => id !== consumer.id)
|
||||
},
|
||||
)
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
device.value = undefined
|
||||
rtpCapabilities.value = undefined
|
||||
|
||||
sendTransport.value?.close()
|
||||
sendTransport.value = undefined
|
||||
|
||||
recvTransport.value?.close()
|
||||
recvTransport.value = undefined
|
||||
|
||||
micProducer.value = undefined
|
||||
webcamProducer.value = undefined
|
||||
shareProducer.value = undefined
|
||||
|
||||
consumers.value = new Map()
|
||||
producers.value = new Map()
|
||||
})
|
||||
}, { immediate: true, flush: 'sync' })
|
||||
|
||||
onScopeDispose(() => {
|
||||
socket.value?.close()
|
||||
})
|
||||
|
||||
async function join() {
|
||||
if (!socket.value)
|
||||
return
|
||||
|
||||
device.value = new mediasoupClient.Device()
|
||||
rtpCapabilities.value = await socket.value.emitWithAck('getRtpCapabilities')
|
||||
|
||||
await device.value.load({ routerRtpCapabilities: rtpCapabilities.value! })
|
||||
|
||||
// Send transport
|
||||
{
|
||||
const transportInfo = await socket.value.emitWithAck('createTransport', { producing: true, consuming: false })
|
||||
sendTransport.value = device.value.createSendTransport({
|
||||
...transportInfo,
|
||||
iceServers: [
|
||||
...ICE_SERVERS,
|
||||
...(transportInfo.iceServers ?? []),
|
||||
],
|
||||
})
|
||||
|
||||
sendTransport.value.on('connect', async ({ dtlsParameters }, callback, errback) => {
|
||||
try {
|
||||
await socket.value!.emitWithAck('connectTransport', {
|
||||
transportId: sendTransport.value!.id,
|
||||
dtlsParameters,
|
||||
})
|
||||
|
||||
callback()
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof Error) {
|
||||
errback(error)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
sendTransport.value.on('produce', async ({ kind, rtpParameters, appData }, callback, errback) => {
|
||||
try {
|
||||
const { id } = await socket.value!.emitWithAck('produce', {
|
||||
transportId: sendTransport.value!.id,
|
||||
kind,
|
||||
rtpParameters,
|
||||
appData,
|
||||
})
|
||||
callback({ id })
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof Error) {
|
||||
errback(error)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Recv Transport
|
||||
{
|
||||
const transportInfo = await socket.value.emitWithAck('createTransport', { producing: false, consuming: true })
|
||||
recvTransport.value = device.value.createRecvTransport({
|
||||
...transportInfo,
|
||||
iceServers: [
|
||||
...ICE_SERVERS,
|
||||
...(transportInfo.iceServers ?? []),
|
||||
],
|
||||
})
|
||||
|
||||
recvTransport.value.on('connect', async ({ dtlsParameters }, callback, errback) => {
|
||||
try {
|
||||
await socket.value!.emitWithAck('connectTransport', {
|
||||
transportId: recvTransport.value!.id,
|
||||
dtlsParameters,
|
||||
})
|
||||
|
||||
callback()
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof Error) {
|
||||
errback(error)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const result = await socket.value.emitWithAck('join', { username: state.username.value, rtpCapabilities: rtpCapabilities.value })
|
||||
|
||||
state.clients.value = (result as RemoteClient[]).map(transformClient)
|
||||
|
||||
await enableMic()
|
||||
function getClientConsumers(clientId: ChadClient['socketId']) {
|
||||
return consumers.value.values().filter(consumer => consumer.appData.clientId === clientId)
|
||||
}
|
||||
|
||||
async function enableMic() {
|
||||
@@ -281,7 +255,7 @@ export const useMediasoup = createSharedComposable(() => {
|
||||
}
|
||||
|
||||
async function disableMic() {
|
||||
if (!micProducer.value)
|
||||
if (!signaling.socket.value || !micProducer.value)
|
||||
return
|
||||
|
||||
producers.value.delete(micProducer.value.id)
|
||||
@@ -290,7 +264,7 @@ export const useMediasoup = createSharedComposable(() => {
|
||||
try {
|
||||
micProducer.value.close()
|
||||
|
||||
await socket.value?.emitWithAck('closeProducer', {
|
||||
await signaling.socket.value.emitWithAck('closeProducer', {
|
||||
producerId: micProducer.value.id,
|
||||
})
|
||||
}
|
||||
@@ -301,13 +275,13 @@ export const useMediasoup = createSharedComposable(() => {
|
||||
}
|
||||
|
||||
async function muteMic() {
|
||||
if (!micProducer.value)
|
||||
if (!signaling.socket.value || !micProducer.value)
|
||||
return
|
||||
|
||||
try {
|
||||
micProducer.value.pause()
|
||||
|
||||
await socket.value?.emitWithAck('pauseProducer', {
|
||||
await signaling.socket.value.emitWithAck('pauseProducer', {
|
||||
producerId: micProducer.value.id,
|
||||
})
|
||||
}
|
||||
@@ -316,13 +290,13 @@ export const useMediasoup = createSharedComposable(() => {
|
||||
}
|
||||
|
||||
async function unmuteMic() {
|
||||
if (!micProducer.value)
|
||||
if (!signaling.socket.value || !micProducer.value)
|
||||
return
|
||||
|
||||
try {
|
||||
micProducer.value?.resume()
|
||||
micProducer.value.resume()
|
||||
|
||||
await socket.value?.emitWithAck('resumeProducer', {
|
||||
await signaling.socket.value.emitWithAck('resumeProducer', {
|
||||
producerId: micProducer.value.id,
|
||||
})
|
||||
}
|
||||
@@ -330,38 +304,8 @@ export const useMediasoup = createSharedComposable(() => {
|
||||
}
|
||||
}
|
||||
|
||||
function transformClient(client: RemoteClient): ChadClient {
|
||||
return {
|
||||
...client,
|
||||
isMe: client.id === socket.value!.id,
|
||||
consumerIds: [],
|
||||
}
|
||||
}
|
||||
|
||||
function init() {
|
||||
if (socket.value)
|
||||
return
|
||||
|
||||
socket.value = io('https://api.koptilnya.xyz/webrtc', {
|
||||
path: '/chad/ws',
|
||||
transports: ['websocket'],
|
||||
})
|
||||
}
|
||||
|
||||
function dispose() {
|
||||
device.value = undefined
|
||||
rtpCapabilities.value = undefined
|
||||
sendTransport.value = undefined
|
||||
recvTransport.value = undefined
|
||||
|
||||
micProducer.value = undefined
|
||||
webcamProducer.value = undefined
|
||||
shareProducer.value = undefined
|
||||
|
||||
consumers.value = new Map()
|
||||
producers.value = new Map()
|
||||
|
||||
state.reset()
|
||||
async function init() {
|
||||
signaling.connect()
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -370,11 +314,13 @@ export const useMediasoup = createSharedComposable(() => {
|
||||
producers,
|
||||
sendTransport,
|
||||
recvTransport,
|
||||
socket,
|
||||
rtpCapabilities,
|
||||
device,
|
||||
micProducer,
|
||||
webcamProducer,
|
||||
shareProducer,
|
||||
getClientConsumers,
|
||||
muteMic,
|
||||
unmuteMic,
|
||||
}
|
||||
})
|
||||
|
||||
11
client/app/composables/use-preferences.ts
Normal file
11
client/app/composables/use-preferences.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { createGlobalState } from '@vueuse/core'
|
||||
|
||||
export const usePreferences = createGlobalState(() => {
|
||||
const audioDevice = shallowRef()
|
||||
const videoDevice = shallowRef()
|
||||
|
||||
return {
|
||||
audioDevice,
|
||||
videoDevice,
|
||||
}
|
||||
})
|
||||
80
client/app/composables/use-signaling.ts
Normal file
80
client/app/composables/use-signaling.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import type { Socket } from 'socket.io-client'
|
||||
import { createSharedComposable } from '@vueuse/core'
|
||||
import { io } from 'socket.io-client'
|
||||
|
||||
export const useSignaling = createSharedComposable(() => {
|
||||
const toast = useToast()
|
||||
const { 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)
|
||||
return
|
||||
|
||||
socket.value = io('https://api.koptilnya.xyz/webrtc', {
|
||||
// socket.value = io('http://localhost:4000/webrtc', {
|
||||
path: '/chad/ws',
|
||||
transports: ['websocket'],
|
||||
withCredentials: true,
|
||||
auth: {
|
||||
userId: me.value!.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
socket,
|
||||
connected,
|
||||
connect,
|
||||
}
|
||||
})
|
||||
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 {}
|
||||
40
client/app/layouts/auth.vue
Normal file
40
client/app/layouts/auth.vue
Normal file
@@ -0,0 +1,40 @@
|
||||
<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>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const route = useRoute()
|
||||
|
||||
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>
|
||||
47
client/app/layouts/default.vue
Normal file
47
client/app/layouts/default.vue
Normal file
@@ -0,0 +1,47 @@
|
||||
<template>
|
||||
<div v-auto-animate class="grid grid-cols-2 h-screen">
|
||||
<div class="flex flex-col shadow-xl shadow-surface-950 overflow-y-hidden">
|
||||
<AppHeader title="Шальные сиськи 18+">
|
||||
<template #right>
|
||||
<PrimeButtonGroup class="ml-auto">
|
||||
<PrimeButton
|
||||
icon="pi pi-microphone" size="large" :severity="inputMuted ? 'contrast' : 'secondary'"
|
||||
:outlined="!inputMuted" @click="toggleInput"
|
||||
/>
|
||||
<PrimeButton
|
||||
icon="pi pi-headphones" size="large" :severity="outputMuted ? 'contrast' : 'secondary'"
|
||||
:outlined="!outputMuted" @click="toggleOutput"
|
||||
/>
|
||||
</PrimeButtonGroup>
|
||||
|
||||
<PrimeButton icon="pi pi-cog" size="large" :text="!inPreferences" :severity="inPreferences ? 'contrast' : 'secondary'" @click="onClickPreferences" />
|
||||
</template>
|
||||
</AppHeader>
|
||||
|
||||
<div v-auto-animate class="p-3 overflow-y-auto flex-1 bg-surface-900 overflow-hidden divide-y divide-surface-800">
|
||||
<ClientRow v-for="client of clients" :key="client.id" :client="client" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<slot />
|
||||
</div>
|
||||
|
||||
<PrimeBadge class="fixed top-3 right-3" severity="success" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const { clients, inputMuted, toggleInput, outputMuted, toggleOutput } = useApp()
|
||||
const { connect } = useSignaling()
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
const inPreferences = computed(() => {
|
||||
return route.name === 'Preferences'
|
||||
})
|
||||
|
||||
function onClickPreferences() {
|
||||
navigateTo(!inPreferences.value ? { name: 'Preferences' } : '/')
|
||||
}
|
||||
|
||||
connect()
|
||||
</script>
|
||||
3
client/app/layouts/updater.vue
Normal file
3
client/app/layouts/updater.vue
Normal file
@@ -0,0 +1,3 @@
|
||||
<template>
|
||||
UPDATER
|
||||
</template>
|
||||
41
client/app/middleware/00.updater.global.ts
Normal file
41
client/app/middleware/00.updater.global.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { relaunch } from '@tauri-apps/plugin-process'
|
||||
import { check } from '@tauri-apps/plugin-updater'
|
||||
|
||||
export default defineNuxtRouteMiddleware(async (to, from) => {
|
||||
if (from?.name)
|
||||
return
|
||||
|
||||
const update = await check()
|
||||
|
||||
console.log(update)
|
||||
|
||||
if (import.meta.dev)
|
||||
return
|
||||
|
||||
if (update) {
|
||||
console.log(
|
||||
`found update ${update.version} from ${update.date} with notes ${update.body}`,
|
||||
)
|
||||
let downloaded = 0
|
||||
let contentLength = 0
|
||||
// alternatively we could also call update.download() and update.install() separately
|
||||
await update.downloadAndInstall((event) => {
|
||||
switch (event.event) {
|
||||
case 'Started':
|
||||
contentLength = event.data.contentLength ?? 0
|
||||
console.log(`started downloading ${event.data.contentLength} bytes`)
|
||||
break
|
||||
case 'Progress':
|
||||
downloaded += event.data.chunkLength
|
||||
console.log(`downloaded ${downloaded} from ${contentLength}`)
|
||||
break
|
||||
case 'Finished':
|
||||
console.log('download finished')
|
||||
break
|
||||
}
|
||||
})
|
||||
|
||||
console.log('update installed')
|
||||
await relaunch()
|
||||
}
|
||||
})
|
||||
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('/')
|
||||
}
|
||||
})
|
||||
@@ -1,5 +0,0 @@
|
||||
export default defineNuxtRouteMiddleware((to, from) => {
|
||||
console.group('Build Info')
|
||||
console.log(`COMMIT_SHA: ${__COMMIT_SHA__}`)
|
||||
console.groupEnd()
|
||||
})
|
||||
@@ -1,19 +0,0 @@
|
||||
export default defineNuxtRouteMiddleware((to, from) => {
|
||||
const { username } = useGlobalState()
|
||||
|
||||
if (!username.value && to.name !== 'Login') {
|
||||
console.log('yes')
|
||||
return navigateTo({ name: 'Login' })
|
||||
}
|
||||
|
||||
if (!username.value)
|
||||
return
|
||||
|
||||
const { init } = useMediasoup()
|
||||
|
||||
init()
|
||||
|
||||
if (to.name === 'Login') {
|
||||
return navigateTo('/')
|
||||
}
|
||||
})
|
||||
@@ -1,56 +1,11 @@
|
||||
<template>
|
||||
<div class="grid grid-cols-2 h-screen">
|
||||
<div class="flex flex-col shadow-xl overflow-y-hidden">
|
||||
<div class="flex items-center bg-surface-950 border-b-2 border-surface-800 px-3 py-3">
|
||||
<h1>
|
||||
Шальные сиськи 18+
|
||||
</h1>
|
||||
|
||||
<div class="inline-flex gap-2 ml-auto">
|
||||
<PrimeButton icon="pi pi-headphones" text size="large" />
|
||||
<PrimeButton icon="pi pi-microphone" text size="large" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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="flex items-center justify-center p-3">
|
||||
<PrimeFieldset legend="Important information">
|
||||
The chat is under development.
|
||||
</PrimeFieldset>
|
||||
</div>
|
||||
|
||||
<audio v-for="client in clients" :key="client.id" :ref="(el) => onAudioRef(el, client)" autoplay controls />
|
||||
|
||||
<PrimeBadge class="fixed top-3 right-3" severity="success" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { ChadClient } from '#shared/types'
|
||||
import { vAutoAnimate } from '@formkit/auto-animate'
|
||||
|
||||
const { clients } = useGlobalState()
|
||||
const { consumers } = useMediasoup()
|
||||
|
||||
function onAudioRef(ref: HTMLAudioElement, client: ChadClient) {
|
||||
if (!ref || !client)
|
||||
return
|
||||
|
||||
if (client.isMe)
|
||||
return
|
||||
|
||||
const consumersArray = client.consumerIds.map(id => consumers.value.get(id)!)
|
||||
|
||||
const audioConsumer = consumersArray.find(
|
||||
consumer => consumer.track.kind === 'audio',
|
||||
)
|
||||
|
||||
if (!audioConsumer)
|
||||
return
|
||||
|
||||
const stream = new MediaStream()
|
||||
|
||||
stream.addTrack(audioConsumer!.track)
|
||||
|
||||
ref.srcObject = stream
|
||||
ref.setAttribute('data-consumer-id', audioConsumer.id)
|
||||
}
|
||||
const { clients, inputMuted, toggleInput, outputMuted, toggleOutput } = useApp()
|
||||
</script>
|
||||
|
||||
@@ -1,30 +1,67 @@
|
||||
<template>
|
||||
<div class="w-full h-full flex justify-center items-center">
|
||||
<PrimeCard class="w-2/5">
|
||||
<template #content>
|
||||
<form class="flex flex-col gap-3" @submit.prevent="submit">
|
||||
<PrimeInputText v-model="username" type="text" placeholder="Username" />
|
||||
<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>
|
||||
|
||||
<PrimeButton size="large" icon="pi pi-arrow-right" icon-pos="right" label="Let's go" :disabled="!username" type="submit" />
|
||||
</form>
|
||||
</template>
|
||||
</PrimeCard>
|
||||
</div>
|
||||
<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: 'login',
|
||||
layout: 'auth',
|
||||
auth: 'guest',
|
||||
})
|
||||
|
||||
const { username } = useGlobalState()
|
||||
const { init } = useMediasoup()
|
||||
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 (!username.value)
|
||||
if (!valid.value)
|
||||
return
|
||||
|
||||
await navigateTo('/')
|
||||
submitting.value = true
|
||||
|
||||
await login(username.value!, password.value!)
|
||||
|
||||
submitting.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
54
client/app/pages/preferences.vue
Normal file
54
client/app/pages/preferences.vue
Normal file
@@ -0,0 +1,54 @@
|
||||
<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 class="p-3">
|
||||
<PrimeButton label="Logout" fluid severity="danger" @click="logout" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
definePageMeta({
|
||||
name: 'Preferences',
|
||||
})
|
||||
|
||||
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 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>
|
||||
11
client/latest.json
Normal file
11
client/latest.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"pub_date": "2025-10-19T18:09:51Z",
|
||||
"version": "0.2.1",
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"url": "https://git.koptilnya.xyz/opti1337/chad/releases/download/latest/chad_0.2.1_x64-setup.exe",
|
||||
"signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUMHdwTUN1SnhESjBiY2xtakN0WW1LTHNyQ1RyQjd2YlVXRUozWHp0K003SlFYbmlreHY2UjF5RjAvdEhZKzBpL0J6NVJ1c09VaUVUa3ZCZmFUL1AxN2lCNW9pVW9MY0FvPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzYwODk3MzkwCWZpbGU6Y2hhZF8wLjIuMV94NjQtc2V0dXAuZXhlCmtqcDJtSVQ0d1ZVdXpoYWxnMXVxQVlwLzM5V3BjM2Q4RGQzRXZBUlRFQzhnaDdqdjNTK0h0RW1zcjR5UFE2ZWx2dVppbWpjMlBYdG1ZUGM3NXVqT0F3PT0K"
|
||||
}
|
||||
},
|
||||
"notes": ""
|
||||
}
|
||||
@@ -3,11 +3,12 @@ import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
export default defineNuxtConfig({
|
||||
compatibilityDate: '2025-09-29',
|
||||
devtools: { enabled: true },
|
||||
devtools: { enabled: true, vueDevTools: true },
|
||||
ssr: false,
|
||||
modules: [
|
||||
'@nuxt/fonts',
|
||||
'@primevue/nuxt-module',
|
||||
'@formkit/auto-animate/nuxt',
|
||||
],
|
||||
primevue: {
|
||||
options: {
|
||||
@@ -35,9 +36,17 @@ export default defineNuxtConfig({
|
||||
envPrefix: ['VITE_', 'TAURI_'],
|
||||
server: {
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
'/api': {
|
||||
// target: 'http://localhost:4000',
|
||||
target: 'https://api.koptilnya.xyz',
|
||||
changeOrigin: true,
|
||||
rewrite: path => path.replace(/^\/api/, '/chad'),
|
||||
},
|
||||
},
|
||||
},
|
||||
define: {
|
||||
__COMMIT_SHA__: JSON.stringify(process.env.COMMIT_SHA || 'local'),
|
||||
__COMMIT_SHA__: JSON.stringify(import.meta.env.COMMIT_SHA || 'local'),
|
||||
},
|
||||
},
|
||||
ignore: ['**/src-tauri/**'],
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
"@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",
|
||||
|
||||
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 |
16
client/shared/chad-api.ts
Normal file
16
client/shared/chad-api.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { ToastEventBus } from 'primevue'
|
||||
|
||||
const instance = $fetch.create({
|
||||
baseURL: process.env.API_BASE_URL || 'https://api.koptilnya.xyz/chad',
|
||||
credentials: 'include',
|
||||
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 })
|
||||
},
|
||||
})
|
||||
|
||||
export default instance
|
||||
@@ -1,11 +1,10 @@
|
||||
import type * as mediasoupClient from 'mediasoup-client'
|
||||
|
||||
export interface RemoteClient {
|
||||
id: string
|
||||
export interface ChadClient {
|
||||
socketId: string
|
||||
userId: string
|
||||
username: string
|
||||
displayName: string
|
||||
inputMuted?: boolean
|
||||
outputMuted?: boolean
|
||||
}
|
||||
|
||||
export interface ChadClient extends RemoteClient {
|
||||
isMe?: boolean
|
||||
consumerIds: mediasoupClient.types.Consumer['id'][]
|
||||
}
|
||||
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>
|
||||
@@ -1,3 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
tauri_build::build()
|
||||
}
|
||||
|
||||
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,16 +1,23 @@
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.setup(|app| {
|
||||
if cfg!(debug_assertions) {
|
||||
app.handle().plugin(
|
||||
tauri_plugin_log::Builder::default()
|
||||
.level(log::LevelFilter::Info)
|
||||
.build(),
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_process::init())
|
||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||
// .plugin(tauri_plugin_single_instance::init(|app, args, cwd| {
|
||||
// app.get_webview_window("main")
|
||||
// .expect("no main window")
|
||||
// .set_focus();
|
||||
// }))
|
||||
.setup(|app| {
|
||||
if cfg!(debug_assertions) {
|
||||
app.handle().plugin(
|
||||
tauri_plugin_log::Builder::default()
|
||||
.level(log::LevelFilter::Info)
|
||||
.build(),
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
app_lib::run();
|
||||
app_lib::run();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
|
||||
"productName": "chad",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.2",
|
||||
"identifier": "xyz.koptilnya.chad",
|
||||
"build": {
|
||||
"frontendDist": "../.output/public",
|
||||
@@ -12,20 +12,27 @@
|
||||
"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"
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
"csp": null,
|
||||
"capabilities": []
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"createUpdaterArtifacts": true,
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"targets": ["nsis"],
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
@@ -33,5 +40,13 @@
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
},
|
||||
"plugins": {
|
||||
"updater": {
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDI3NDM5Q0I4MDI5M0MyRjQKUldUMHdwTUN1SnhESjBoUFpuWkJxRzFqcWJxdTY4UkNvMmUzcHFnZnJtbSs3WmJoUmhxQ3R5bWYK",
|
||||
"endpoints": [
|
||||
"https://git.koptilnya.xyz/opti1337/chad/releases/download/latest/latest.json"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2537,6 +2537,13 @@ __metadata:
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"@tauri-apps/api@npm:^2.6.0":
|
||||
version: 2.8.0
|
||||
resolution: "@tauri-apps/api@npm:2.8.0"
|
||||
checksum: 10c0/fb111e4d7572372997b440ebe6879543fa8c4765151878e3fddfbfe809b18da29eed142ce83061d14a9ca6d896b3266dc8a4927c642d71cdc0b4277dc7e3aabf
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"@tauri-apps/cli-darwin-arm64@npm:2.8.4":
|
||||
version: 2.8.4
|
||||
resolution: "@tauri-apps/cli-darwin-arm64@npm:2.8.4"
|
||||
@@ -2658,6 +2665,24 @@ __metadata:
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"@tauri-apps/plugin-process@npm:~2":
|
||||
version: 2.3.0
|
||||
resolution: "@tauri-apps/plugin-process@npm:2.3.0"
|
||||
dependencies:
|
||||
"@tauri-apps/api": "npm:^2.6.0"
|
||||
checksum: 10c0/ef50344a7436d92278c2ef4526f72daaf3171c4d65743bbc1f7a00fa581644a8583bb8680f637a34af5c7e6a0e8722c22189290e903584fef70ed83b64b6e9c0
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"@tauri-apps/plugin-updater@npm:~2":
|
||||
version: 2.9.0
|
||||
resolution: "@tauri-apps/plugin-updater@npm:2.9.0"
|
||||
dependencies:
|
||||
"@tauri-apps/api": "npm:^2.6.0"
|
||||
checksum: 10c0/72ce83d1c241308a13b9929f0900e4d33453875877009166e3998e3e75a1003ac48c3641086b4d3230f0f18c64f475ad6c3556d1603fc641ca50dc9c18d61866
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"@tybys/wasm-util@npm:^0.10.1":
|
||||
version: 0.10.1
|
||||
resolution: "@tybys/wasm-util@npm:0.10.1"
|
||||
@@ -3730,6 +3755,8 @@ __metadata:
|
||||
"@primevue/nuxt-module": "npm:^4.4.0"
|
||||
"@tailwindcss/vite": "npm:^4.1.14"
|
||||
"@tauri-apps/cli": "npm:^2.8.4"
|
||||
"@tauri-apps/plugin-process": "npm:~2"
|
||||
"@tauri-apps/plugin-updater": "npm:~2"
|
||||
"@vueuse/core": "npm:^13.9.0"
|
||||
eslint: "npm:^9.36.0"
|
||||
eslint-plugin-format: "npm:^1.0.2"
|
||||
|
||||
3
server/.gitignore
vendored
3
server/.gitignore
vendored
@@ -15,3 +15,6 @@ node_modules
|
||||
|
||||
#!.yarn/cache
|
||||
.pnp.*
|
||||
|
||||
.env*
|
||||
*.db
|
||||
|
||||
@@ -10,7 +10,8 @@ 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 ["yarn", "start"]
|
||||
CMD yarn db:deploy && yarn start
|
||||
|
||||
29
server/auth/lucia.ts
Normal file
29
server/auth/lucia.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
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), {
|
||||
getUserAttributes: ({ id, displayName, username }) => {
|
||||
return {
|
||||
id,
|
||||
displayName,
|
||||
username,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
export type Auth = typeof auth
|
||||
@@ -1,47 +0,0 @@
|
||||
import { createServer as createHttpServer } from 'node:http'
|
||||
import { consola } from 'consola'
|
||||
import cors from 'cors'
|
||||
import express from 'express'
|
||||
import * as mediasoup from 'mediasoup'
|
||||
import { Server as SocketServer } from 'socket.io'
|
||||
import { webrtcSocket } from './sockets'
|
||||
|
||||
(async () => {
|
||||
const app = express()
|
||||
|
||||
app.use(cors())
|
||||
|
||||
const server = createHttpServer(app)
|
||||
|
||||
const worker = await mediasoup.createWorker()
|
||||
worker.on('died', () => {
|
||||
consola.error('[Mediasoup]', 'Worker died, exiting...')
|
||||
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
const router = await worker.createRouter({
|
||||
mediaCodecs: [
|
||||
{
|
||||
kind: 'audio',
|
||||
mimeType: 'audio/opus',
|
||||
clockRate: 48000,
|
||||
channels: 2,
|
||||
parameters: { useinbandfec: 1, stereo: 1 },
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const io = new SocketServer(server, {
|
||||
path: '/chad/ws',
|
||||
cors: {
|
||||
origin: process.env.CORS_ORIGIN || '*',
|
||||
},
|
||||
})
|
||||
|
||||
webrtcSocket(io, router)
|
||||
|
||||
server.listen(process.env.PORT || 3000, () => {
|
||||
consola.success('[Server]', 'Server started!')
|
||||
})
|
||||
})()
|
||||
@@ -1,19 +1,33 @@
|
||||
{
|
||||
"name": "server",
|
||||
"scripts": {
|
||||
"start": "ts-node --transpile-only index.ts"
|
||||
"start": "ts-node --transpile-only server.ts",
|
||||
"db:deploy": "npx prisma migrate deploy && npx prisma generate"
|
||||
},
|
||||
"type": "module",
|
||||
"packageManager": "yarn@4.10.3",
|
||||
"dependencies": {
|
||||
"@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",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^5.1.0",
|
||||
"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/express": "^5.0.3",
|
||||
"@types/bcrypt": "^6",
|
||||
"@types/ws": "^8",
|
||||
"eslint": "^9.36.0",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.9.3"
|
||||
|
||||
43
server/plugins/auth.ts
Normal file
43
server/plugins/auth.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
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 })
|
||||
}
|
||||
})
|
||||
}
|
||||
42
server/server.ts
Normal file
42
server/server.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
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)
|
||||
|
||||
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)
|
||||
}
|
||||
})()
|
||||
@@ -1,6 +1,17 @@
|
||||
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']
|
||||
@@ -20,10 +31,9 @@ type EventCallback<T = SuccessCallbackResult> = (result: T | ErrorCallbackResult
|
||||
interface ClientToServerEvents {
|
||||
join: (
|
||||
options: {
|
||||
username: string
|
||||
rtpCapabilities: types.RtpCapabilities
|
||||
},
|
||||
cb: EventCallback<{ id: string, username: string }[]>
|
||||
cb: EventCallback<ChadClient[]>
|
||||
) => void
|
||||
getRtpCapabilities: (
|
||||
cb: EventCallback<types.RtpCapabilities>
|
||||
@@ -80,39 +90,54 @@ interface ClientToServerEvents {
|
||||
},
|
||||
cb: EventCallback
|
||||
) => void
|
||||
updateClient: (
|
||||
options: Partial<Omit<ChadClient, 'socketId' | 'userId'>>,
|
||||
cb: EventCallback<ChadClient>
|
||||
) => void
|
||||
}
|
||||
|
||||
interface ServerToClientEvents {
|
||||
newPeer: (arg: { id: string, username: string }) => void
|
||||
authenticated: () => void
|
||||
newPeer: (arg: ChadClient) => void
|
||||
producers: (arg: ProducerShort[]) => void
|
||||
newConsumer: (arg: {
|
||||
peerId: string
|
||||
producerId: types.Producer['id']
|
||||
id: types.Consumer['id']
|
||||
kind: types.MediaKind
|
||||
rtpParameters: types.RtpParameters
|
||||
type: types.ConsumerType
|
||||
appData: types.Producer['appData']
|
||||
producerPaused: types.Consumer['producerPaused']
|
||||
}, cb: EventCallback) => void
|
||||
newConsumer: (
|
||||
arg: {
|
||||
peerId: string
|
||||
producerId: types.Producer['id']
|
||||
id: types.Consumer['id']
|
||||
kind: types.MediaKind
|
||||
rtpParameters: types.RtpParameters
|
||||
type: types.ConsumerType
|
||||
appData: types.Producer['appData']
|
||||
producerPaused: types.Consumer['producerPaused']
|
||||
},
|
||||
cb: EventCallback
|
||||
) => void
|
||||
peerClosed: (arg: string) => void
|
||||
consumerClosed: (arg: { consumerId: string }) => void
|
||||
consumerPaused: (arg: { consumerId: string }) => void
|
||||
consumerResumed: (arg: { consumerId: string }) => void
|
||||
consumerScore: (arg: { consumerId: string, score: types.ConsumerScore }) => void
|
||||
clientChanged: (clientId: ChadClient['socketId'], client: ChadClient) => void
|
||||
}
|
||||
|
||||
interface InterServerEvent {}
|
||||
|
||||
interface SocketData {
|
||||
joined: boolean
|
||||
username: string
|
||||
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')
|
||||
|
||||
@@ -120,30 +145,43 @@ export default function (io: SocketServer, router: types.Router) {
|
||||
consola.info('[WebRtc]', 'Client connected', socket.id)
|
||||
|
||||
socket.data.joined = false
|
||||
socket.data.username = socket.id
|
||||
|
||||
socket.data.inputMuted = false
|
||||
socket.data.outputMuted = false
|
||||
|
||||
socket.data.transports = new Map()
|
||||
socket.data.producers = new Map()
|
||||
socket.data.consumers = new Map()
|
||||
|
||||
socket.on('join', async ({ username, rtpCapabilities }, cb) => {
|
||||
prisma.user.findUnique({
|
||||
where: {
|
||||
id: socket.handshake.auth.userId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
displayName: true,
|
||||
},
|
||||
}).then(({ id, username, displayName }) => {
|
||||
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.username = username
|
||||
socket.data.rtpCapabilities = rtpCapabilities
|
||||
|
||||
const joinedSockets = await getJoinedSockets()
|
||||
|
||||
cb(joinedSockets.map((s) => {
|
||||
return {
|
||||
id: s.id,
|
||||
username: s.data.username,
|
||||
}
|
||||
}))
|
||||
cb(joinedSockets.map(socketToClient))
|
||||
|
||||
for (const joinedSocket of joinedSockets.filter(joinedSocket => joinedSocket.id !== socket.id)) {
|
||||
for (const producer of joinedSocket.data.producers.values()) {
|
||||
@@ -155,10 +193,7 @@ export default function (io: SocketServer, router: types.Router) {
|
||||
}
|
||||
}
|
||||
|
||||
socket.broadcast.emit('newPeer', {
|
||||
id: socket.id,
|
||||
username,
|
||||
})
|
||||
socket.broadcast.emit('newPeer', socketToClient(socket))
|
||||
})
|
||||
|
||||
socket.on('getRtpCapabilities', (cb) => {
|
||||
@@ -400,6 +435,33 @@ export default function (io: SocketServer, router: types.Router) {
|
||||
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)
|
||||
|
||||
@@ -420,8 +482,8 @@ export default function (io: SocketServer, router: types.Router) {
|
||||
}
|
||||
|
||||
async function createConsumer(
|
||||
consumerSocket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvent, SocketData>,
|
||||
producerSocket: RemoteSocket<ServerToClientEvents, SocketData>,
|
||||
consumerSocket: SomeSocket,
|
||||
producerSocket: SomeSocket,
|
||||
producer: types.Producer,
|
||||
) {
|
||||
if (
|
||||
@@ -518,4 +580,15 @@ export default function (io: SocketServer, router: types.Router) {
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import webrtcSocket from './webrtc'
|
||||
|
||||
export {
|
||||
webrtcSocket,
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2016",
|
||||
"module": "commonjs",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "nodenext",
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true
|
||||
"skipLibCheck": true,
|
||||
"allowImportingTsExtensions": true
|
||||
}
|
||||
}
|
||||
|
||||
1859
server/yarn.lock
1859
server/yarn.lock
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user