93 Commits

Author SHA1 Message Date
12ce381abd minor update
All checks were successful
Deploy / publish-web (push) Successful in 46s
2025-12-27 02:52:17 +06:00
2d30ac2863 minor update
All checks were successful
Deploy / publish-web (push) Successful in 44s
2025-12-27 02:49:39 +06:00
0f218c1519 button colors 2025-12-27 01:58:01 +06:00
4b1a563850 screen sharing
All checks were successful
Deploy / publish-web (push) Successful in 1m25s
2025-12-27 01:49:25 +06:00
169d43f0db screen sharing 2025-12-27 01:48:49 +06:00
47a464f08f screen sharing
All checks were successful
Deploy / publish-web (push) Successful in 48s
2025-12-26 18:22:22 +06:00
4d5db12e1b screen sharing
Some checks failed
Deploy / deploy (push) Successful in 35s
Deploy / publish-web (push) Failing after 22s
2025-12-26 17:36:30 +06:00
4f59cbcf65 screen sharing
All checks were successful
Deploy / deploy (push) Successful in 35s
2025-12-26 17:21:59 +06:00
3b3f6b6e40 update 2025-12-26 01:44:16 +06:00
461cbc6f83 profile rest
All checks were successful
Deploy / publish-web (push) Successful in 46s
2025-12-26 01:25:14 +06:00
a5cda8828f refactor
All checks were successful
Deploy / deploy (push) Successful in 34s
2025-12-26 01:22:34 +06:00
778f0a5687 refactor
All checks were successful
Deploy / deploy (push) Successful in 35s
2025-12-26 01:18:54 +06:00
2aca9bca08 refactor
All checks were successful
Deploy / deploy (push) Successful in 40s
2025-12-26 01:13:21 +06:00
7ed23df3e9 refactor
All checks were successful
Deploy / deploy (push) Successful in 39s
2025-12-26 01:08:44 +06:00
2ac88f1010 user preferences
All checks were successful
Deploy / publish-web (push) Successful in 2m14s
2025-12-25 22:53:12 +06:00
c2cffd18de user preferences 2025-12-25 22:51:02 +06:00
bf38267c37 user preferences
All checks were successful
Deploy / deploy (push) Successful in 36s
2025-12-25 22:50:56 +06:00
22c5fafb11 user preferences
All checks were successful
Deploy / deploy (push) Successful in 36s
2025-12-25 21:30:30 +06:00
37683c42a9 user preferences
All checks were successful
Deploy / deploy (push) Successful in 35s
2025-12-25 21:27:54 +06:00
2cbc75d7e3 user preferences
All checks were successful
Deploy / deploy (push) Successful in 37s
2025-12-25 21:24:41 +06:00
6721f63d22 user preferences
All checks were successful
Deploy / deploy (push) Successful in 36s
2025-12-25 21:22:43 +06:00
b47643552f user preferences
All checks were successful
Deploy / deploy (push) Successful in 36s
2025-12-25 21:08:14 +06:00
0ab3e15784 cors origins
All checks were successful
Deploy / deploy (push) Successful in 37s
2025-12-25 07:38:07 +06:00
28c64edaf8 update 2025-12-25 07:33:18 +06:00
67a8dc7782 update 2025-12-25 07:30:57 +06:00
43a8b98a6a update 2025-12-25 07:21:45 +06:00
0f9a7e39ce update 2025-12-25 07:21:30 +06:00
8265e2d719 update 2025-12-25 03:51:29 +06:00
4f91309f7f update 2025-12-24 06:29:44 +06:00
bcd457e2d6 update 2025-12-24 06:20:11 +06:00
8eef4fc477 update 2025-12-24 04:39:46 +06:00
614867bd12 update 2025-12-24 04:35:41 +06:00
cdf2bf5952 update 2025-12-24 04:35:13 +06:00
a4bd6705b6 Merge branch 'master' of git.koptilnya.xyz:opti1337/chad
Some checks failed
Deploy / publish-windows (push) Has been cancelled
2025-12-24 04:03:07 +06:00
723048c72a update 2025-12-24 04:02:53 +06:00
06ea0cd488 Обновить .gitea/workflows/deploy-client.yml
Some checks failed
Deploy / publish-windows (push) Failing after 6m3s
2025-12-23 19:52:47 +00:00
007d3ddda7 Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Has been cancelled
2025-12-24 00:42:07 +06:00
33cdaebada Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 3m0s
2025-12-24 00:25:30 +06:00
9650ea63fc update
Some checks failed
Deploy / publish-windows (push) Failing after 18s
2025-12-24 00:23:29 +06:00
db59b85bd2 udpate
All checks were successful
Deploy / publish-windows (push) Successful in 3m22s
2025-12-24 00:11:03 +06:00
3f6f3b739e Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 9m54s
2025-12-23 23:43:14 +06:00
b33a896117 Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 4m17s
2025-12-23 23:14:44 +06:00
01ae1b5011 Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 24s
2025-12-23 22:53:46 +06:00
0ac69610f2 Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 26s
2025-12-23 22:52:38 +06:00
c4489b58c9 Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 23s
2025-12-23 22:50:37 +06:00
c19bef73e0 Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Has been cancelled
2025-12-23 22:44:24 +06:00
c573d2277a update
Some checks failed
Deploy / publish-windows (push) Failing after 23s
2025-12-23 22:42:04 +06:00
3006a82a0f update
Some checks failed
Deploy / publish-windows (push) Failing after 19m11s
2025-12-23 22:03:09 +06:00
a68aa78ae1 update
Some checks failed
Deploy / publish-windows (push) Failing after 16m16s
2025-12-23 21:45:21 +06:00
ba9f51bd5e Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 18m59s
2025-12-23 21:21:44 +06:00
89a3eac2b9 Update deploy-client.yml
Some checks failed
Deploy / publish-windows (push) Failing after 18s
2025-12-23 20:55:14 +06:00
01de23a036 Merge pull request 'release test' (#7) from release into master
Reviewed-on: #7
2025-12-23 14:51:49 +00:00
aef93ef821 update 2025-12-23 20:50:13 +06:00
72f46df4d1 update
All checks were successful
Deploy / publish-windows (push) Successful in 19s
2025-12-23 00:59:01 +06:00
50c56e87ff Update Dockerfile.windows
All checks were successful
Deploy / publish-windows (push) Successful in 6m11s
2025-12-23 00:37:41 +06:00
a7d65f0e3c Update deploy-client.yml
Some checks failed
Deploy / publish-windows (push) Failing after 5m37s
2025-12-23 00:27:43 +06:00
649b49a732 update
Some checks failed
Deploy / publish-windows (push) Failing after 9s
2025-12-23 00:27:01 +06:00
b887b69997 Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 2m45s
2025-12-23 00:07:40 +06:00
687a2958c0 Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 1m52s
2025-12-22 23:35:59 +06:00
a7fe94abec Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 3m13s
2025-12-22 22:40:13 +06:00
adb539350f Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 27s
2025-12-22 22:37:41 +06:00
d870b7c1f1 Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 9m31s
2025-12-22 22:27:02 +06:00
edd5a69cd4 Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 35s
2025-12-22 22:24:34 +06:00
6343f1de4d Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 2m21s
2025-12-22 22:19:14 +06:00
3f581ea8e9 Update deploy-client.yml
Some checks failed
Deploy / publish-windows (push) Failing after 2m34s
2025-12-22 22:15:37 +06:00
10bfcf0727 Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 21s
2025-12-22 22:14:24 +06:00
6b5383ba24 Update Dockerfile.windows
Some checks failed
Deploy / publish-windows (push) Failing after 19s
2025-12-22 22:01:30 +06:00
6b5d669f64 update
Some checks failed
Deploy / publish-windows (push) Failing after 27s
2025-12-22 21:55:12 +06:00
40d66d356b update
Some checks failed
Deploy / publish-tauri (push) Failing after 15s
Deploy / publish-web (push) Successful in 40s
2025-12-22 21:50:33 +06:00
c665c19cf3 update
Some checks failed
Deploy / publish-web (push) Failing after 33s
Deploy / publish-tauri (push) Failing after 50s
2025-12-22 21:47:24 +06:00
b05a7324d6 update
Some checks failed
Deploy / publish-web (push) Successful in 41s
Deploy / publish-tauri (push) Failing after 52s
2025-12-22 21:45:17 +06:00
e8cbf6e146 update
Some checks failed
Deploy / publish-tauri (push) Has been cancelled
Deploy / publish-web (push) Has been cancelled
2025-12-22 21:44:36 +06:00
472fa8d907 update
Some checks failed
Deploy / publish-web (push) Failing after 20s
Deploy / publish-tauri (push) Failing after 18s
2025-12-22 21:40:38 +06:00
ddc43e4b42 update
Some checks failed
Deploy / publish-web (push) Failing after 41s
Deploy / publish-tauri (push) Failing after 25s
2025-12-22 21:36:12 +06:00
8d02eb380d update
Some checks failed
Deploy / publish-web (push) Failing after 13s
Deploy / publish-tauri (push) Failing after 12s
2025-12-22 21:17:29 +06:00
4c70dce568 build
Some checks failed
Deploy / publish-web (push) Failing after 25s
Deploy / publish-tauri (push) Failing after 10s
2025-12-22 21:07:20 +06:00
76f0ec74b5 test publish
Some checks failed
Deploy / deploy (push) Has been cancelled
Deploy / publish-web (push) Successful in 1m43s
Deploy / publish-tauri (push) Has been cancelled
2025-12-22 19:23:06 +06:00
Никита Круглицкий
e3d0106d8f куча говна
All checks were successful
Deploy / deploy (push) Successful in 44s
2025-10-20 06:44:21 +06:00
Никита Круглицкий
e2068dd89a куча говна
All checks were successful
Deploy / deploy (push) Successful in 45s
2025-10-20 06:14:18 +06:00
Никита Круглицкий
a2f845f228 куча говна
All checks were successful
Deploy / deploy (push) Successful in 45s
2025-10-20 06:01:29 +06:00
Никита Круглицкий
1a497d402d куча говна
All checks were successful
Deploy / deploy (push) Successful in 46s
2025-10-20 05:59:06 +06:00
Никита Круглицкий
924bbd4285 куча говна
All checks were successful
Deploy / deploy (push) Successful in 43s
2025-10-20 05:57:08 +06:00
Никита Круглицкий
58d37ee02b куча говна
All checks were successful
Deploy / deploy (push) Successful in 45s
2025-10-20 05:50:27 +06:00
Никита Круглицкий
ba12d413dc куча говна
All checks were successful
Deploy / deploy (push) Successful in 44s
2025-10-20 03:53:29 +06:00
Никита Круглицкий
f525d1afe5 куча говна
All checks were successful
Deploy / deploy (push) Successful in 45s
2025-10-20 03:36:30 +06:00
Никита Круглицкий
75fe5b0b8c куча говна
All checks were successful
Deploy / deploy (push) Successful in 44s
2025-10-20 03:33:07 +06:00
Никита Круглицкий
39e877bbe9 куча говна
All checks were successful
Deploy / deploy (push) Successful in 47s
2025-10-20 03:23:34 +06:00
Никита Круглицкий
fe205531e0 куча говна
All checks were successful
Deploy / deploy (push) Successful in 44s
2025-10-20 03:17:54 +06:00
Никита Круглицкий
1ef0df7afb куча говна
All checks were successful
Deploy / deploy (push) Successful in 44s
2025-10-20 00:20:09 +06:00
Никита Круглицкий
a0bd6f92e9 куча говна
Some checks failed
Deploy / deploy (push) Failing after 25s
2025-10-20 00:19:25 +06:00
Никита Круглицкий
511cb76888 куча говна
Some checks failed
Deploy / deploy (push) Failing after 1m27s
2025-10-20 00:16:59 +06:00
Никита Круглицкий
a433e1982b куча говна
Some checks failed
Deploy / deploy (push) Failing after 9s
2025-10-20 00:11:03 +06:00
Никита Круглицкий
ec67be8aa6 куча говна
All checks were successful
Deploy / deploy (push) Successful in 4m32s
2025-10-20 00:10:13 +06:00
80 changed files with 6068 additions and 2719 deletions

View File

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

2
client/.gitattributes vendored Normal file
View File

@@ -0,0 +1,2 @@
/.yarn/releases/** binary
/.yarn/plugins/** binary

6
client/.gitignore vendored
View File

@@ -23,9 +23,15 @@ logs
.env.* .env.*
!.env.example !.env.example
.pnp.*
.yarn/* .yarn/*
!.yarn/patches !.yarn/patches
!.yarn/plugins !.yarn/plugins
!.yarn/releases !.yarn/releases
!.yarn/sdks !.yarn/sdks
!.yarn/versions !.yarn/versions
scripts/release.ps1
.tauri
updater.json

Binary file not shown.

942
client/.yarn/releases/yarn-4.12.0.cjs vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1 +1,3 @@
nodeLinker: node-modules nodeLinker: node-modules
yarnPath: .yarn/releases/yarn-4.12.0.cjs

View File

@@ -2,16 +2,17 @@ FROM node:lts-alpine AS builder
WORKDIR /app WORKDIR /app
RUN corepack enable
RUN yarn set version stable
COPY package.json yarn.lock .yarnrc.yml ./ COPY package.json yarn.lock .yarnrc.yml ./
COPY .yarn ./.yarn
RUN yarn install RUN yarn install --immutable
COPY . . COPY . .
ARG COMMIT_SHA=unknown 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 RUN yarn generate

46
client/Dockerfile.windows Normal file
View File

@@ -0,0 +1,46 @@
# === Build ===
FROM node:lts AS builder
WORKDIR /app
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"]

View File

@@ -5,3 +5,7 @@
<PrimeToast position="bottom-center" /> <PrimeToast position="bottom-center" />
</template> </template>
<script setup lang="ts">
const route = useRoute()
</script>

View File

@@ -6,8 +6,42 @@ body {
height: 100%; height: 100%;
overflow: hidden; overflow: hidden;
background-image: radial-gradient(var(--p-surface-700), var(--p-surface-800));
background-size: 200% 200%;
background-position: left -100% top -100%;
} }
#__nuxt { #__nuxt {
--p-scrollpanel-bar-size: 5px;
--p-scrollpanel-bar-background: var(--p-surface-950);
--p-divider-horizontal-margin: 2rem 0 1rem;
height: 100%; height: 100%;
} }
.p-divider {
&:first-child {
--p-divider-horizontal-margin: 1rem 0 1rem;
}
}
.p-scrollpanel-bar-y {
translate: -0.25rem;
}
.p-select-overlay {
/* Force dropdown width to match computed min-width from PrimeVue internals. */
width: 0 !important;
}
.p-select-label {
width: 0 !important;
overflow: hidden !important;
text-overflow: ellipsis !important;
}
.p-select-option-label {
min-width: 0 !important;
overflow: hidden !important;
text-overflow: ellipsis !important;
}

View File

@@ -13,13 +13,21 @@ declare module 'vue' {
PrimeButton: typeof import('primevue/button')['default'] PrimeButton: typeof import('primevue/button')['default']
PrimeButtonGroup: typeof import('primevue/buttongroup')['default'] PrimeButtonGroup: typeof import('primevue/buttongroup')['default']
PrimeCard: typeof import('primevue/card')['default'] PrimeCard: typeof import('primevue/card')['default']
PrimeFieldset: typeof import('primevue/fieldset')['default'] PrimeDivider: typeof import('primevue/divider')['default']
PrimeFloatLabel: typeof import('primevue/floatlabel')['default'] PrimeFloatLabel: typeof import('primevue/floatlabel')['default']
PrimeInputText: typeof import('primevue/inputtext')['default'] PrimeInputText: typeof import('primevue/inputtext')['default']
PrimeMenu: typeof import('primevue/menu')['default'] PrimePassword: typeof import('primevue/password')['default']
PrimeProgressBar: typeof import('primevue/progressbar')['default']
PrimeScrollPanel: typeof import('primevue/scrollpanel')['default']
PrimeSelect: typeof import('primevue/select')['default']
PrimeSelectButton: typeof import('primevue/selectbutton')['default']
PrimeSlider: typeof import('primevue/slider')['default'] PrimeSlider: typeof import('primevue/slider')['default']
PrimeToast: typeof import('primevue/toast')['default'] PrimeToast: typeof import('primevue/toast')['default']
PrimeToggleSwitch: typeof import('primevue/toggleswitch')['default']
RouterLink: typeof import('vue-router')['RouterLink'] RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView'] RouterView: typeof import('vue-router')['RouterView']
} }
export interface ComponentCustomProperties {
Tooltip: typeof import('primevue/tooltip')['default']
}
} }

View File

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

View File

@@ -1,89 +1,129 @@
<template> <template>
<div class="py-3"> <div
<div class="flex items-center gap-3 "> class="overflow-hidden rounded-xl transition-[background-color]"
<PrimeAvatar :class="{
icon="pi pi-user" 'hover:bg-surface-800 cursor-pointer': !isMe,
size="small" 'bg-surface-800': expanded,
/> }"
>
<div class="p-3 flex items-center gap-3" @click="toggleExpand">
<PrimeAvatar size="small">
<template #icon>
<User :size="20" />
</template>
</PrimeAvatar>
<div class="flex-1"> <div class="flex-1 overflow-hidden text-sm leading-5 font-medium text-color whitespace-nowrap overflow-ellipsis">
<div class="text-sm leading-5 font-medium text-color whitespace-nowrap overflow-ellipsis"> {{ client.displayName || client.username }}
{{ client.username }}
</div>
<div class="mt-1 text-xs leading-5 text-muted-color">
{{ client.id }}
</div>
</div> </div>
<PrimeBadge v-if="client.isMe && inputMuted" severity="info" value="Muted" /> <div class="flex align-center gap-1">
<PrimeBadge v-if="client.isMe" severity="secondary" value="You" /> <PrimeBadge v-if="!!shareConsumer" v-tooltip.top="'Watch'" severity="success" value="Streaming" size="small" @click.stop="watchStream" />
<template v-if="!client.isMe"> <PrimeBadge v-if="premuted" severity="danger" value="Muted" size="small" />
<PrimeButton icon="pi pi-ellipsis-h" text size="small" severity="contrast" @click="menuRef?.toggle" /> <PrimeBadge v-else-if="client.outputMuted" severity="info" value="No sound" size="small" />
<PrimeBadge v-else-if="inputMuted" severity="info" value="Muted" size="small" />
<PrimeMenu ref="menu" popup :model="menuItems" style="translate: calc(-100% + 2rem) 0.5rem"> <PrimeBadge v-if="isMe" severity="secondary" value="You" size="small" class="shrink-0" />
<template #start> </div>
<div class="px-4 py-3">
<div class="flex justify-between"> <Component :is="expanded ? ChevronUp : ChevronDown" v-if="!isMe" :size="20" class="text-muted-color" />
<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>
<CollapseTransition v-if="!isMe">
<div v-if="expanded">
<div class="px-3 pb-3">
<div class="flex justify-between text-sm mb-3">
<span>Volume</span>
<span>{{ volume }}</span>
</div>
<PrimeSlider v-model="volume" :min="0" :max="1000" :step="volume < 200 ? 5 : 25" />
<div class="mt-3 flex gap-1 justify-end">
<PrimeButton size="small" variant="text" @click="premuted = !premuted">
{{ premuted ? 'Unmute' : 'Mute' }}
</PrimeButton>
</div>
</div>
</div>
</CollapseTransition>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import type { ChadClient } from '#shared/types' import type { ChadClient } from '#shared/types'
import type { MenuItem } from 'primevue/menuitem' import { useLocalStorage } from '@vueuse/core'
import { ChevronDown, ChevronUp, User } from 'lucide-vue-next'
import CollapseTransition from '~/components/CollapseTransition.vue'
const props = defineProps<{ const props = defineProps<{
client: ChadClient client: ChadClient
}>() }>()
const { inputMuted, outputMuted } = useApp() const { outputMuted } = useApp()
const { getClientConsumers } = useMediasoup() const { consumers: allConsumers, micProducer } = useMediasoup()
const { me } = useClients()
const { show } = useFullscreenVideo()
const menuRef = useTemplateRef<HTMLAudioElement>('menu') const expanded = ref(false)
const volume = ref(100) const volume = useLocalStorage<number>(computed(() => `CLIENT_VOLUME_${props.client.userId}`), 100, { writeDefaults: false })
const premuted = useLocalStorage<boolean>(computed(() => `CLIENT_PREMUTED_${props.client.userId}`), false, { writeDefaults: false })
const menuItems: MenuItem[] = [ const isMe = computed(() => {
{ return me.value && props.client.userId === me.value.userId
label: 'Mute', })
icon: 'pi pi-headphones',
}, const consumers = computed(() => {
{ return allConsumers.value.values().filter(consumer => consumer.appData.socketId === props.client.socketId).toArray()
label: 'DM', })
icon: 'pi pi-comment',
disabled: true,
},
]
const audioConsumer = computed(() => { const audioConsumer = computed(() => {
const consumers = getClientConsumers(props.client.id) return consumers.value.find(consumer => consumer.track.kind === 'audio')
})
return consumers.find(consumer => consumer.track.kind === 'audio') const videoConsumers = computed(() => {
return consumers.value.filter(consumer => consumer.track.kind === 'video')
})
const shareConsumer = computed(() => {
return videoConsumers.value.find(consumer => consumer.appData.source === 'share')
}) })
const audioTrack = computed(() => { const audioTrack = computed(() => {
return audioConsumer.value?.track return audioConsumer.value?.track
}) })
const audioConsumerPaused = ref(false)
const inputMuted = computed(() => {
if (isMe.value)
return micProducer.value?.paused ?? false
return premuted.value || audioConsumerPaused.value
})
watch(allConsumers, () => {
audioConsumerPaused.value = audioConsumer.value?.paused ?? false
})
const { setGain } = useAudioContext(audioTrack) const { setGain } = useAudioContext(audioTrack)
watch(volume, (volume) => { watchEffect(() => {
if (outputMuted.value) setGain((outputMuted.value || premuted.value) ? 0 : (volume.value * 0.01))
})
function toggleExpand() {
if (isMe.value)
return return
setGain(volume * 0.01) expanded.value = !expanded.value
}) }
watch(outputMuted, (outputMuted) => { function watchStream() {
setGain(outputMuted ? 0 : (volume.value * 0.01)) if (!shareConsumer.value)
}) return
show(new MediaStream([shareConsumer.value.track]))
}
</script> </script>

View File

@@ -0,0 +1,118 @@
<template>
<Transition name="collapse-transition" v-on="bindings">
<slot />
</Transition>
</template>
<script lang="ts" setup>
import type { RendererElement } from 'vue'
defineOptions({
name: 'CollapseTransition',
})
const emit = defineEmits<{
expanded: []
collapsed: []
}>()
const bindings = {
beforeEnter(el: RendererElement) {
if (!el.dataset)
el.dataset = {}
el.dataset.oldPaddingTop = el.style.paddingTop
el.dataset.oldPaddingBottom = el.style.paddingBottom
el.dataset.elExistsHeight = el.style.height ?? undefined
el.style.maxHeight = 0
el.style.paddingTop = 0
el.style.paddingBottom = 0
},
enter(el: RendererElement) {
requestAnimationFrame(() => {
el.dataset.oldOverflow = el.style.overflow
if (el.dataset.elExistsHeight) {
el.style.maxHeight = el.dataset.elExistsHeight
}
else if (el.scrollHeight !== 0) {
el.style.maxHeight = `${el.scrollHeight}px`
}
else {
el.style.maxHeight = 0
}
el.style.paddingTop = el.dataset.oldPaddingTop
el.style.paddingBottom = el.dataset.oldPaddingBottom
el.style.overflow = 'hidden'
})
},
afterEnter(el: RendererElement) {
el.style.maxHeight = ''
el.style.overflow = el.dataset.oldOverflow
emit('expanded')
},
enterCancelled(el: RendererElement) {
reset(el)
},
beforeLeave(el: RendererElement) {
if (!el.dataset)
el.dataset = {}
el.dataset.oldPaddingTop = el.style.paddingTop
el.dataset.oldPaddingBottom = el.style.paddingBottom
el.dataset.oldOverflow = el.style.overflow
el.style.maxHeight = `${el.scrollHeight}px`
el.style.overflow = 'hidden'
},
leave(el: RendererElement) {
if (el.scrollHeight !== 0) {
el.style.maxHeight = 0
el.style.paddingTop = 0
el.style.paddingBottom = 0
}
},
afterLeave(el: RendererElement) {
reset(el)
emit('collapsed')
},
leaveCancelled(el: RendererElement) {
reset(el)
},
}
function reset(el: RendererElement) {
el.style.maxHeight = ''
el.style.overflow = el.dataset.oldOverflow
el.style.paddingTop = el.dataset.oldPaddingTop
el.style.paddingBottom = el.dataset.oldPaddingBottom
}
</script>
<style lang="scss">
.collapse-transition {
transition-property: height, padding-top, padding-bottom;
transition-timing-function: var(--default-transition-timing-function, cubic-bezier(0.4, 0, 0.2, 1));
transition-duration: var(--default-transition-duration, 150ms);
}
.collapse-transition-leave-active,
.collapse-transition-enter-active {
transition-property: opacity, max-height, padding-top, padding-bottom;
transition-timing-function: var(--default-transition-timing-function, cubic-bezier(0.4, 0, 0.2, 1));
transition-duration: var(--default-transition-duration, 150ms);
}
.collapse-transition-leave-to,
.collapse-transition-enter-from {
opacity: 0;
}
</style>

View File

@@ -1,79 +1,118 @@
import { createGlobalState } from '@vueuse/core' import { getVersion } from '@tauri-apps/api/app'
import { computedAsync, createGlobalState } from '@vueuse/core'
import { useClients } from '~/composables/use-clients' import { useClients } from '~/composables/use-clients'
export const useApp = createGlobalState(() => { export const useApp = createGlobalState(() => {
const { clients } = useClients() const { clients } = useClients()
const mediasoup = useMediasoup() const mediasoup = useMediasoup()
const signaling = useSignaling()
const toast = useToast() const toast = useToast()
const inputMuted = ref(false) const ready = ref(false)
const outputMuted = ref(false) const isTauri = computed(() => '__TAURI_INTERNALS__' in window)
const commitSha = __COMMIT_SHA__
const version = computedAsync(() => {
if (import.meta.dev) {
return 'dev'
}
else if (isTauri.value) {
return getVersion()
}
else {
return 'web'
}
}, '-')
const inputMuted = computed(() => {
return !!mediasoup.micProducer.value?.paused
})
const previousInputMuted = ref(inputMuted.value) const previousInputMuted = ref(inputMuted.value)
const me = computed(() => clients.value.find(client => client.isMe)) const outputMuted = ref(false)
function muteInput() { const sharingEnabled = computed(() => {
inputMuted.value = true return !!mediasoup.shareProducer.value
} })
function unmuteInput() { async function muteInput() {
inputMuted.value = false
}
function toggleInput() {
if (inputMuted.value) if (inputMuted.value)
unmuteInput() return
await mediasoup.pauseProducer('microphone')
toast.add({ severity: 'info', summary: 'Microphone muted', closable: false, life: 1000 })
}
async function unmuteInput() {
if (!inputMuted.value)
return
if (outputMuted.value) {
await unmuteOutput()
}
await mediasoup.resumeProducer('microphone')
toast.add({ severity: 'info', summary: 'Microphone activated', closable: false, life: 1000 })
}
async function toggleInput() {
if (inputMuted.value)
await unmuteInput()
else else
muteInput() await muteInput()
} }
function muteOutput() { async function muteOutput() {
outputMuted.value = true
}
function unmuteOutput() {
outputMuted.value = false
}
function toggleOutput() {
if (outputMuted.value) if (outputMuted.value)
unmuteOutput() return
else
muteOutput() outputMuted.value = true
previousInputMuted.value = inputMuted.value
await muteInput()
await signaling.socket.value?.emitWithAck('updateClient', {
outputMuted: true,
})
toast.add({ severity: 'info', summary: 'Sound muted', closable: false, life: 1000 })
} }
watch(inputMuted, async (inputMuted) => { async function unmuteOutput() {
if (inputMuted) { outputMuted.value = false
await mediasoup.muteMic()
if (!previousInputMuted.value)
await unmuteInput()
await signaling.socket.value?.emitWithAck('updateClient', {
outputMuted: false,
})
toast.add({ severity: 'info', summary: 'Sound resumed', closable: false, life: 1000 })
}
async function toggleOutput() {
if (outputMuted.value)
await unmuteOutput()
else
await muteOutput()
}
async function toggleShare() {
if (!mediasoup.shareProducer.value) {
await mediasoup.enableShare()
} }
else { else {
if (outputMuted.value) { await mediasoup.disableProducer('share')
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 { return {
ready,
clients, clients,
me,
inputMuted, inputMuted,
muteInput, muteInput,
unmuteInput, unmuteInput,
@@ -82,5 +121,10 @@ export const useApp = createGlobalState(() => {
muteOutput, muteOutput,
unmuteOutput, unmuteOutput,
toggleOutput, toggleOutput,
version,
isTauri,
commitSha,
toggleShare,
sharingEnabled,
} }
}) })

View File

@@ -4,13 +4,12 @@ export default function useAudioContext(audioTrack: Ref<MediaStreamTrack | undef
const ctx = new (window.AudioContext || window.webkitAudioContext)() const ctx = new (window.AudioContext || window.webkitAudioContext)()
const stream = new MediaStream() const stream = new MediaStream()
const audioEl = new Audio()
const sourceNode = shallowRef<MediaStreamAudioSourceNode>() const sourceNode = shallowRef<MediaStreamAudioSourceNode>()
const gainNode = ctx.createGain() const gainNode = ctx.createGain()
let hackExecuted = false watch(audioTrack, async (track, prevTrack) => {
watch(audioTrack, (track, prevTrack) => {
if (prevTrack) if (prevTrack)
stream.removeTrack(prevTrack) stream.removeTrack(prevTrack)
@@ -19,16 +18,14 @@ export default function useAudioContext(audioTrack: Ref<MediaStreamTrack | undef
stream.addTrack(track) stream.addTrack(track)
if (!hackExecuted) { if (!audioEl.srcObject) {
const audioEl = new Audio()
audioEl.srcObject = stream audioEl.srcObject = stream
audioEl.muted = true audioEl.muted = true
hackExecuted = true
} }
sourceNode.value = ctx.createMediaStreamSource(stream) sourceNode.value = ctx.createMediaStreamSource(stream)
connect() await connect()
}, { immediate: true }) }, { immediate: true })
useEventListener(document, 'click', async () => { useEventListener(document, 'click', async () => {
@@ -36,10 +33,16 @@ export default function useAudioContext(audioTrack: Ref<MediaStreamTrack | undef
await ctx.resume() await ctx.resume()
} }
connect() await connect()
}, { once: true }) }, { once: true })
function connect() { onScopeDispose(() => {
audioEl.pause()
audioEl.srcObject = null
ctx.close()
})
async function connect() {
if (!sourceNode.value || ctx.state === 'suspended') if (!sourceNode.value || ctx.state === 'suspended')
return return

View 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,
}
})

View File

@@ -2,26 +2,33 @@ import type { ChadClient, UpdatedClient } from '#shared/types'
import { createGlobalState } from '@vueuse/core' import { createGlobalState } from '@vueuse/core'
export const useClients = createGlobalState(() => { export const useClients = createGlobalState(() => {
const auth = useAuth()
const signaling = useSignaling() const signaling = useSignaling()
const toast = useToast() const toast = useToast()
const clients = shallowRef<ChadClient[]>([]) const clients = shallowRef<ChadClient[]>([])
const me = computed(() => clients.value.find(client => client.userId === auth.me.value?.id))
watch(signaling.socket, (socket) => { watch(signaling.socket, (socket) => {
if (!socket) if (!socket)
return return
socket.on('clientChanged', (clientId: ChadClient['id'], updatedClient: UpdatedClient) => { socket.on('clientChanged', (clientId: ChadClient['socketId'], updatedClient: UpdatedClient) => {
const client = getClient(clientId) const client = getClient(clientId)
updateClient(clientId, updatedClient) updateClient(clientId, updatedClient)
if (updatedClient.username) if (client && client.displayName !== updatedClient.displayName)
toast.add({ severity: 'info', summary: `${client?.username} is now ${updatedClient.username}`, closable: false, life: 1000 }) toast.add({ severity: 'info', summary: `${client.displayName} is now ${updatedClient.displayName}`, closable: false, life: 1000 })
})
socket.on('disconnect', () => {
clients.value = []
}) })
}) })
function getClient(clientId: ChadClient['id']) { function getClient(clientId: ChadClient['socketId']) {
return clients.value.find(client => client.id === clientId) return clients.value.find(client => client.socketId === clientId)
} }
function addClient(...client: ChadClient[]) { function addClient(...client: ChadClient[]) {
@@ -30,12 +37,12 @@ export const useClients = createGlobalState(() => {
triggerRef(clients) triggerRef(clients)
} }
function removeClient(clientId: ChadClient['id']) { function removeClient(clientId: ChadClient['socketId']) {
clients.value = clients.value.filter(client => client.id !== clientId) clients.value = clients.value.filter(client => client.socketId !== clientId)
} }
function updateClient(clientId: ChadClient['id'], updatedClient: UpdatedClient) { function updateClient(clientId: ChadClient['socketId'], updatedClient: UpdatedClient) {
const clientIdx = clients.value.findIndex(client => client.id === clientId) const clientIdx = clients.value.findIndex(client => client.socketId === clientId)
if (clientIdx === -1) if (clientIdx === -1)
return return
@@ -49,6 +56,7 @@ export const useClients = createGlobalState(() => {
} }
return { return {
me,
clients, clients,
getClient, getClient,
addClient, addClient,

View File

@@ -0,0 +1,28 @@
import { createGlobalState, useDevicesList } from '@vueuse/core'
export const useDevices = createGlobalState(() => {
const {
ensurePermissions,
permissionGranted,
videoInputs,
audioInputs,
audioOutputs,
} = useDevicesList()
async function getShareStream(fps = 30) {
return navigator.mediaDevices.getDisplayMedia({
audio: false,
video: {
displaySurface: 'monitor',
frameRate: { max: fps },
},
})
}
return {
videoInputs: computed<MediaDeviceInfo[]>(() => JSON.parse(JSON.stringify(videoInputs.value))),
audioInputs: computed<MediaDeviceInfo[]>(() => JSON.parse(JSON.stringify(audioInputs.value))),
audioOutputs: computed<MediaDeviceInfo[]>(() => JSON.parse(JSON.stringify(audioOutputs.value))),
getShareStream,
}
})

View File

@@ -0,0 +1,65 @@
import { createGlobalState, useEventListener } from '@vueuse/core'
export const useFullscreenVideo = createGlobalState(() => {
const videoEl = shallowRef<HTMLVideoElement>()
const visible = computed(() => !!videoEl.value)
async function show(stream: MediaStream) {
if (videoEl.value) {
videoEl.value.srcObject = stream
}
else {
const el = document.createElement('video')
el.srcObject = stream
el.autoplay = true
el.playsInline = true
el.controls = false
el.muted = true
// el.style.position = 'fixed'
// el.style.top = '0'
// el.style.left = '0'
// el.style.width = '1px'
// el.style.height = '1px'
// el.style.opacity = '0'
// el.style.pointerEvents = 'none'
document.body.appendChild(el)
videoEl.value = el
}
stream.getTracks().forEach(t =>
t.addEventListener('ended', hide),
)
videoEl.value.addEventListener('ended', hide)
await videoEl.value.requestFullscreen()
}
function hide() {
if (!videoEl.value)
return
(videoEl.value.srcObject as MediaStream).getTracks().forEach(t =>
t.removeEventListener('ended', hide),
)
videoEl.value.removeEventListener('ended', hide)
videoEl.value?.remove()
videoEl.value = undefined
}
useEventListener(document, 'fullscreenchange', () => {
if (!document.fullscreenElement && videoEl.value) {
videoEl.value?.remove()
videoEl.value = undefined
}
})
return {
visible,
show,
hide,
}
})

View File

@@ -1,9 +1,12 @@
import type { ChadClient, RemoteClient } from '#shared/types' import type { MediaKind, ProducerOptions } from 'mediasoup-client/types'
import { createSharedComposable } from '@vueuse/core' import { createSharedComposable } from '@vueuse/core'
import * as mediasoupClient from 'mediasoup-client' import * as mediasoupClient from 'mediasoup-client'
import { useDevices } from '~/composables/use-devices'
import { usePreferences } from '~/composables/use-preferences' import { usePreferences } from '~/composables/use-preferences'
import { useSignaling } from '~/composables/use-signaling' import { useSignaling } from '~/composables/use-signaling'
type ProducerType = 'microphone' | 'camera' | 'share'
const ICE_SERVERS: RTCIceServer[] = [ const ICE_SERVERS: RTCIceServer[] = [
{ urls: 'stun:stun.l.google.com:19302' }, { urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun.l.google.com:5349' }, { urls: 'stun:stun.l.google.com:5349' },
@@ -23,6 +26,7 @@ export const useMediasoup = createSharedComposable(() => {
const signaling = useSignaling() const signaling = useSignaling()
const { addClient, removeClient } = useClients() const { addClient, removeClient } = useClients()
const preferences = usePreferences() const preferences = usePreferences()
const { getShareStream } = useDevices()
const device = shallowRef<mediasoupClient.Device>() const device = shallowRef<mediasoupClient.Device>()
const rtpCapabilities = shallowRef<mediasoupClient.types.RtpCapabilities>() const rtpCapabilities = shallowRef<mediasoupClient.types.RtpCapabilities>()
@@ -30,7 +34,7 @@ export const useMediasoup = createSharedComposable(() => {
const recvTransport = shallowRef<mediasoupClient.types.Transport>() const recvTransport = shallowRef<mediasoupClient.types.Transport>()
const micProducer = shallowRef<mediasoupClient.types.Producer>() const micProducer = shallowRef<mediasoupClient.types.Producer>()
const webcamProducer = shallowRef<mediasoupClient.types.Producer>() const cameraProducer = shallowRef<mediasoupClient.types.Producer>()
const shareProducer = shallowRef<mediasoupClient.types.Producer>() const shareProducer = shallowRef<mediasoupClient.types.Producer>()
const consumers = shallowRef<Map<string, mediasoupClient.types.Consumer>>(new Map()) const consumers = shallowRef<Map<string, mediasoupClient.types.Consumer>>(new Map())
@@ -40,7 +44,7 @@ export const useMediasoup = createSharedComposable(() => {
if (!socket) if (!socket)
return return
socket.on('connect', async () => { socket.on('authenticated', async () => {
if (!signaling.socket.value) if (!signaling.socket.value)
return return
@@ -123,9 +127,8 @@ export const useMediasoup = createSharedComposable(() => {
} }
const joinedClients = (await signaling.socket.value.emitWithAck('join', { const joinedClients = (await signaling.socket.value.emitWithAck('join', {
username: preferences.username.value,
rtpCapabilities: rtpCapabilities.value, rtpCapabilities: rtpCapabilities.value,
})).map(transformClient) }))
addClient(...joinedClients) addClient(...joinedClients)
@@ -135,7 +138,7 @@ export const useMediasoup = createSharedComposable(() => {
}) })
socket.on('newPeer', (client) => { socket.on('newPeer', (client) => {
addClient(transformClient(client)) addClient(client)
}) })
socket.on('peerClosed', (id) => { socket.on('peerClosed', (id) => {
@@ -145,7 +148,7 @@ export const useMediasoup = createSharedComposable(() => {
socket.on( socket.on(
'newConsumer', 'newConsumer',
async ( async (
{ id, producerId, kind, rtpParameters, peerId: clientId, appData }, { id, producerId, kind, rtpParameters, socketId, appData, producerPaused },
cb, cb,
) => { ) => {
if (!recvTransport.value) if (!recvTransport.value)
@@ -156,13 +159,16 @@ export const useMediasoup = createSharedComposable(() => {
producerId, producerId,
kind, kind,
rtpParameters, rtpParameters,
streamId: `${clientId}-${appData.share ? 'share' : 'mic-webcam'}`, streamId: `${socketId}-${appData.source === 'share' ? 'share' : 'mic-webcam'}`,
appData: { ...appData, clientId }, appData: { ...appData, socketId },
}) })
if (producerPaused)
consumer.pause()
consumer.on('transportclose', () => { consumer.on('transportclose', () => {
consumers.value.delete(consumer.id) if (consumers.value.delete(consumer.id))
triggerRef(consumers) triggerRef(consumers)
}) })
consumers.value.set(consumer.id, consumer) consumers.value.set(consumer.id, consumer)
@@ -177,53 +183,123 @@ export const useMediasoup = createSharedComposable(() => {
async ( async (
{ consumerId }, { consumerId },
) => { ) => {
const consumer = consumers.value.get(consumerId) if (consumers.value.delete(consumerId))
triggerRef(consumers)
if (!consumer)
return
consumers.value.delete(consumer.id)
triggerRef(consumers)
}, },
) )
socket.on('disconnect', () => { socket.on('disconnect', () => {
device.value = undefined
rtpCapabilities.value = undefined
sendTransport.value?.close() sendTransport.value?.close()
sendTransport.value = undefined sendTransport.value = undefined
recvTransport.value?.close() recvTransport.value?.close()
recvTransport.value = undefined 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()
triggerRef(consumers)
})
socket.on('consumerResumed', ({ consumerId }) => {
const consumer = consumers.value.get(consumerId)
if (!consumer)
return
consumer.resume()
triggerRef(consumers)
}) })
}, { immediate: true, flush: 'sync' }) }, { immediate: true, flush: 'sync' })
function getClientConsumers(clientId: ChadClient['id']) { async function enableProducer(type: ProducerType, options: ProducerOptions) {
return consumers.value.values().filter(consumer => consumer.appData.clientId === clientId) const producer = getProducerByType(type)
}
async function enableMic() { if (producer.value)
if (micProducer.value)
return return
if (!device.value || !sendTransport.value) if (!device.value || !sendTransport.value)
return return
if (!device.value.canProduce('audio')) if (!options.track)
return return
if (!device.value.canProduce(options.track.kind as MediaKind))
return
producer.value = await sendTransport.value.produce(options)
producers.value.set(producer.value.id, producer.value)
triggerRef(producers)
triggerRef(producer)
producer.value.on('transportclose', () => {
micProducer.value = undefined
})
producer.value.on('trackended', () => {
disableProducer(type)
})
}
async function disableProducer(type: ProducerType) {
const producer = getProducerByType(type)
if (!signaling.socket.value || !producer.value)
return
producers.value.delete(producer.value.id)
try {
producer.value.close()
await signaling.socket.value.emitWithAck('closeProducer', {
producerId: producer.value.id,
})
}
catch {
}
finally {
triggerRef(producers)
triggerRef(producer)
}
producer.value = undefined
}
async function enableMic() {
const stream = await navigator.mediaDevices.getUserMedia({ const stream = await navigator.mediaDevices.getUserMedia({
audio: { audio: {
autoGainControl: false, deviceId: { exact: preferences.inputDeviceId.value },
noiseSuppression: true, autoGainControl: { exact: preferences.autoGainControl.value },
echoCancellation: false, echoCancellation: { exact: preferences.echoCancellation.value },
channelCount: 2, noiseSuppression: { exact: preferences.noiseSuppression.value },
}, },
}) })
const track = stream.getAudioTracks()[0] const track = stream.getAudioTracks()[0]
if (!track) if (!track)
return return
micProducer.value = await sendTransport.value.produce({ await enableProducer('microphone', {
track, track,
codecOptions: { codecOptions: {
opusStereo: true, opusStereo: true,
@@ -231,66 +307,87 @@ export const useMediasoup = createSharedComposable(() => {
opusFec: false, // Фиксит пакет лос 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() { async function disableMic() {
if (!signaling.socket.value || !micProducer.value) await disableProducer('microphone')
return
producers.value.delete(micProducer.value.id)
triggerRef(producers)
try {
micProducer.value.close()
await signaling.socket.value.emitWithAck('closeProducer', {
producerId: micProducer.value.id,
})
}
catch {
}
micProducer.value = undefined
} }
async function muteMic() { async function enableShare() {
if (!signaling.socket.value || !micProducer.value) if (!device.value)
return
const stream = await getShareStream()
const track = stream.getVideoTracks()[0]
if (!track)
return
await enableProducer('share', {
track,
codec: device.value.rtpCapabilities.codecs?.find(
c => c.mimeType.toLowerCase() === 'video/h264',
),
codecOptions: {
videoGoogleStartBitrate: 1000,
},
appData: {
source: 'share',
},
})
}
async function pauseProducer(type: ProducerType) {
if (!signaling.socket.value)
return
const producer = getProducerByType(type)
if (!producer.value)
return
if (producer.value.paused)
return return
try { try {
micProducer.value.pause() producer.value.pause()
await signaling.socket.value.emitWithAck('pauseProducer', { await signaling.socket.value.emitWithAck('pauseProducer', {
producerId: micProducer.value.id, producerId: producer.value.id,
}) })
} }
catch { catch {
producer.value.resume()
}
finally {
triggerRef(producers)
triggerRef(producer)
} }
} }
async function unmuteMic() { async function resumeProducer(type: ProducerType) {
if (!signaling.socket.value || !micProducer.value) if (!signaling.socket.value)
return
const producer = getProducerByType(type)
if (!producer.value)
return return
try { try {
micProducer.value.resume() producer.value.resume()
await signaling.socket.value.emitWithAck('resumeProducer', { await signaling.socket.value.emitWithAck('resumeProducer', {
producerId: micProducer.value.id, producerId: producer.value.id,
}) })
} }
catch { catch {
producer.value.pause()
}
finally {
triggerRef(producers)
triggerRef(producer)
} }
} }
@@ -298,26 +395,30 @@ export const useMediasoup = createSharedComposable(() => {
signaling.connect() signaling.connect()
} }
function transformClient(client: RemoteClient): ChadClient { function getProducerByType(type: ProducerType) {
return { switch (type) {
...client, case 'microphone':
isMe: client.id === signaling.socket.value!.id, return micProducer
case 'camera':
return cameraProducer
case 'share':
return shareProducer
} }
} }
function dispose() { watch([
device.value = undefined preferences.inputDeviceId,
rtpCapabilities.value = undefined preferences.echoCancellation,
sendTransport.value = undefined preferences.autoGainControl,
recvTransport.value = undefined preferences.noiseSuppression,
], async ([inputDeviceId]) => {
await disableMic()
micProducer.value = undefined if (!inputDeviceId)
webcamProducer.value = undefined return
shareProducer.value = undefined
consumers.value = new Map() await enableMic()
producers.value = new Map() })
}
return { return {
init, init,
@@ -328,10 +429,11 @@ export const useMediasoup = createSharedComposable(() => {
rtpCapabilities, rtpCapabilities,
device, device,
micProducer, micProducer,
webcamProducer, cameraProducer,
shareProducer, shareProducer,
getClientConsumers, pauseProducer,
muteMic, resumeProducer,
unmuteMic, enableShare,
disableProducer,
} }
}) })

View File

@@ -1,14 +1,65 @@
import { createGlobalState, useLocalStorage } from '@vueuse/core' import chadApi from '#shared/chad-api'
import { createGlobalState, useLocalStorage, watchDebounced } from '@vueuse/core'
export interface SyncedPreferences {
toggleInputHotkey: string
toggleOutputHotkey: string
volumes: Record<Client['id'], number>
}
export const usePreferences = createGlobalState(() => { export const usePreferences = createGlobalState(() => {
const username = useLocalStorage<string>('username', '') const { videoInputs, audioInputs, audioOutputs } = useDevices()
const audioDevice = shallowRef() const synced = ref(false)
const videoDevice = shallowRef()
const inputDeviceId = useLocalStorage<MediaDeviceInfo['deviceId']>('INPUT_DEVICE_ID', 'default')
const outputDeviceId = useLocalStorage<MediaDeviceInfo['deviceId']>('OUTPUT_DEVICE_ID', 'default')
const autoGainControl = useLocalStorage('AUTO_GAIN_CONTROL', false)
const noiseSuppression = useLocalStorage('NOISE_SUPPRESSION', true)
const echoCancellation = useLocalStorage('ECHO_CANCELLATION', true)
const toggleInputHotkey = ref<SyncedPreferences['toggleInputHotkey']>('')
const toggleOutputHotkey = ref<SyncedPreferences['toggleOutputHotkey']>('')
const inputDeviceExist = computed(() => {
return audioInputs.value.some(device => device.deviceId === inputDeviceId.value)
})
const outputDeviceExist = computed(() => {
return audioOutputs.value.some(device => device.deviceId === outputDeviceId.value)
})
watchDebounced(
[toggleInputHotkey, toggleOutputHotkey],
async ([toggleInputHotkey, toggleOutputHotkey]) => {
try {
await chadApi(
'/preferences',
{
method: 'PATCH',
body: {
toggleInputHotkey,
toggleOutputHotkey,
},
},
)
}
catch {}
},
{ debounce: 1000 },
)
return { return {
username, synced,
audioDevice, inputDeviceId,
videoDevice, outputDeviceId,
autoGainControl,
noiseSuppression,
echoCancellation,
toggleInputHotkey,
toggleOutputHotkey,
inputDeviceExist,
outputDeviceExist,
} }
}) })

View File

@@ -1,9 +1,11 @@
import type { Socket } from 'socket.io-client' import type { Socket } from 'socket.io-client'
import { createSharedComposable } from '@vueuse/core' import { createSharedComposable } from '@vueuse/core'
import { io } from 'socket.io-client' import { io } from 'socket.io-client'
import { parseURL } from 'ufo'
export const useSignaling = createSharedComposable(() => { export const useSignaling = createSharedComposable(() => {
const toast = useToast() const toast = useToast()
const { me } = useAuth()
const socket = shallowRef<Socket>() const socket = shallowRef<Socket>()
@@ -44,18 +46,33 @@ export const useSignaling = createSharedComposable(() => {
toast.add({ severity: 'error', summary: 'Disconnected', closable: false, life: 1000 }) toast.add({ severity: 'error', summary: 'Disconnected', closable: false, life: 1000 })
}, { immediate: true }) }, { immediate: true })
watch(me, (me) => {
if (!me) {
socket.value?.close()
socket.value = undefined
}
})
onScopeDispose(() => { onScopeDispose(() => {
socket.value?.close() socket.value?.close()
socket.value = undefined
}) })
function connect() { function connect() {
if (socket.value) if (socket.value || !me.value)
return return
socket.value = io('https://api.koptilnya.xyz/webrtc', { const { protocol, host, pathname } = parseURL(__API_BASE_URL__)
// socket.value = io('http://127.0.0.1:4000/webrtc', {
path: '/chad/ws', const uri = host ? `${protocol}//${host}` : ``
socket.value = io(`${uri}/webrtc`, {
path: `${pathname}/ws`,
transports: ['websocket'], transports: ['websocket'],
withCredentials: true,
auth: {
userId: me.value.id,
},
}) })
} }

View File

@@ -0,0 +1,28 @@
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,
checking,
checkForUpdates,
}
})

7
client/app/index.d.ts vendored Normal file
View File

@@ -0,0 +1,7 @@
declare module '#app' {
interface PageMeta {
auth?: boolean | 'guest'
}
}
export {}

View File

@@ -1,5 +1,42 @@
<template> <template>
<div class="w-full h-full flex justify-center items-center p-3"> <div class="w-full h-full flex p-3">
<slot /> <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> </div>
<PrimeBadge class="fixed top-3 right-3 opacity-50" severity="secondary" :value="version" size="small" />
</template> </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>

View File

@@ -0,0 +1,3 @@
<template>
<slot />
</template>

View File

@@ -1,46 +1,125 @@
<template> <template>
<div v-auto-animate class="grid grid-cols-2 h-screen"> <div class="grid grid-cols-[1fr_1.25fr] gap-2 p-2 h-screen grid-rows-[auto_1fr]">
<div class="flex flex-col shadow-xl shadow-surface-950 overflow-y-hidden"> <div
<AppHeader title="Шальные сиськи 18+"> class="flex items-center justify-between gap-2 rounded-xl p-3 bg-surface-950"
<template #right> >
<PrimeButtonGroup class="ml-auto"> <div class="inline-flex items-center gap-3">
<PrimeButton <PrimeBadge class="opacity-50" severity="secondary" :value="version" size="small" />
icon="pi pi-microphone" size="large" :severity="inputMuted ? 'contrast' : 'secondary'" <PrimeBadge :severity="connected ? 'success' : 'danger' " />
: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>
<PrimeButtonGroup class="ml-auto">
<PrimeButton :severity="inputMuted ? 'info' : undefined" outlined @click="toggleInput">
<template #icon>
<Component :is="inputMuted ? MicOff : Mic" />
</template>
</PrimeButton>
<PrimeButton :severity="outputMuted ? 'info' : undefined" outlined @click="toggleOutput">
<template #icon>
<Component :is="outputMuted ? VolumeOff : Volume2" />
</template>
</PrimeButton>
</PrimeButtonGroup>
<PrimeButton :severity="sharingEnabled ? 'success' : undefined" outlined @click="toggleShare">
<template #icon>
<Component :is="sharingEnabled ? ScreenShareOff : ScreenShare" />
</template>
</PrimeButton>
</div> </div>
<slot /> <div
</div> class="flex items-center justify-center rounded-xl p-3 bg-surface-950"
>
<PrimeSelectButton
v-model="activeTab"
:options="tabs"
data-key="id"
:allow-empty="false"
style="--p-togglebutton-content-padding: 0.25rem 0.5rem"
>
<template #option="{ option }">
<Component :is="option.icon" size="24" />
</template>
</PrimeSelectButton>
</div>
<PrimeBadge class="fixed top-3 right-3" severity="success" /> <PrimeScrollPanel class="bg-surface-900 rounded-xl" style="min-height: 0">
<div v-auto-animate class="p-3 space-y-1">
<ClientRow v-for="client of clients" :key="client.userId" :client="client" />
</div>
</PrimeScrollPanel>
<PrimeScrollPanel class="bg-surface-900 rounded-xl" style="min-height: 0">
<div class="p-3">
<slot />
</div>
</PrimeScrollPanel>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { vAutoAnimate } from '@formkit/auto-animate' import {
MessageCircle,
Mic,
MicOff,
ScreenShare,
ScreenShareOff,
Settings,
UserPen,
Volume2,
VolumeOff,
} from 'lucide-vue-next'
const { clients, inputMuted, toggleInput, outputMuted, toggleOutput } = useApp() const {
version,
clients,
inputMuted,
outputMuted,
sharingEnabled,
toggleInput,
toggleOutput,
toggleShare,
} = useApp()
const { connect, connected } = useSignaling()
interface Tab {
id: string
icon: Component
onClick: () => void | Promise<void>
}
const route = useRoute() const route = useRoute()
const inPreferences = computed(() => { const tabs: Tab[] = [
return route.name === 'Preferences' {
id: 'Index',
icon: MessageCircle,
onClick: () => {
navigateTo({ name: 'Index' })
},
},
{
id: 'Profile',
icon: UserPen,
onClick: () => {
navigateTo({ name: 'Profile' })
},
},
{
id: 'Preferences',
icon: Settings,
onClick: () => {
navigateTo({ name: 'Preferences' })
},
},
]
const activeTab = ref<Tab>(tabs.find(tab => tab.id === route.name) ?? tabs[0]!)
watch(activeTab, (activeTab) => {
activeTab.onClick()
}) })
function onClickPreferences() { connect()
navigateTo(!inPreferences.value ? { name: 'Preferences' } : '/')
}
</script> </script>

View 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 || !!to.redirectedFrom)
return
const { checkForUpdates } = useUpdater()
const update = await checkForUpdates()
if (update) {
return navigateTo({ name: 'Updater' })
}
})

View File

@@ -0,0 +1,23 @@
import chadApi from '#shared/chad-api'
export default defineNuxtRouteMiddleware(async (to, from) => {
const { me, setMe } = useAuth()
if (!me.value) {
try {
setMe(await chadApi('/me', { method: 'GET' }))
if (to.meta.auth !== false)
return navigateTo({ name: 'Index' })
}
catch {
if (to.meta.auth !== 'guest') {
return navigateTo({ name: 'Login' })
}
}
}
if (me.value && to.meta.auth === 'guest') {
return navigateTo({ name: 'Index' })
}
})

View File

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

View File

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

View File

@@ -0,0 +1,26 @@
import type { SyncedPreferences } from '~/composables/use-preferences'
import chadApi from '#shared/chad-api'
export default defineNuxtRouteMiddleware(async () => {
const { me } = useAuth()
if (!me.value)
return
const { synced, toggleInputHotkey, toggleOutputHotkey } = usePreferences()
if (synced.value)
return
try {
const preferences = await chadApi<SyncedPreferences>('/preferences', { method: 'GET' })
if (!preferences)
return
toggleInputHotkey.value = preferences.toggleInputHotkey ?? toggleInputHotkey.value
toggleOutputHotkey.value = preferences.toggleOutputHotkey ?? toggleOutputHotkey.value
synced.value = true
}
catch {}
})

View File

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

View File

@@ -1,13 +1,30 @@
<template> <template>
<PrimeCard class="w-2/5"> <PrimeCard>
<template #content> <template #content>
<form class="flex flex-col gap-3" @submit.prevent="submit"> <form @submit.prevent="submit">
<PrimeFloatLabel variant="on"> <div class="flex flex-col gap-3">
<PrimeInputText id="username" v-model="localUsername" size="large" class="w-full" /> <PrimeFloatLabel variant="on">
<label for="username">Username</label> <PrimeInputText id="username" v-model="username" size="large" autocomplete="off" fluid autofocus />
</PrimeFloatLabel> <label for="username">Username</label>
</PrimeFloatLabel>
<PrimeButton size="large" icon="pi pi-arrow-right" icon-pos="right" label="Let's go" :disabled="!localUsername" type="submit" /> <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> </form>
</template> </template>
</PrimeCard> </PrimeCard>
@@ -17,18 +34,34 @@
definePageMeta({ definePageMeta({
name: 'Login', name: 'Login',
layout: 'auth', layout: 'auth',
auth: 'guest',
}) })
const { username } = usePreferences() const { login } = useAuth()
const localUsername = ref<typeof username.value>() 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() { async function submit() {
if (!localUsername.value) if (!valid.value)
return return
username.value = localUsername.value submitting.value = true
await navigateTo('/') await login(username.value!, password.value!)
submitting.value = false
} }
</script> </script>

View File

@@ -1,39 +1,161 @@
<template> <template>
<div> <div>
<AppHeader title="Preferences" secondary /> <PrimeDivider align="left">
Audio
</PrimeDivider>
<PrimeFloatLabel variant="on">
<PrimeSelect
v-model="inputDeviceId"
:options="audioInputs"
option-label="label"
option-value="deviceId"
input-id="inputDevice"
fluid
:invalid="!inputDeviceExist"
/>
<label for="inputDevice">Input device</label>
</PrimeFloatLabel>
<div class="flex items-center gap-2 mt-3">
<PrimeToggleSwitch v-model="autoGainControl" input-id="autoGainControl" />
<label for="autoGainControl">Auto Gain Control</label>
</div>
<div class="flex items-center gap-2 mt-3">
<PrimeToggleSwitch v-model="echoCancellation" input-id="echoCancellation" />
<label for="echoCancellation">Echo Cancellation</label>
</div>
<div class="flex items-center gap-2 mt-3">
<PrimeToggleSwitch v-model="noiseSuppression" input-id="noiseSuppression" />
<label for="noiseSuppression">Noise Suppression</label>
</div>
<!-- <PrimeFloatLabel variant="on"> -->
<!-- <PrimeSelect -->
<!-- v-model="outputDeviceId" -->
<!-- :options="audioOutputs" -->
<!-- option-label="label" -->
<!-- option-value="deviceId" -->
<!-- fluid -->
<!-- class="mt-6" -->
<!-- input-id="outputDevice" -->
<!-- :invalid="!outputDeviceExist" -->
<!-- -->
<!-- /> -->
<!-- <label for="outputDevice">Output device</label> -->
<!-- </PrimeFloatLabel> -->
<template v-if="isTauri">
<PrimeDivider align="left">
Hotkeys
</PrimeDivider>
<form class="flex flex-col gap-3 p-3" @submit.prevent="save">
<PrimeFloatLabel variant="on"> <PrimeFloatLabel variant="on">
<PrimeInputText id="username" v-model="localUsername" size="large" class="w-full" /> <PrimeInputText id="microphoneToggle" :model-value="toggleInputHotkey" fluid @keydown="setupToggleInputHotkey" />
<label for="username">Username</label> <label for="microphoneToggle">Toggle microphone</label>
</PrimeFloatLabel> </PrimeFloatLabel>
<PrimeButton label="Save" type="submit" :disabled="!localUsername || localUsername === username" /> <PrimeFloatLabel variant="on" class="mt-3">
</form> <PrimeInputText id="soundToggle" :model-value="toggleOutputHotkey" fluid @keydown="setupToggleOutputHotkey" />
<label for="soundToggle">Toggle sound</label>
</PrimeFloatLabel>
</template>
<PrimeDivider align="left">
About
</PrimeDivider>
<p v-if="version" class="text-muted-color text-sm">
VERSION: {{ version }}
</p>
<p class="text-muted-color text-sm mt-2">
COMMIT_SHA: {{ commitSha }}
</p>
<template v-if="isTauri">
<PrimeButton
v-if="lastUpdate"
class="mt-3"
size="small"
label="Install new version"
fluid
severity="success"
@click="navigateTo({ name: 'Updater' })"
/>
<PrimeButton
v-else
class="mt-3"
size="small"
label="Check for Updates"
fluid
severity="info"
:loading="checking"
@click="checkForUpdates"
/>
</template>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import type { RemovableRef } from '@vueuse/core'
definePageMeta({ definePageMeta({
name: 'Preferences', name: 'Preferences',
}) })
const { isTauri, version, commitSha } = useApp()
const { checking, checkForUpdates, lastUpdate } = useUpdater()
const { audioInputs, audioOutputs } = useDevices()
const {
inputDeviceId,
outputDeviceId,
autoGainControl,
noiseSuppression,
echoCancellation,
toggleInputHotkey,
toggleOutputHotkey,
inputDeviceExist,
outputDeviceExist,
} = usePreferences()
const signaling = useSignaling() const setupToggleInputHotkey = (event: KeyboardEvent) => setupHotkey(event, toggleInputHotkey)
const { username } = usePreferences() const setupToggleOutputHotkey = (event: KeyboardEvent) => setupHotkey(event, toggleOutputHotkey)
const toast = useToast()
const localUsername = ref(username.value) function setupHotkey(event: KeyboardEvent, model: RemovableRef<string>) {
if (event.key === 'Tab' || event.key === 'Enter') {
async function save() {
if (!localUsername.value || localUsername.value === username.value)
return return
}
username.value = localUsername.value event.preventDefault()
await signaling.socket.value?.emitWithAck('updateClient', { const hotkey = []
username: username.value,
})
toast.add({ severity: 'success', summary: 'Saved', life: 1000, closable: false }) if (event.ctrlKey || event.metaKey)
hotkey.push('CommandOrControl')
if (event.altKey)
hotkey.push('Alt')
if (event.shiftKey)
hotkey.push('Shift')
const modifierApplied = hotkey.length > 0
if (!modifierApplied && ['Escape', 'Backspace', 'Delete'].includes(event.key)) {
model.value = ''
return
}
if (!['Control', 'Shift', 'Alt'].includes(event.key)) {
hotkey.push(event.key.toUpperCase())
}
if (modifierApplied && hotkey.length === 1) {
model.value = ''
return
}
model.value = hotkey.join('+')
} }
</script> </script>

View File

@@ -0,0 +1,68 @@
<template>
<form @submit.prevent="save()">
<PrimeDivider align="left">
General
</PrimeDivider>
<PrimeFloatLabel variant="on">
<PrimeInputText id="displayName" v-model="displayName" fluid autocomplete="off" />
<label for="displayName">Display name</label>
</PrimeFloatLabel>
<div class="flex items-center gap-3 mt-6">
<PrimeButton label="Save" :disabled="!valid" :loading="saving" fluid type="submit" />
<PrimeButton severity="danger" class="shrink-0" @click="logout()">
<template #icon>
<LogOut />
</template>
</PrimeButton>
</div>
</form>
</template>
<script setup lang="ts">
import chadApi from '#shared/chad-api'
import { LogOut } from 'lucide-vue-next'
definePageMeta({
name: 'Profile',
})
const { me, setMe, logout } = useAuth()
const signaling = useSignaling()
const toast = useToast()
const displayName = ref(me.value?.displayName || '')
const saving = ref(false)
const valid = computed(() => {
if (!me.value)
return false
if (displayName.value === me.value.displayName)
return false
return true
})
async function save() {
if (!valid.value)
return
saving.value = true
const updatedMe = await chadApi('/profile', {
method: 'PATCH',
body: {
displayName: displayName.value,
},
})
setMe({ ...me.value!, displayName: (updatedMe.displayName as string) })
toast.add({ severity: 'success', summary: 'Saved', life: 1000, closable: false })
saving.value = false
}
</script>

View 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>

View File

@@ -0,0 +1,41 @@
<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>

View File

@@ -0,0 +1,7 @@
export default defineNuxtPlugin({
setup() {
console.group('Build Info')
console.log(`COMMIT_SHA: ${__COMMIT_SHA__}`)
console.groupEnd()
},
})

View File

@@ -0,0 +1,45 @@
import { isRegistered, register, unregister, unregisterAll } from '@tauri-apps/plugin-global-shortcut'
export default defineNuxtPlugin({
async setup() {
const { isTauri, toggleInput, toggleOutput } = useApp()
const preferences = usePreferences()
if (!isTauri.value)
return
await unregisterAll()
watch(preferences.toggleInputHotkey, async (shortcut, prevShortcut) => {
await registerHotkey(shortcut, prevShortcut, toggleInput)
}, {
immediate: true,
})
watch(preferences.toggleOutputHotkey, async (shortcut, prevShortcut) => {
await registerHotkey(shortcut, prevShortcut, toggleOutput)
}, {
immediate: true,
})
async function registerHotkey(shortcut: string, prevShortcut: string | undefined, cb: () => void) {
if (!!prevShortcut && await isRegistered(prevShortcut)) {
await unregister(prevShortcut)
}
if (!shortcut)
return
if (await isRegistered(shortcut)) {
await unregister(shortcut)
}
await register(shortcut, ({ state }) => {
if (state !== 'Released')
return
cb()
})
}
},
})

1
client/globals.d.ts vendored
View File

@@ -1 +1,2 @@
declare const __API_BASE_URL__: string
declare const __COMMIT_SHA__: string declare const __COMMIT_SHA__: string

View File

@@ -1,3 +1,4 @@
import { definePreset } from '@primeuix/themes'
import Aura from '@primeuix/themes/aura' import Aura from '@primeuix/themes/aura'
import tailwindcss from '@tailwindcss/vite' import tailwindcss from '@tailwindcss/vite'
@@ -8,11 +9,62 @@ export default defineNuxtConfig({
modules: [ modules: [
'@nuxt/fonts', '@nuxt/fonts',
'@primevue/nuxt-module', '@primevue/nuxt-module',
'@formkit/auto-animate/nuxt',
], ],
fonts: {
provider: 'google',
},
primevue: { primevue: {
options: { options: {
theme: { theme: {
preset: Aura, 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: { components: {
@@ -24,9 +76,6 @@ export default defineNuxtConfig({
'@/assets/styles/primeicons.css', '@/assets/styles/primeicons.css',
'@/assets/styles/main.scss', '@/assets/styles/main.scss',
], ],
devServer: {
// host: '0',
},
vite: { vite: {
plugins: [ plugins: [
tailwindcss(), tailwindcss(),
@@ -35,9 +84,21 @@ export default defineNuxtConfig({
envPrefix: ['VITE_', 'TAURI_'], envPrefix: ['VITE_', 'TAURI_'],
server: { server: {
strictPort: true, 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: { define: {
__COMMIT_SHA__: JSON.stringify(process.env.COMMIT_SHA || 'local'), __API_BASE_URL__: JSON.stringify(import.meta.env.API_BASE_URL || 'http://localhost:4000/chad'),
__COMMIT_SHA__: JSON.stringify(import.meta.env.COMMIT_SHA || 'local'),
}, },
}, },
ignore: ['**/src-tauri/**'], ignore: ['**/src-tauri/**'],

View File

@@ -14,19 +14,25 @@
"@nuxt/fonts": "^0.11.4", "@nuxt/fonts": "^0.11.4",
"@primeuix/themes": "^1.2.5", "@primeuix/themes": "^1.2.5",
"@tailwindcss/vite": "^4.1.14", "@tailwindcss/vite": "^4.1.14",
"@tauri-apps/plugin-global-shortcut": "~2",
"@tauri-apps/plugin-process": "~2",
"@tauri-apps/plugin-updater": "~2",
"@vueuse/core": "^13.9.0", "@vueuse/core": "^13.9.0",
"hotkeys-js": "^4.0.0",
"lucide-vue-next": "^0.562.0",
"mediasoup-client": "^3.16.7", "mediasoup-client": "^3.16.7",
"nuxt": "^4.1.2", "nuxt": "^4.2.2",
"postcss": "^8.5.6", "postcss": "^8.5.6",
"primeicons": "^7.0.0", "primeicons": "^7.0.0",
"primevue": "^4.4.0", "primevue": "^4.4.0",
"socket.io-client": "^4.8.1", "socket.io-client": "^4.8.1",
"tailwindcss": "^4.1.14", "tailwindcss": "^4.1.14",
"tailwindcss-primeui": "^0.6.1", "tailwindcss-primeui": "^0.6.1",
"ufo": "^1.6.1",
"vue": "^3.5.22", "vue": "^3.5.22",
"vue-router": "^4.5.1" "vue-router": "^4.5.1"
}, },
"packageManager": "yarn@4.10.3", "packageManager": "yarn@4.12.0",
"devDependencies": { "devDependencies": {
"@antfu/eslint-config": "^5.4.1", "@antfu/eslint-config": "^5.4.1",
"@primevue/nuxt-module": "^4.4.0", "@primevue/nuxt-module": "^4.4.0",

BIN
client/public/chad-bg.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

View 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')

View File

@@ -0,0 +1,4 @@
export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('render:html', (html, { event }) => {
})
})

64
client/shared/chad-api.ts Normal file
View File

@@ -0,0 +1,64 @@
import { ToastEventBus } from 'primevue'
const instance = $fetch.create({
baseURL: __API_BASE_URL__,
credentials: 'include',
retry: false,
onResponseError({ request, response }) {
if (!import.meta.client)
return
if (typeof request === 'string' && request.endsWith('/me'))
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

View File

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

View File

@@ -93,8 +93,20 @@ dependencies = [
"serde_json", "serde_json",
"tauri", "tauri",
"tauri-build", "tauri-build",
"tauri-plugin-global-shortcut",
"tauri-plugin-log", "tauri-plugin-log",
"tauri-plugin-process",
"tauri-plugin-single-instance", "tauri-plugin-single-instance",
"tauri-plugin-updater",
]
[[package]]
name = "arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
dependencies = [
"derive_arbitrary",
] ]
[[package]] [[package]]
@@ -281,7 +293,7 @@ dependencies = [
"miniz_oxide", "miniz_oxide",
"object", "object",
"rustc-demangle", "rustc-demangle",
"windows-link 0.2.0", "windows-link 0.2.1",
] ]
[[package]] [[package]]
@@ -592,7 +604,7 @@ dependencies = [
"iana-time-zone", "iana-time-zone",
"num-traits", "num-traits",
"serde", "serde",
"windows-link 0.2.0", "windows-link 0.2.1",
] ]
[[package]] [[package]]
@@ -795,6 +807,17 @@ dependencies = [
"serde_core", "serde_core",
] ]
[[package]]
name = "derive_arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.106",
]
[[package]] [[package]]
name = "derive_more" name = "derive_more"
version = "0.99.20" version = "0.99.20"
@@ -1064,6 +1087,18 @@ dependencies = [
"rustc_version", "rustc_version",
] ]
[[package]]
name = "filetime"
version = "0.2.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc0505cd1b6fa6580283f6bdf70a73fcf4aba1184038c90902b92b3dd0df63ed"
dependencies = [
"cfg-if",
"libc",
"libredox",
"windows-sys 0.60.2",
]
[[package]] [[package]]
name = "find-msvc-tools" name = "find-msvc-tools"
version = "0.1.2" version = "0.1.2"
@@ -1341,6 +1376,16 @@ dependencies = [
"version_check", "version_check",
] ]
[[package]]
name = "gethostname"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
dependencies = [
"rustix",
"windows-link 0.2.1",
]
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.1.16" version = "0.1.16"
@@ -1359,8 +1404,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys",
"libc", "libc",
"wasi 0.11.1+wasi-snapshot-preview1", "wasi 0.11.1+wasi-snapshot-preview1",
"wasm-bindgen",
] ]
[[package]] [[package]]
@@ -1370,9 +1417,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys",
"libc", "libc",
"r-efi", "r-efi",
"wasi 0.14.7+wasi-0.2.4", "wasi 0.14.7+wasi-0.2.4",
"wasm-bindgen",
] ]
[[package]] [[package]]
@@ -1466,6 +1515,24 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]]
name = "global-hotkey"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9247516746aa8e53411a0db9b62b0e24efbcf6a76e0ba73e5a91b512ddabed7"
dependencies = [
"crossbeam-channel",
"keyboard-types",
"objc2 0.6.2",
"objc2-app-kit",
"once_cell",
"serde",
"thiserror 2.0.17",
"windows-sys 0.59.0",
"x11rb",
"xkeysym",
]
[[package]] [[package]]
name = "gobject-sys" name = "gobject-sys"
version = "0.18.0" version = "0.18.0"
@@ -1641,6 +1708,23 @@ dependencies = [
"want", "want",
] ]
[[package]]
name = "hyper-rustls"
version = "0.27.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58"
dependencies = [
"http",
"hyper",
"hyper-util",
"rustls",
"rustls-pki-types",
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots",
]
[[package]] [[package]]
name = "hyper-util" name = "hyper-util"
version = "0.1.17" version = "0.1.17"
@@ -2031,6 +2115,7 @@ checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb"
dependencies = [ dependencies = [
"bitflags 2.9.4", "bitflags 2.9.4",
"libc", "libc",
"redox_syscall",
] ]
[[package]] [[package]]
@@ -2064,6 +2149,12 @@ dependencies = [
"value-bag", "value-bag",
] ]
[[package]]
name = "lru-slab"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
[[package]] [[package]]
name = "mac" name = "mac"
version = "0.1.1" version = "0.1.1"
@@ -2122,6 +2213,12 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "minisign-verify"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e856fdd13623a2f5f2f54676a4ee49502a96a80ef4a62bcedd23d52427c44d43"
[[package]] [[package]]
name = "miniz_oxide" name = "miniz_oxide"
version = "0.8.9" version = "0.8.9"
@@ -2439,6 +2536,18 @@ dependencies = [
"objc2-foundation 0.2.2", "objc2-foundation 0.2.2",
] ]
[[package]]
name = "objc2-osa-kit"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26bb88504b5a050dbba515d2414607bf5e57dd56b107bc5f0351197a3e7bdc5d"
dependencies = [
"bitflags 2.9.4",
"objc2 0.6.2",
"objc2-app-kit",
"objc2-foundation 0.3.1",
]
[[package]] [[package]]
name = "objc2-quartz-core" name = "objc2-quartz-core"
version = "0.2.2" version = "0.2.2"
@@ -2533,6 +2642,20 @@ dependencies = [
"pin-project-lite", "pin-project-lite",
] ]
[[package]]
name = "osakit"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"
dependencies = [
"objc2 0.6.2",
"objc2-foundation 0.3.1",
"objc2-osa-kit",
"serde",
"serde_json",
"thiserror 2.0.17",
]
[[package]] [[package]]
name = "pango" name = "pango"
version = "0.18.3" version = "0.18.3"
@@ -2923,6 +3046,61 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "quinn"
version = "0.11.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
dependencies = [
"bytes",
"cfg_aliases",
"pin-project-lite",
"quinn-proto",
"quinn-udp",
"rustc-hash",
"rustls",
"socket2",
"thiserror 2.0.17",
"tokio",
"tracing",
"web-time",
]
[[package]]
name = "quinn-proto"
version = "0.11.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31"
dependencies = [
"bytes",
"getrandom 0.3.3",
"lru-slab",
"rand 0.9.2",
"ring",
"rustc-hash",
"rustls",
"rustls-pki-types",
"slab",
"thiserror 2.0.17",
"tinyvec",
"tracing",
"web-time",
]
[[package]]
name = "quinn-udp"
version = "0.5.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2",
"tracing",
"windows-sys 0.60.2",
]
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.41" version = "1.0.41"
@@ -2969,6 +3147,16 @@ dependencies = [
"rand_core 0.6.4", "rand_core 0.6.4",
] ]
[[package]]
name = "rand"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
dependencies = [
"rand_chacha 0.9.0",
"rand_core 0.9.3",
]
[[package]] [[package]]
name = "rand_chacha" name = "rand_chacha"
version = "0.2.2" version = "0.2.2"
@@ -2989,6 +3177,16 @@ dependencies = [
"rand_core 0.6.4", "rand_core 0.6.4",
] ]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core 0.9.3",
]
[[package]] [[package]]
name = "rand_core" name = "rand_core"
version = "0.5.1" version = "0.5.1"
@@ -3007,6 +3205,15 @@ dependencies = [
"getrandom 0.2.16", "getrandom 0.2.16",
] ]
[[package]]
name = "rand_core"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"
dependencies = [
"getrandom 0.3.3",
]
[[package]] [[package]]
name = "rand_hc" name = "rand_hc"
version = "0.2.0" version = "0.2.0"
@@ -3123,16 +3330,21 @@ dependencies = [
"http-body", "http-body",
"http-body-util", "http-body-util",
"hyper", "hyper",
"hyper-rustls",
"hyper-util", "hyper-util",
"js-sys", "js-sys",
"log", "log",
"percent-encoding", "percent-encoding",
"pin-project-lite", "pin-project-lite",
"quinn",
"rustls",
"rustls-pki-types",
"serde", "serde",
"serde_json", "serde_json",
"serde_urlencoded", "serde_urlencoded",
"sync_wrapper", "sync_wrapper",
"tokio", "tokio",
"tokio-rustls",
"tokio-util", "tokio-util",
"tower", "tower",
"tower-http", "tower-http",
@@ -3142,6 +3354,21 @@ dependencies = [
"wasm-bindgen-futures", "wasm-bindgen-futures",
"wasm-streams", "wasm-streams",
"web-sys", "web-sys",
"webpki-roots",
]
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.16",
"libc",
"untrusted",
"windows-sys 0.52.0",
] ]
[[package]] [[package]]
@@ -3195,6 +3422,12 @@ version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace"
[[package]]
name = "rustc-hash"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]] [[package]]
name = "rustc_version" name = "rustc_version"
version = "0.4.1" version = "0.4.1"
@@ -3217,6 +3450,41 @@ dependencies = [
"windows-sys 0.61.1", "windows-sys 0.61.1",
] ]
[[package]]
name = "rustls"
version = "0.23.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "751e04a496ca00bb97a5e043158d23d66b5aabf2e1d5aa2a0aaebb1aafe6f82c"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pki-types"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "229a4a4c221013e7e1f1a043678c5cc39fe5171437c88fb47151a21e6f5b5c79"
dependencies = [
"web-time",
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e10b3f4191e8a80e6b43eebabfac91e5dcecebb27a71f04e820c47ec41d314bf"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]] [[package]]
name = "rustversion" name = "rustversion"
version = "1.0.22" version = "1.0.22"
@@ -3663,6 +3931,12 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]] [[package]]
name = "swift-rs" name = "swift-rs"
version = "1.0.7" version = "1.0.7"
@@ -3786,6 +4060,17 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tar"
version = "0.4.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a"
dependencies = [
"filetime",
"libc",
"xattr",
]
[[package]] [[package]]
name = "target-lexicon" name = "target-lexicon"
version = "0.12.16" version = "0.12.16"
@@ -3924,6 +4209,21 @@ dependencies = [
"walkdir", "walkdir",
] ]
[[package]]
name = "tauri-plugin-global-shortcut"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "424af23c7e88d05e4a1a6fc2c7be077912f8c76bd7900fd50aa2b7cbf5a2c405"
dependencies = [
"global-hotkey",
"log",
"serde",
"serde_json",
"tauri",
"tauri-plugin",
"thiserror 2.0.17",
]
[[package]] [[package]]
name = "tauri-plugin-log" name = "tauri-plugin-log"
version = "2.7.0" version = "2.7.0"
@@ -3946,6 +4246,16 @@ dependencies = [
"time", "time",
] ]
[[package]]
name = "tauri-plugin-process"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7461c622a5ea00eb9cd9f7a08dbd3bf79484499fd5c21aa2964677f64ca651ab"
dependencies = [
"tauri",
"tauri-plugin",
]
[[package]] [[package]]
name = "tauri-plugin-single-instance" name = "tauri-plugin-single-instance"
version = "2.3.4" version = "2.3.4"
@@ -3961,6 +4271,38 @@ dependencies = [
"zbus", "zbus",
] ]
[[package]]
name = "tauri-plugin-updater"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27cbc31740f4d507712550694749572ec0e43bdd66992db7599b89fbfd6b167b"
dependencies = [
"base64 0.22.1",
"dirs",
"flate2",
"futures-util",
"http",
"infer",
"log",
"minisign-verify",
"osakit",
"percent-encoding",
"reqwest",
"semver",
"serde",
"serde_json",
"tar",
"tauri",
"tauri-plugin",
"tempfile",
"thiserror 2.0.17",
"time",
"tokio",
"url",
"windows-sys 0.60.2",
"zip",
]
[[package]] [[package]]
name = "tauri-runtime" name = "tauri-runtime"
version = "2.8.0" version = "2.8.0"
@@ -4200,6 +4542,16 @@ dependencies = [
"windows-sys 0.59.0", "windows-sys 0.59.0",
] ]
[[package]]
name = "tokio-rustls"
version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
dependencies = [
"rustls",
"tokio",
]
[[package]] [[package]]
name = "tokio-util" name = "tokio-util"
version = "0.7.16" version = "0.7.16"
@@ -4489,6 +4841,12 @@ version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]] [[package]]
name = "url" name = "url"
version = "2.5.7" version = "2.5.7"
@@ -4725,6 +5083,16 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "web-time"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]] [[package]]
name = "webkit2gtk" name = "webkit2gtk"
version = "2.0.1" version = "2.0.1"
@@ -4769,6 +5137,15 @@ dependencies = [
"system-deps", "system-deps",
] ]
[[package]]
name = "webpki-roots"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32b130c0d2d49f8b6889abc456e795e82525204f27c42cf767cf0d7734e089b8"
dependencies = [
"rustls-pki-types",
]
[[package]] [[package]]
name = "webview2-com" name = "webview2-com"
version = "0.38.0" version = "0.38.0"
@@ -4894,7 +5271,7 @@ checksum = "6844ee5416b285084d3d3fffd743b925a6c9385455f64f6d4fa3031c4c2749a9"
dependencies = [ dependencies = [
"windows-implement", "windows-implement",
"windows-interface", "windows-interface",
"windows-link 0.2.0", "windows-link 0.2.1",
"windows-result 0.4.0", "windows-result 0.4.0",
"windows-strings 0.5.0", "windows-strings 0.5.0",
] ]
@@ -4940,9 +5317,9 @@ checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
[[package]] [[package]]
name = "windows-link" name = "windows-link"
version = "0.2.0" version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]] [[package]]
name = "windows-numerics" name = "windows-numerics"
@@ -4969,7 +5346,7 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7084dcc306f89883455a206237404d3eaf961e5bd7e0f312f7c91f57eb44167f" checksum = "7084dcc306f89883455a206237404d3eaf961e5bd7e0f312f7c91f57eb44167f"
dependencies = [ dependencies = [
"windows-link 0.2.0", "windows-link 0.2.1",
] ]
[[package]] [[package]]
@@ -4987,7 +5364,7 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7218c655a553b0bed4426cf54b20d7ba363ef543b52d515b3e48d7fd55318dda" checksum = "7218c655a553b0bed4426cf54b20d7ba363ef543b52d515b3e48d7fd55318dda"
dependencies = [ dependencies = [
"windows-link 0.2.0", "windows-link 0.2.1",
] ]
[[package]] [[package]]
@@ -4999,6 +5376,15 @@ dependencies = [
"windows-targets 0.42.2", "windows-targets 0.42.2",
] ]
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.6",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.59.0" version = "0.59.0"
@@ -5023,7 +5409,7 @@ version = "0.61.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f109e41dd4a3c848907eb83d5a42ea98b3769495597450cf6d153507b166f0f" checksum = "6f109e41dd4a3c848907eb83d5a42ea98b3769495597450cf6d153507b166f0f"
dependencies = [ dependencies = [
"windows-link 0.2.0", "windows-link 0.2.1",
] ]
[[package]] [[package]]
@@ -5063,7 +5449,7 @@ version = "0.53.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d42b7b7f66d2a06854650af09cfdf8713e427a439c97ad65a6375318033ac4b" checksum = "2d42b7b7f66d2a06854650af09cfdf8713e427a439c97ad65a6375318033ac4b"
dependencies = [ dependencies = [
"windows-link 0.2.0", "windows-link 0.2.1",
"windows_aarch64_gnullvm 0.53.0", "windows_aarch64_gnullvm 0.53.0",
"windows_aarch64_msvc 0.53.0", "windows_aarch64_msvc 0.53.0",
"windows_i686_gnu 0.53.0", "windows_i686_gnu 0.53.0",
@@ -5089,7 +5475,7 @@ version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "700dad7c058606087f6fdc1f88da5841e06da40334413c6cd4367b25ef26d24e" checksum = "700dad7c058606087f6fdc1f88da5841e06da40334413c6cd4367b25ef26d24e"
dependencies = [ dependencies = [
"windows-link 0.2.0", "windows-link 0.2.1",
] ]
[[package]] [[package]]
@@ -5345,6 +5731,39 @@ dependencies = [
"pkg-config", "pkg-config",
] ]
[[package]]
name = "x11rb"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"
dependencies = [
"gethostname",
"rustix",
"x11rb-protocol",
]
[[package]]
name = "x11rb-protocol"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
[[package]]
name = "xattr"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix",
]
[[package]]
name = "xkeysym"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
[[package]] [[package]]
name = "yoke" name = "yoke"
version = "0.8.0" version = "0.8.0"
@@ -5470,6 +5889,12 @@ dependencies = [
"synstructure", "synstructure",
] ]
[[package]]
name = "zeroize"
version = "1.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
[[package]] [[package]]
name = "zerotrie" name = "zerotrie"
version = "0.2.2" version = "0.2.2"
@@ -5503,6 +5928,18 @@ dependencies = [
"syn 2.0.106", "syn 2.0.106",
] ]
[[package]]
name = "zip"
version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
dependencies = [
"arbitrary",
"crc32fast",
"indexmap 2.11.4",
"memchr",
]
[[package]] [[package]]
name = "zvariant" name = "zvariant"
version = "5.7.0" version = "5.7.0"

View File

@@ -23,6 +23,9 @@ serde = { version = "1.0", features = ["derive"] }
log = "0.4" log = "0.4"
tauri = { version = "2.8.5", features = [] } tauri = { version = "2.8.5", features = [] }
tauri-plugin-log = "2" tauri-plugin-log = "2"
tauri-plugin-process = "2"
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies] [target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-global-shortcut = "2"
tauri-plugin-single-instance = "2" tauri-plugin-single-instance = "2"
tauri-plugin-updater = "2"

View File

@@ -0,0 +1,18 @@
{
"identifier": "desktop-capability",
"platforms": [
"macOS",
"windows",
"linux"
],
"windows": [
"main"
],
"permissions": [
"updater:default",
"global-shortcut:allow-is-registered",
"global-shortcut:allow-register",
"global-shortcut:allow-unregister",
"global-shortcut:allow-unregister-all"
]
}

View File

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

View File

@@ -1,7 +1,7 @@
{ {
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "chad", "productName": "chad",
"version": "0.1.0", "version": "0.2.19",
"identifier": "xyz.koptilnya.chad", "identifier": "xyz.koptilnya.chad",
"build": { "build": {
"frontendDist": "../.output/public", "frontendDist": "../.output/public",
@@ -21,7 +21,8 @@
"fullscreen": false, "fullscreen": false,
"center": true, "center": true,
"theme": "Dark", "theme": "Dark",
"additionalBrowserArgs": "--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection --autoplay-policy=no-user-gesture-required" "additionalBrowserArgs": "--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection --autoplay-policy=no-user-gesture-required",
"incognito": false
} }
], ],
"security": { "security": {
@@ -30,6 +31,7 @@
} }
}, },
"bundle": { "bundle": {
"createUpdaterArtifacts": true,
"active": true, "active": true,
"targets": ["nsis"], "targets": ["nsis"],
"icon": [ "icon": [
@@ -39,5 +41,13 @@
"icons/icon.icns", "icons/icon.icns",
"icons/icon.ico" "icons/icon.ico"
] ]
},
"plugins": {
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEU3MzkxMzM3RkQ3NTg4QUQKUldTdGlIWDlOeE01NStIak9VbmZTTm9HY2NyNUQrVXB5ZEdIN1BkK2lhYW9zWkNCQnZQSjRmelIK",
"endpoints": [
"https://git.koptilnya.xyz/opti1337/chad/releases/download/latest/updater.json"
]
}
} }
} }

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -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 || 4000, () => {
consola.success('[Server]', 'Server started!')
})
})()

View File

@@ -4,17 +4,19 @@
"start": "ts-node --transpile-only server.ts", "start": "ts-node --transpile-only server.ts",
"db:deploy": "npx prisma migrate deploy && npx prisma generate" "db:deploy": "npx prisma migrate deploy && npx prisma generate"
}, },
"type": "module",
"packageManager": "yarn@4.10.3", "packageManager": "yarn@4.10.3",
"dependencies": { "dependencies": {
"@fastify/autoload": "^6.3.1",
"@fastify/cookie": "^11.0.2",
"@fastify/cors": "^11.1.0",
"@lucia-auth/adapter-prisma": "^4.0.1", "@lucia-auth/adapter-prisma": "^4.0.1",
"@prisma/client": "^6.17.0", "@prisma/client": "^6.17.0",
"@trpc/server": "^11.6.0",
"bcrypt": "^6.0.0", "bcrypt": "^6.0.0",
"consola": "^3.4.2", "consola": "^3.4.2",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"dotenv": "^17.2.3", "dotenv": "^17.2.3",
"express": "^5.1.0", "fastify": "^5.6.1",
"fastify-plugin": "^5.1.0",
"lucia": "^3.2.2", "lucia": "^3.2.2",
"mediasoup": "^3.19.3", "mediasoup": "^3.19.3",
"prisma": "^6.17.0", "prisma": "^6.17.0",
@@ -25,8 +27,6 @@
"devDependencies": { "devDependencies": {
"@antfu/eslint-config": "^5.4.1", "@antfu/eslint-config": "^5.4.1",
"@types/bcrypt": "^6", "@types/bcrypt": "^6",
"@types/cookie-parser": "^1",
"@types/express": "^5.0.3",
"@types/ws": "^8", "@types/ws": "^8",
"eslint": "^9.36.0", "eslint": "^9.36.0",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",

45
server/plugins/auth.ts Normal file
View 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
}
})
})

View File

@@ -0,0 +1,74 @@
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 },
},
{
kind: 'video',
mimeType: 'video/VP8',
clockRate: 90000,
parameters: {
'x-google-start-bitrate': 1000,
},
},
{
kind: 'video',
mimeType: 'video/VP9',
clockRate: 90000,
parameters: {
'profile-id': 2,
'x-google-start-bitrate': 1000,
},
},
{
kind: 'video',
mimeType: 'video/h264',
clockRate: 90000,
parameters: {
'packetization-mode': 1,
'profile-level-id': '4d0032',
'level-asymmetry-allowed': 1,
'x-google-start-bitrate': 1000,
},
},
{
kind: 'video',
mimeType: 'video/h264',
clockRate: 90000,
parameters: {
'packetization-mode': 1,
'profile-level-id': '42e01f',
'level-asymmetry-allowed': 1,
'x-google-start-bitrate': 1000,
},
},
{
kind: 'video',
mimeType: 'video/AV1',
clockRate: 90000,
parameters: {},
},
],
}

View 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
View 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,
},
}

View File

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

View File

@@ -0,0 +1,10 @@
-- CreateTable
CREATE TABLE "UserPreferences" (
"userId" TEXT NOT NULL PRIMARY KEY,
"toggleInputHotkey" TEXT NOT NULL,
"toggleOutputHotkey" TEXT NOT NULL,
CONSTRAINT "UserPreferences_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateIndex
CREATE INDEX "Session_userId_idx" ON "Session"("userId");

View File

@@ -0,0 +1,21 @@
/*
Warnings:
- Added the required column `volumes` to the `UserPreferences` table without a default value. This is not possible if the table is not empty.
*/
-- RedefineTables
PRAGMA defer_foreign_keys=ON;
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_UserPreferences" (
"userId" TEXT NOT NULL PRIMARY KEY,
"toggleInputHotkey" TEXT NOT NULL,
"toggleOutputHotkey" TEXT NOT NULL,
"volumes" JSONB NOT NULL,
CONSTRAINT "UserPreferences_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "new_UserPreferences" ("toggleInputHotkey", "toggleOutputHotkey", "userId") SELECT "toggleInputHotkey", "toggleOutputHotkey", "userId" FROM "UserPreferences";
DROP TABLE "UserPreferences";
ALTER TABLE "new_UserPreferences" RENAME TO "UserPreferences";
PRAGMA foreign_keys=ON;
PRAGMA defer_foreign_keys=OFF;

View File

@@ -0,0 +1,15 @@
-- RedefineTables
PRAGMA defer_foreign_keys=ON;
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_UserPreferences" (
"userId" TEXT NOT NULL PRIMARY KEY,
"toggleInputHotkey" TEXT,
"toggleOutputHotkey" TEXT,
"volumes" JSONB,
CONSTRAINT "UserPreferences_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "new_UserPreferences" ("toggleInputHotkey", "toggleOutputHotkey", "userId", "volumes") SELECT "toggleInputHotkey", "toggleOutputHotkey", "userId", "volumes" FROM "UserPreferences";
DROP TABLE "UserPreferences";
ALTER TABLE "new_UserPreferences" RENAME TO "UserPreferences";
PRAGMA foreign_keys=ON;
PRAGMA defer_foreign_keys=OFF;

View File

@@ -5,25 +5,36 @@ datasource db {
generator client { generator client {
provider = "prisma-client-js" provider = "prisma-client-js"
// output = "./generated/client"
} }
model User { model User {
id String @id @default(cuid()) id String @id @default(cuid())
username String @unique username String @unique
password String password String
displayName String displayName String
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
Session Session[] Session Session[]
UserPreferences UserPreferences?
} }
model Session { model Session {
id String @id id String @id
userId String userId String
expiresAt DateTime expiresAt DateTime
user User @relation(references: [id], fields: [userId], onDelete: Cascade) user User @relation(references: [id], fields: [userId], onDelete: Cascade)
@@index([userId]) @@index([userId])
} }
model UserPreferences {
userId String @id
toggleInputHotkey String? @default("")
toggleOutputHotkey String? @default("")
volumes Json? @default("{}")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

118
server/routes/auth.ts Normal file
View 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 })
}
})
}

97
server/routes/user.ts Normal file
View File

@@ -0,0 +1,97 @@
import type { FastifyInstance } from 'fastify'
import type { Namespace } from '../types/webrtc.ts'
import { z } from 'zod'
import prisma from '../prisma/client.ts'
import { socketToClient } from '../utils/socket-to-client.ts'
export default function (fastify: FastifyInstance) {
fastify.get('/preferences', async (req, reply) => {
if (req.user) {
return prisma.userPreferences.findFirst({ where: { userId: req.user.id } })
}
reply.code(401).send(false)
})
fastify.patch('/preferences', async (req, reply) => {
if (!req.user) {
reply.code(401).send(false)
return
}
try {
const schema = z.object({
toggleInputHotkey: z.string().optional(),
toggleOutputHotkey: z.string().optional(),
volumes: z.record(z.string(), z.number()).optional(),
})
const input = schema.parse(req.body)
return prisma.userPreferences.upsert({
where: { userId: req.user.id },
create: {
userId: req.user.id,
...input,
},
update: input,
})
}
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.patch('/profile', async (req, reply) => {
if (!req.user) {
reply.code(401).send(false)
return
}
try {
const schema = z.object({
displayName: z.string().optional(),
})
const input = schema.parse(req.body)
const updatedUser = prisma.user.update({
where: { id: req.user.id },
data: {
displayName: input.displayName,
},
})
const namespace: Namespace = fastify.io.of('/webrtc')
const sockets = await namespace.fetchSockets()
const found = sockets.find(socket => socket.data.joined && socket.data.userId === req.user!.id)
if (found) {
found.data.displayName = input.displayName
namespace.emit('clientChanged', found.id, socketToClient(found))
}
return updatedUser
}
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 })
}
}
})
}

View File

@@ -1,61 +1,51 @@
import { createServer as createHttpServer } from 'node:http' import { dirname, join } from 'node:path'
import { createExpressMiddleware } from '@trpc/server/adapters/express' import { fileURLToPath } from 'node:url'
import { consola } from 'consola' import FastifyAutoLoad from '@fastify/autoload'
import cookieParser from 'cookie-parser' import FastifyCookie from '@fastify/cookie'
import cors from 'cors' import FastifyCors from '@fastify/cors'
import express from 'express' import Fastify from 'fastify'
import * as mediasoup from 'mediasoup' import prisma from './prisma/client.ts'
import { Server as SocketServer } from 'socket.io'
import { createContext } from './trpc/context'
import { appRouter } from './trpc/routers'
import webrtcSocket from './webrtc/socket'
(async () => { const __filename = fileURLToPath(import.meta.url)
const app = express() const __dirname = dirname(__filename)
app.use(cors()) const fastify = Fastify({
app.use(cookieParser()) logger: true,
app.use(express.json()) })
app.use( fastify.register(FastifyCors, {
'/chad/trpc', origin: [
createExpressMiddleware({ 'http://localhost:3000',
router: appRouter, 'http://tauri.localhost',
createContext, 'https://koptilnya.xyz',
}), 'https://chad.koptilnya.xyz',
) ],
methods: ['PATCH', 'PUT', 'OPTIONS', 'GET', 'POST', 'DELETE'],
credentials: true,
})
const server = createHttpServer(app) fastify.register(FastifyCookie)
const worker = await mediasoup.createWorker() fastify.register(FastifyAutoLoad, {
worker.on('died', () => { dir: join(__dirname, 'plugins'),
consola.error('[Mediasoup]', 'Worker died, exiting...') })
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) process.exit(1)
}) }
const router = await worker.createRouter({
mediaCodecs: [
{
kind: 'audio',
mimeType: 'audio/opus',
clockRate: 48000,
channels: 2,
parameters: { useinbandfec: 1, stereo: 1 },
},
],
})
const io = new SocketServer(server, {
path: '/chad/ws',
cors: {
origin: process.env.CORS_ORIGIN || '*',
},
})
webrtcSocket(io, router)
server.listen(process.env.PORT || 4000, () => {
console.log('✅ Server running')
})
})() })()

View File

@@ -1,144 +1,21 @@
import type { types } from 'mediasoup' import type { types } from 'mediasoup'
import type { Namespace, RemoteSocket, Socket, Server as SocketServer } from 'socket.io' import type { Server as SocketServer } from 'socket.io'
import type {
Namespace,
SomeSocket,
} from '../types/webrtc.ts'
import { consola } from 'consola' import { consola } from 'consola'
import prisma from '../prisma/client.ts'
interface ChadClient { import { socketToClient } from '../utils/socket-to-client.ts'
id: string
username: string
inputMuted: boolean
outputMuted: boolean
}
interface ProducerShort {
producerId: types.Producer['id']
kind: types.MediaKind
}
interface ErrorCallbackResult {
error: string
}
interface SuccessCallbackResult {
ok: true
}
type EventCallback<T = SuccessCallbackResult> = (result: T | ErrorCallbackResult) => void
interface ClientToServerEvents {
join: (
options: {
username: string
rtpCapabilities: types.RtpCapabilities
},
cb: EventCallback<{ id: string, username: string }[]>
) => void
getRtpCapabilities: (
cb: EventCallback<types.RtpCapabilities>
) => void
createTransport: (
options: {
producing: boolean
consuming: boolean
},
cb: EventCallback<Pick<types.WebRtcTransport, 'id' | 'iceParameters' | 'iceCandidates' | 'dtlsParameters'>>
) => void
connectTransport: (
options: {
transportId: types.WebRtcTransport['id']
dtlsParameters: types.WebRtcTransport['dtlsParameters']
},
cb: EventCallback
) => void
produce: (
options: {
transportId: types.WebRtcTransport['id']
kind: types.MediaKind
rtpParameters: types.RtpParameters
},
cb: EventCallback<{ id: types.Producer['id'] }>
) => void
closeProducer: (
options: {
producerId: types.Producer['id']
},
cb: EventCallback
) => void
pauseProducer: (
options: {
producerId: types.Producer['id']
},
cb: EventCallback
) => void
resumeProducer: (
options: {
producerId: types.Producer['id']
},
cb: EventCallback
) => void
pauseConsumer: (
options: {
consumerId: types.Consumer['id']
},
cb: EventCallback
) => void
resumeConsumer: (
options: {
consumerId: types.Consumer['id']
},
cb: EventCallback
) => void
updateClient: (
options: Partial<Omit<ChadClient, 'id'>>,
cb: EventCallback
) => void
}
interface ServerToClientEvents {
newPeer: (arg: ChadClient) => void
producers: (arg: ProducerShort[]) => void
newConsumer: (
arg: {
peerId: string
producerId: types.Producer['id']
id: types.Consumer['id']
kind: types.MediaKind
rtpParameters: types.RtpParameters
type: types.ConsumerType
appData: types.Producer['appData']
producerPaused: types.Consumer['producerPaused']
},
cb: EventCallback
) => void
peerClosed: (arg: string) => void
consumerClosed: (arg: { consumerId: string }) => void
consumerPaused: (arg: { consumerId: string }) => void
consumerResumed: (arg: { consumerId: string }) => void
consumerScore: (arg: { consumerId: string, score: types.ConsumerScore }) => void
clientChanged: (clientId: ChadClient['id'], client: ChadClient) => void
}
interface InterServerEvent {}
interface SocketData {
joined: boolean
username: string
inputMuted: boolean
outputMuted: boolean
rtpCapabilities: types.RtpCapabilities
transports: Map<types.WebRtcTransport['id'], types.WebRtcTransport>
producers: Map<types.Producer['id'], types.Producer>
consumers: Map<types.Consumer['id'], types.Consumer>
}
export default function (io: SocketServer, router: types.Router) { export default function (io: SocketServer, router: types.Router) {
const namespace: Namespace<ClientToServerEvents, ServerToClientEvents, InterServerEvent, SocketData> = io.of('/webrtc') const namespace: Namespace = io.of('/webrtc')
namespace.on('connection', (socket) => { namespace.on('connection', async (socket) => {
consola.info('[WebRtc]', 'Client connected', socket.id) consola.info('[WebRtc]', 'Client connected', socket.id)
socket.data.joined = false socket.data.joined = false
socket.data.username = socket.id
socket.data.inputMuted = false socket.data.inputMuted = false
socket.data.outputMuted = false socket.data.outputMuted = false
@@ -146,24 +23,35 @@ export default function (io: SocketServer, router: types.Router) {
socket.data.producers = new Map() socket.data.producers = new Map()
socket.data.consumers = new Map() socket.data.consumers = new Map()
socket.on('join', async ({ username, rtpCapabilities }, cb) => { 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) { if (socket.data.joined) {
consola.error('[WebRtc]', 'Already joined') consola.error('[WebRtc]', 'Already joined')
cb({ error: 'Already joined' }) cb({ error: 'Already joined' })
} }
socket.data.joined = true socket.data.joined = true
socket.data.username = username
socket.data.rtpCapabilities = rtpCapabilities socket.data.rtpCapabilities = rtpCapabilities
const joinedSockets = await getJoinedSockets() const joinedSockets = await getJoinedSockets()
cb(joinedSockets.map((s) => { cb(joinedSockets.map(socketToClient))
return {
id: s.id,
username: s.data.username,
}
}))
for (const joinedSocket of joinedSockets.filter(joinedSocket => joinedSocket.id !== socket.id)) { for (const joinedSocket of joinedSockets.filter(joinedSocket => joinedSocket.id !== socket.id)) {
for (const producer of joinedSocket.data.producers.values()) { for (const producer of joinedSocket.data.producers.values()) {
@@ -213,7 +101,7 @@ export default function (io: SocketServer, router: types.Router) {
dtlsParameters: transport.dtlsParameters, dtlsParameters: transport.dtlsParameters,
}) })
transport.on('icestatechange', (iceState) => { transport.on('icestatechange', (iceState: types.IceState) => {
if (iceState === 'disconnected' || iceState === 'closed') { if (iceState === 'disconnected' || iceState === 'closed') {
consola.info('[WebRtc]', '[WebRtcTransport]', `"icestatechange" event [iceState:${iceState}], closing peer`, transport.id) consola.info('[WebRtc]', '[WebRtcTransport]', `"icestatechange" event [iceState:${iceState}], closing peer`, transport.id)
@@ -221,7 +109,7 @@ export default function (io: SocketServer, router: types.Router) {
} }
}) })
transport.on('dtlsstatechange', (dtlsState) => { transport.on('dtlsstatechange', (dtlsState: types.DtlsState) => {
if (dtlsState === 'failed' || dtlsState === 'closed') { if (dtlsState === 'failed' || dtlsState === 'closed') {
consola.warn('WebRtcTransport "dtlsstatechange" event [dtlsState:%s], closing peer', dtlsState) consola.warn('WebRtcTransport "dtlsstatechange" event [dtlsState:%s], closing peer', dtlsState)
@@ -260,7 +148,7 @@ export default function (io: SocketServer, router: types.Router) {
} }
}) })
socket.on('produce', async ({ transportId, kind, rtpParameters }, cb) => { socket.on('produce', async ({ transportId, kind, rtpParameters, appData }, cb) => {
if (!socket.data.joined) { if (!socket.data.joined) {
consola.error('Peer not joined yet') consola.error('Peer not joined yet')
cb({ error: 'Peer not joined yet' }) cb({ error: 'Peer not joined yet' })
@@ -278,7 +166,7 @@ export default function (io: SocketServer, router: types.Router) {
} }
try { try {
const producer = await transport.produce({ kind, rtpParameters, appData: { socketId: socket.id } }) const producer = await transport.produce({ kind, rtpParameters, appData: { ...appData, socketId: socket.id } })
socket.data.producers.set(producer.id, producer) socket.data.producers.set(producer.id, producer)
@@ -346,6 +234,9 @@ export default function (io: SocketServer, router: types.Router) {
return return
} }
if (producer.paused)
return
await producer.pause() await producer.pause()
cb({ ok: true }) cb({ ok: true })
@@ -417,20 +308,16 @@ export default function (io: SocketServer, router: types.Router) {
cb({ ok: true }) cb({ ok: true })
}) })
socket.on('updateClient', (updatedClient, cb) => { socket.on('updateClient', async (updatedClient, cb) => {
if (updatedClient.username) { if (typeof updatedClient.inputMuted === 'boolean') {
socket.data.username = updatedClient.username
}
if (updatedClient.inputMuted) {
socket.data.inputMuted = updatedClient.inputMuted socket.data.inputMuted = updatedClient.inputMuted
} }
if (updatedClient.outputMuted) { if (typeof updatedClient.outputMuted === 'boolean') {
socket.data.outputMuted = updatedClient.outputMuted socket.data.outputMuted = updatedClient.outputMuted
} }
cb({ ok: true }) cb(socketToClient(socket))
namespace.emit('clientChanged', socket.id, socketToClient(socket)) namespace.emit('clientChanged', socket.id, socketToClient(socket))
}) })
@@ -455,8 +342,8 @@ export default function (io: SocketServer, router: types.Router) {
} }
async function createConsumer( async function createConsumer(
consumerSocket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvent, SocketData>, consumerSocket: SomeSocket,
producerSocket: RemoteSocket<ServerToClientEvents, SocketData>, producerSocket: SomeSocket,
producer: types.Producer, producer: types.Producer,
) { ) {
if ( if (
@@ -520,7 +407,7 @@ export default function (io: SocketServer, router: types.Router) {
consumerSocket.emit('consumerResumed', { consumerId: consumer.id }) consumerSocket.emit('consumerResumed', { consumerId: consumer.id })
}) })
consumer.on('score', (score) => { consumer.on('score', (score: types.ConsumerScore) => {
consumerSocket.emit('consumerScore', { consumerId: consumer.id, score }) consumerSocket.emit('consumerScore', { consumerId: consumer.id, score })
}) })
@@ -528,7 +415,7 @@ export default function (io: SocketServer, router: types.Router) {
await consumerSocket.emitWithAck( await consumerSocket.emitWithAck(
'newConsumer', 'newConsumer',
{ {
peerId: producerSocket.id, socketId: producerSocket.id,
producerId: producer.id, producerId: producer.id,
id: consumer.id, id: consumer.id,
kind: consumer.kind, kind: consumer.kind,
@@ -553,13 +440,4 @@ export default function (io: SocketServer, router: types.Router) {
consola.error('_createConsumer() | failed:%o', error) consola.error('_createConsumer() | failed:%o', error)
} }
} }
function socketToClient(socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvent, SocketData>): ChadClient {
return {
id: socket.id,
username: socket.data.username,
inputMuted: socket.data.inputMuted,
outputMuted: socket.data.outputMuted,
}
}
} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,10 +1,12 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "es2016", "target": "es2016",
"module": "commonjs", "module": "ESNext",
"moduleResolution": "nodenext",
"esModuleInterop": true, "esModuleInterop": true,
"forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true,
"strict": true, "strict": true,
"skipLibCheck": true "skipLibCheck": true,
"allowImportingTsExtensions": true
} }
} }

140
server/types/webrtc.ts Normal file
View File

@@ -0,0 +1,140 @@
import type { types } from 'mediasoup'
import type { RemoteSocket, Socket, Namespace as SocketNamespace } from 'socket.io'
import type { User } from '../prisma/client'
export interface ChadClient {
socketId: string
userId: User['id']
username: User['username']
displayName: User['displayName']
inputMuted: boolean
outputMuted: boolean
}
export interface ProducerShort {
producerId: types.Producer['id']
kind: types.MediaKind
}
export interface ErrorCallbackResult {
error: string
}
export interface SuccessCallbackResult {
ok: true
}
export type EventCallback<T = SuccessCallbackResult> = (result: T | ErrorCallbackResult) => void
export 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
appData: { source: 'share' | string }
},
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<Pick<ChadClient, 'inputMuted' | 'outputMuted'>>,
cb: EventCallback<ChadClient>
) => void
}
export 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
}
export interface InterServerEvent {}
export 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>
}
export type SomeSocket = Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvent, SocketData> | RemoteSocket<ServerToClientEvents, SocketData>
export type Namespace = SocketNamespace<ClientToServerEvents, ServerToClientEvents, InterServerEvent, SocketData>

View File

@@ -0,0 +1,12 @@
import type { ChadClient, SomeSocket } from '../types/webrtc.ts'
export 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,
}
}

File diff suppressed because it is too large Load Diff

View File

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