Compare commits

..

19 Commits

Author SHA1 Message Date
Zomatree
6043ba6004 Merge branch 'main' into feat/oauth2 2025-11-03 03:28:19 +00:00
Aeledfyr
657a3f08e5 fix: preserve order of replies in message (#447)
Signed-off-by: Aeledfyr <aeledfyr@gmail.com>
2025-10-27 00:10:07 +00:00
Zomatree
af78ac0586 chore(ci): move to stoatchat 2025-10-11 23:22:41 +01:00
Zomatree
d65c1a1ab3 fix(ci): publish images under stoatchat and remove docker hub 2025-10-11 23:01:35 +01:00
izzy
4fb99e3bd0 ci: also include gifbox src 2025-09-23 12:12:33 -05:00
izzy
f0a83abcfa ci: add missing src copies for Docker build 2025-09-23 12:09:19 -05:00
izzy
6f1c715b8c chore: bump version to 0.8.9 2025-09-23 12:02:35 -05:00
Zomatree
67773d3e43 chore: sync branch with main 2025-08-18 02:14:36 +01:00
Zomatree
14ea180683 refactor: simplify scope struct macro 2025-08-18 01:58:15 +01:00
Zomatree
83c15404a5 fix: use correct key name for auth bots collection 2025-08-18 01:58:15 +01:00
Zomatree
9d4bcb5e3d chore: rework oauth2 route scoping 2025-08-18 01:58:15 +01:00
Zomatree
f895ca7b23 feat: allow connecting to ws via oauth2 2025-08-18 01:58:15 +01:00
Zomatree
ef65223c89 feat: initial work on refresh tokens 2025-08-18 01:58:14 +01:00
Zomatree
660e646b2b feat: initial oauth2 token revoking 2025-08-18 01:58:14 +01:00
Zomatree
5a5f84f207 fix: add more oauth2 checks 2025-08-18 01:58:14 +01:00
Zomatree
11eee02cfe feat: allowed scopes 2025-08-18 01:58:14 +01:00
Zomatree
1e5b27ff9e fix(oauth2): use public bot 2025-08-18 01:58:14 +01:00
Zomatree
3ae25fbcfe fix(oauth2): fix spec discrepancies 2025-08-18 01:58:14 +01:00
Zomatree
9e05e5be7e feat: initial oauth2 implementation 2025-08-18 01:58:14 +01:00
135 changed files with 2229 additions and 3304 deletions

View File

@@ -49,13 +49,6 @@ jobs:
uses: docker/setup-buildx-action@v2
# Authenticate with Docker Hub and GHCR
- name: Login to DockerHub
uses: docker/login-action@v2
with:
registry: docker.io
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to Github Container Registry
uses: docker/login-action@v2
with:
@@ -72,14 +65,13 @@ jobs:
platforms: linux/amd64,linux/arm64
tags: ghcr.io/${{ github.repository_owner }}/base:latest
# revoltchat/server
# stoatchat/api
- name: Docker meta
id: meta-delta
uses: docker/metadata-action@v4
with:
images: |
docker.io/revoltchat/server
ghcr.io/revoltchat/server
ghcr.io/stoatchat/api
- name: Publish
uses: docker/build-push-action@v4
with:
@@ -92,14 +84,13 @@ jobs:
BASE_IMAGE=ghcr.io/${{ github.repository_owner }}/base:latest
labels: ${{ steps.meta-delta.outputs.labels }}
# revoltchat/bonfire
# stoatchat/events
- name: Docker meta
id: meta-bonfire
uses: docker/metadata-action@v4
with:
images: |
docker.io/revoltchat/bonfire
ghcr.io/revoltchat/bonfire
ghcr.io/stoatchat/events
- name: Publish
uses: docker/build-push-action@v4
with:
@@ -112,14 +103,13 @@ jobs:
BASE_IMAGE=ghcr.io/${{ github.repository_owner }}/base:latest
labels: ${{ steps.meta-bonfire.outputs.labels }}
# revoltchat/autumn
# stoatchat/file-server
- name: Docker meta
id: meta-autumn
uses: docker/metadata-action@v4
with:
images: |
docker.io/revoltchat/autumn
ghcr.io/revoltchat/autumn
ghcr.io/stoatchat/file-server
- name: Publish
uses: docker/build-push-action@v4
with:
@@ -132,14 +122,13 @@ jobs:
BASE_IMAGE=ghcr.io/${{ github.repository_owner }}/base:latest
labels: ${{ steps.meta-autumn.outputs.labels }}
# revoltchat/january
# stoatchat/proxy
- name: Docker meta
id: meta-january
uses: docker/metadata-action@v4
with:
images: |
docker.io/revoltchat/january
ghcr.io/revoltchat/january
ghcr.io/stoatchat/proxy
- name: Publish
uses: docker/build-push-action@v4
with:
@@ -152,14 +141,13 @@ jobs:
BASE_IMAGE=ghcr.io/${{ github.repository_owner }}/base:latest
labels: ${{ steps.meta-january.outputs.labels }}
# revoltchat/gifbox
# stoatchat/gifbox
- name: Docker meta
id: meta-gifbox
uses: docker/metadata-action@v4
with:
images: |
docker.io/revoltchat/gifbox
ghcr.io/revoltchat/gifbox
ghcr.io/stoatchat/gifbox
- name: Publish
uses: docker/build-push-action@v4
with:
@@ -172,14 +160,13 @@ jobs:
BASE_IMAGE=ghcr.io/${{ github.repository_owner }}/base:latest
labels: ${{ steps.meta-gifbox.outputs.labels }}
# revoltchat/crond
# stoatchat/crond
- name: Docker meta
id: meta-crond
uses: docker/metadata-action@v4
with:
images: |
docker.io/revoltchat/crond
ghcr.io/revoltchat/crond
ghcr.io/stoatchat/crond
- name: Publish
uses: docker/build-push-action@v4
with:
@@ -192,14 +179,13 @@ jobs:
BASE_IMAGE=ghcr.io/${{ github.repository_owner }}/base:latest
labels: ${{ steps.meta-crond.outputs.labels }}
# revoltchat/pushd
# stoatchat/pushd
- name: Docker meta
id: meta-pushd
uses: docker/metadata-action@v4
with:
images: |
docker.io/revoltchat/pushd
ghcr.io/revoltchat/pushd
ghcr.io/stoatchat/pushd
- name: Publish
uses: docker/build-push-action@v4
with:

View File

@@ -73,7 +73,7 @@ jobs:
if: github.event_name != 'pull_request' && github.ref_name == 'main'
uses: actions/checkout@v3
with:
repository: revoltchat/api
repository: stoatchat/api
path: api
token: ${{ secrets.PAT }}

View File

@@ -14,7 +14,7 @@ jobs:
run: |
gh api graphql -f query='
query {
organization(login: "revoltchat"){
organization(login: "stoatchat"){
projectV2(number: 3) {
id
fields(first:20) {

View File

@@ -14,7 +14,7 @@ jobs:
run: |
gh api graphql -f query='
query {
organization(login: "revoltchat"){
organization(login: "stoatchat"){
projectV2(number: 5) {
id
fields(first:20) {

4
.gitignore vendored
View File

@@ -11,6 +11,4 @@ venv/
.vercel
.DS_Store
livekit.yml
.idea
start
.idea

478
Cargo.lock generated
View File

@@ -136,9 +136,9 @@ dependencies = [
[[package]]
name = "anyhow"
version = "1.0.100"
version = "1.0.99"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
checksum = "b0674a1ddeecb70197781e945de4b3b8ffb61fa939a5597bcf48503737663100"
dependencies = [
"backtrace",
]
@@ -822,11 +822,11 @@ dependencies = [
"hyper-util",
"pin-project-lite 0.2.16",
"rustls 0.21.12",
"rustls 0.23.32",
"rustls 0.23.31",
"rustls-native-certs 0.8.1",
"rustls-pki-types",
"tokio 1.47.1",
"tokio-rustls 0.26.3",
"tokio-rustls 0.26.2",
"tower",
"tracing",
]
@@ -1067,7 +1067,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11eeb275b20a4c750c9fe7bf5a750e97e7944563003efd1c82e70c229a612ca1"
dependencies = [
"darling 0.20.11",
"heck 0.5.0",
"heck",
"proc-macro-error",
"quote 1.0.40",
"syn 2.0.106",
@@ -1275,7 +1275,7 @@ dependencies = [
"getrandom 0.2.16",
"getrandom 0.3.3",
"hex",
"indexmap 2.11.4",
"indexmap 2.11.1",
"js-sys",
"once_cell",
"rand 0.9.2",
@@ -1382,9 +1382,9 @@ checksum = "a2698f953def977c68f935bb0dfa959375ad4638570e969e2f1e9f433cbf1af6"
[[package]]
name = "cc"
version = "1.2.38"
version = "1.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80f41ae168f955c12fb8960b057d70d0ca153fb83182b57d86380443527be7e9"
checksum = "65193589c6404eb80b450d618eaf9a2cafaaafd57ecce47370519ef674a7bd44"
dependencies = [
"find-msvc-tools",
"jobserver",
@@ -1874,16 +1874,6 @@ dependencies = [
"darling_macro 0.20.11",
]
[[package]]
name = "darling"
version = "0.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0"
dependencies = [
"darling_core 0.21.3",
"darling_macro 0.21.3",
]
[[package]]
name = "darling_core"
version = "0.13.4"
@@ -1926,20 +1916,6 @@ dependencies = [
"syn 2.0.106",
]
[[package]]
name = "darling_core"
version = "0.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote 1.0.40",
"strsim 0.11.1",
"syn 2.0.106",
]
[[package]]
name = "darling_macro"
version = "0.13.4"
@@ -1973,17 +1949,6 @@ dependencies = [
"syn 2.0.106",
]
[[package]]
name = "darling_macro"
version = "0.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81"
dependencies = [
"darling_core 0.21.3",
"quote 1.0.40",
"syn 2.0.106",
]
[[package]]
name = "dashmap"
version = "5.5.3"
@@ -2351,7 +2316,7 @@ version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"
dependencies = [
"heck 0.5.0",
"heck",
"proc-macro2",
"quote 1.0.40",
"syn 2.0.106",
@@ -2432,7 +2397,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -2589,9 +2554,9 @@ dependencies = [
[[package]]
name = "find-msvc-tools"
version = "0.1.2"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ced73b1dacfc750a6db6c0a0c3a3853c8b41997e2e2c563dc90804ae6867959"
checksum = "7fd99930f64d146689264c637b5af2f0233a933bef0d8570e2526bf9e083192d"
[[package]]
name = "findshlibs"
@@ -2605,12 +2570,6 @@ dependencies = [
"winapi",
]
[[package]]
name = "fixedbitset"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "flate2"
version = "1.1.2"
@@ -2965,7 +2924,7 @@ dependencies = [
"js-sys",
"libc",
"r-efi",
"wasi 0.14.7+wasi-0.2.4",
"wasi 0.14.5+wasi-0.2.4",
"wasm-bindgen",
]
@@ -3072,7 +3031,7 @@ dependencies = [
"futures-sink",
"futures-util",
"http 0.2.12",
"indexmap 2.11.4",
"indexmap 2.11.1",
"slab",
"tokio 1.47.1",
"tokio-util",
@@ -3091,7 +3050,7 @@ dependencies = [
"futures-core",
"futures-sink",
"http 1.3.1",
"indexmap 2.11.4",
"indexmap 2.11.1",
"slab",
"tokio 1.47.1",
"tokio-util",
@@ -3158,12 +3117,6 @@ dependencies = [
"foldhash",
]
[[package]]
name = "hashbrown"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d"
[[package]]
name = "headers"
version = "0.4.1"
@@ -3188,12 +3141,6 @@ dependencies = [
"http 1.3.1",
]
[[package]]
name = "heck"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]]
name = "heck"
version = "0.5.0"
@@ -3500,11 +3447,11 @@ dependencies = [
"http 1.3.1",
"hyper 1.7.0",
"hyper-util",
"rustls 0.23.32",
"rustls 0.23.31",
"rustls-native-certs 0.8.1",
"rustls-pki-types",
"tokio 1.47.1",
"tokio-rustls 0.26.3",
"tokio-rustls 0.26.2",
"tower-service",
]
@@ -3539,9 +3486,9 @@ dependencies = [
[[package]]
name = "hyper-util"
version = "0.1.17"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c6995591a8f1380fcb4ba966a252a4b29188d51d2b89e3a252f5305be65aea8"
checksum = "8d9b05277c7e8da2c93a568989bb6207bef0112e8d17df7a6eda4a3cf143bc5e"
dependencies = [
"base64 0.22.1",
"bytes 1.10.1",
@@ -3812,14 +3759,13 @@ dependencies = [
[[package]]
name = "indexmap"
version = "2.11.4"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b0f83760fb341a774ed326568e19f5a863af4a952def8c39f9ab92fd95b88e5"
checksum = "206a8042aec68fa4a62e8d3f7aa4ceb508177d9324faf261e1959e495b7a1921"
dependencies = [
"equivalent",
"hashbrown 0.16.0",
"hashbrown 0.15.5",
"serde",
"serde_core",
]
[[package]]
@@ -3957,15 +3903,6 @@ dependencies = [
"time",
]
[[package]]
name = "itertools"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"
dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.12.1"
@@ -4002,9 +3939,9 @@ dependencies = [
[[package]]
name = "js-sys"
version = "0.3.80"
version = "0.3.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "852f13bec5eba4ba9afbeb93fd7c13fe56147f055939ae21c43a29a0ecb2702e"
checksum = "0c0b063578492ceec17683ef2f8c5e89121fbd0b172cbc280635ab7567db2738"
dependencies = [
"once_cell",
"wasm-bindgen",
@@ -4029,9 +3966,11 @@ checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
dependencies = [
"base64 0.22.1",
"js-sys",
"pem 3.0.5",
"ring",
"serde",
"serde_json",
"simple_asn1",
]
[[package]]
@@ -4384,9 +4323,9 @@ dependencies = [
[[package]]
name = "linux-raw-sys"
version = "0.11.0"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12"
[[package]]
name = "litemap"
@@ -4394,68 +4333,6 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "241eaef5fd12c88705a01fc1066c48c4b36e0dd4377dcdc7ec3942cea7a69956"
[[package]]
name = "livekit-api"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a17951fa8d398241f4a9503b57a7b38b3f40fb9dc94954f17b9fe99683e6b9b"
dependencies = [
"base64 0.21.7",
"http 0.2.12",
"jsonwebtoken",
"livekit-protocol",
"log",
"parking_lot",
"pbjson-types",
"prost",
"rand 0.9.2",
"reqwest 0.11.27",
"scopeguard",
"serde",
"serde_json",
"sha2",
"thiserror 1.0.69",
"url",
]
[[package]]
name = "livekit-protocol"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45c90494efa508ec40228f870affec648826d23e1a9621a4430f67d187901eb4"
dependencies = [
"futures-util",
"livekit-runtime 0.4.0",
"parking_lot",
"pbjson",
"pbjson-types",
"prost",
"prost-types",
"serde",
"thiserror 1.0.69",
"tokio 1.47.1",
]
[[package]]
name = "livekit-runtime"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ae53eb874eb86e96e8ccffc31b5a00926d46174cbcb1c24ce4e57b1fcc5c8f6"
dependencies = [
"tokio 1.47.1",
"tokio-stream",
]
[[package]]
name = "livekit-runtime"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "532e84c6cdc5fe774f2b5d9912597b5f3bea561927a48296d03e24549d21c3f6"
dependencies = [
"tokio 1.47.1",
"tokio-stream",
]
[[package]]
name = "lock_api"
version = "0.4.13"
@@ -4861,7 +4738,7 @@ dependencies = [
"percent-encoding",
"rand 0.8.5",
"rustc_version_runtime",
"rustls 0.23.32",
"rustls 0.23.31",
"rustversion",
"serde",
"serde_bytes",
@@ -4874,7 +4751,7 @@ dependencies = [
"take_mut",
"thiserror 1.0.69",
"tokio 1.47.1",
"tokio-rustls 0.26.3",
"tokio-rustls 0.26.2",
"tokio-util",
"typed-builder",
"uuid",
@@ -4922,12 +4799,6 @@ dependencies = [
"version_check",
]
[[package]]
name = "multimap"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
[[package]]
name = "mutate_once"
version = "0.1.2"
@@ -5315,43 +5186,6 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
[[package]]
name = "pbjson"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1030c719b0ec2a2d25a5df729d6cff1acf3cc230bf766f4f97833591f7577b90"
dependencies = [
"base64 0.21.7",
"serde",
]
[[package]]
name = "pbjson-build"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2580e33f2292d34be285c5bc3dba5259542b083cfad6037b6d70345f24dcb735"
dependencies = [
"heck 0.4.1",
"itertools 0.11.0",
"prost",
"prost-types",
]
[[package]]
name = "pbjson-types"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18f596653ba4ac51bdecbb4ef6773bc7f56042dc13927910de1684ad3d32aa12"
dependencies = [
"bytes 1.10.1",
"chrono",
"pbjson",
"pbjson-build",
"prost",
"prost-build",
"serde",
]
[[package]]
name = "pbkdf2"
version = "0.11.0"
@@ -5473,16 +5307,6 @@ dependencies = [
"sha2",
]
[[package]]
name = "petgraph"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db"
dependencies = [
"fixedbitset",
"indexmap 2.11.4",
]
[[package]]
name = "phf"
version = "0.10.1"
@@ -5628,6 +5452,17 @@ dependencies = [
"futures-io",
]
[[package]]
name = "pkce"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e228dbe2aebd82de09c914fe28d36d3170ed5192e8d52b9c070ee0794519c2d3"
dependencies = [
"base64 0.21.7",
"rand 0.8.5",
"sha2",
]
[[package]]
name = "pkcs1"
version = "0.4.1"
@@ -5668,12 +5503,12 @@ checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
name = "plist"
version = "1.8.0"
version = "1.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07"
checksum = "3af6b589e163c5a788fab00ce0c0366f6efbb9959c2f9874b224936af7fce7e1"
dependencies = [
"base64 0.22.1",
"indexmap 2.11.4",
"indexmap 2.11.1",
"quick-xml",
"serde",
"time",
@@ -5923,64 +5758,11 @@ dependencies = [
"thiserror 1.0.69",
]
[[package]]
name = "prost"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29"
dependencies = [
"bytes 1.10.1",
"prost-derive",
]
[[package]]
name = "prost-build"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4"
dependencies = [
"bytes 1.10.1",
"heck 0.5.0",
"itertools 0.12.1",
"log",
"multimap",
"once_cell",
"petgraph",
"prettyplease",
"prost",
"prost-types",
"regex",
"syn 2.0.106",
"tempfile",
]
[[package]]
name = "prost-derive"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1"
dependencies = [
"anyhow",
"itertools 0.12.1",
"proc-macro2",
"quote 1.0.40",
"syn 2.0.106",
]
[[package]]
name = "prost-types"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9091c90b0a32608e984ff2fa4091273cbdd755d54935c51d520887f4a1dbd5b0"
dependencies = [
"prost",
]
[[package]]
name = "pxfm"
version = "0.1.24"
version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83f9b339b02259ada5c0f4a389b7fb472f933aa17ce176fd2ad98f28bb401fde"
checksum = "f55f4fedc84ed39cb7a489322318976425e42a147e2be79d8f878e2884f94e84"
dependencies = [
"num-traits",
]
@@ -6590,7 +6372,7 @@ dependencies = [
name = "revolt-coalesced"
version = "0.8.9"
dependencies = [
"indexmap 2.11.4",
"indexmap 1.9.3",
"lru 0.7.8",
"tokio 1.47.1",
]
@@ -6637,16 +6419,15 @@ dependencies = [
"axum",
"base64 0.21.7",
"bson",
"chrono",
"deadqueue",
"decancer",
"futures",
"indexmap 1.9.3",
"isahc",
"iso8601-timestamp",
"jsonwebtoken",
"linkify 0.8.1",
"livekit-api",
"livekit-protocol",
"livekit-runtime 0.3.1",
"log",
"lru 0.11.1",
"mongodb",
@@ -6691,13 +6472,12 @@ dependencies = [
"iso8601-timestamp",
"lettre",
"linkify 0.6.0",
"livekit-api",
"livekit-protocol",
"log",
"lru 0.7.8",
"nanoid",
"num_enum 0.5.11",
"once_cell",
"pkce",
"rand 0.8.5",
"redis-kiss",
"regex",
@@ -6900,7 +6680,6 @@ name = "revolt-result"
version = "0.8.9"
dependencies = [
"axum",
"log",
"revolt_okapi",
"revolt_rocket_okapi",
"rocket",
@@ -6910,34 +6689,6 @@ dependencies = [
"utoipa",
]
[[package]]
name = "revolt-voice-ingress"
version = "0.7.1"
dependencies = [
"amqprs",
"async-std",
"chrono",
"futures",
"livekit-api",
"livekit-protocol",
"livekit-runtime 0.3.1",
"log",
"lru 0.7.8",
"redis-kiss",
"revolt-config",
"revolt-database",
"revolt-models",
"revolt-permissions",
"revolt-result",
"rmp-serde",
"rocket",
"rocket_empty",
"sentry",
"serde",
"serde_json",
"ulid 0.5.0",
]
[[package]]
name = "revolt_a2"
version = "0.10.1"
@@ -7099,7 +6850,7 @@ dependencies = [
"either",
"figment",
"futures",
"indexmap 2.11.4",
"indexmap 2.11.1",
"log",
"memchr",
"multer",
@@ -7147,7 +6898,7 @@ checksum = "575d32d7ec1a9770108c879fc7c47815a80073f96ca07ff9525a94fcede1dd46"
dependencies = [
"devise",
"glob",
"indexmap 2.11.4",
"indexmap 2.11.1",
"proc-macro2",
"quote 1.0.40",
"rocket_http",
@@ -7194,7 +6945,7 @@ dependencies = [
"futures",
"http 0.2.12",
"hyper 0.14.32",
"indexmap 2.11.4",
"indexmap 2.11.1",
"log",
"memchr",
"pear",
@@ -7313,15 +7064,15 @@ dependencies = [
[[package]]
name = "rustix"
version = "1.1.2"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e"
checksum = "c71e83d6afe7ff64890ec6b71d6a69bb8a610ab78ce364b3352876bb4c801266"
dependencies = [
"bitflags 2.9.4",
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -7352,16 +7103,16 @@ dependencies = [
[[package]]
name = "rustls"
version = "0.23.32"
version = "0.23.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd3c25631629d034ce7cd9940adc9d45762d46de2b0f57193c4443b92c6d4d40"
checksum = "c0ebcbd2f03de0fc1122ad9bb24b127a5a6cd51d72604a3f3c50ac459762b6cc"
dependencies = [
"aws-lc-rs",
"log",
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki 0.103.6",
"rustls-webpki 0.103.5",
"subtle",
"zeroize",
]
@@ -7440,9 +7191,9 @@ dependencies = [
[[package]]
name = "rustls-webpki"
version = "0.103.6"
version = "0.103.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8572f3c2cb9934231157b45499fc41e1f58c589fdfb81a844ba873265e80f8eb"
checksum = "b5a37813727b78798e53c2bec3f5e8fe12a6d6f8389bf9ca7802add4c9905ad8"
dependencies = [
"aws-lc-rs",
"ring",
@@ -7842,9 +7593,9 @@ dependencies = [
[[package]]
name = "serde"
version = "1.0.225"
version = "1.0.223"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd6c24dee235d0da097043389623fb913daddf92c76e9f5a1db88607a0bcbd1d"
checksum = "a505d71960adde88e293da5cb5eda57093379f64e61cf77bf0e6a63af07a7bac"
dependencies = [
"serde_core",
"serde_derive",
@@ -7852,9 +7603,9 @@ dependencies = [
[[package]]
name = "serde_bytes"
version = "0.11.19"
version = "0.11.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"
checksum = "fe07b5d88710e3b807c16a06ccbc9dfecd5fff6a4d2745c59e3e26774f10de6a"
dependencies = [
"serde",
"serde_core",
@@ -7871,18 +7622,18 @@ dependencies = [
[[package]]
name = "serde_core"
version = "1.0.225"
version = "1.0.223"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "659356f9a0cb1e529b24c01e43ad2bdf520ec4ceaf83047b83ddcc2251f96383"
checksum = "20f57cbd357666aa7b3ac84a90b4ea328f1d4ddb6772b430caa5d9e1309bb9e9"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.225"
version = "1.0.223"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ea936adf78b1f766949a4977b91d2f5595825bd6ec079aa9543ad2685fc4516"
checksum = "3d428d07faf17e306e699ec1e91996e5a165ba5d6bce5b5155173e91a8a01a56"
dependencies = [
"proc-macro2",
"quote 1.0.40",
@@ -7906,7 +7657,7 @@ version = "1.0.145"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c"
dependencies = [
"indexmap 2.11.4",
"indexmap 2.11.1",
"itoa",
"memchr",
"ryu",
@@ -7916,9 +7667,9 @@ dependencies = [
[[package]]
name = "serde_path_to_error"
version = "0.1.20"
version = "0.1.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
checksum = "a30a8abed938137c7183c173848e3c9b3517f5e038226849a4ecc9b21a4b4e2a"
dependencies = [
"itoa",
"serde",
@@ -7948,15 +7699,15 @@ dependencies = [
[[package]]
name = "serde_with"
version = "3.14.1"
version = "3.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c522100790450cf78eeac1507263d0a350d4d5b30df0c8e1fe051a10c22b376e"
checksum = "f2c45cd61fefa9db6f254525d46e392b852e0e61d9a1fd36e5bd183450a556d5"
dependencies = [
"base64 0.22.1",
"chrono",
"hex",
"indexmap 1.9.3",
"indexmap 2.11.4",
"indexmap 2.11.1",
"schemars 0.9.0",
"schemars 1.0.4",
"serde",
@@ -7968,11 +7719,11 @@ dependencies = [
[[package]]
name = "serde_with_macros"
version = "3.14.1"
version = "3.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "327ada00f7d64abaac1e55a6911e90cf665aa051b9a561c7006c157f4633135e"
checksum = "de90945e6565ce0d9a25098082ed4ee4002e047cb59892c318d66821e14bb30f"
dependencies = [
"darling 0.21.3",
"darling 0.20.11",
"proc-macro2",
"quote 1.0.40",
"syn 2.0.106",
@@ -8091,6 +7842,18 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "simple_asn1"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb"
dependencies = [
"num-bigint",
"num-traits",
"thiserror 2.0.16",
"time",
]
[[package]]
name = "simplecss"
version = "0.2.2"
@@ -8287,7 +8050,7 @@ version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"
dependencies = [
"heck 0.5.0",
"heck",
"proc-macro2",
"quote 1.0.40",
"rustversion",
@@ -8453,7 +8216,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"
dependencies = [
"cfg-expr",
"heck 0.5.0",
"heck",
"pkg-config",
"toml 0.8.23",
"version-compare",
@@ -8581,12 +8344,11 @@ dependencies = [
[[package]]
name = "time"
version = "0.3.44"
version = "0.3.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d"
checksum = "83bde6f1ec10e72d583d91623c939f623002284ef622b87de38cfd546cbf2031"
dependencies = [
"deranged",
"itoa",
"libc",
"num-conv",
"num_threads",
@@ -8747,11 +8509,11 @@ dependencies = [
[[package]]
name = "tokio-rustls"
version = "0.26.3"
version = "0.26.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05f63835928ca123f1bef57abbcd23bb2ba0ac9ae1235f1e65bda0d06e7786bd"
checksum = "8e727b36a1a0e8b74c376ac2211e40c2c8af09fb4013c60d910495810f008e9b"
dependencies = [
"rustls 0.23.32",
"rustls 0.23.31",
"tokio 1.47.1",
]
@@ -8816,7 +8578,7 @@ version = "0.19.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"
dependencies = [
"indexmap 2.11.4",
"indexmap 2.11.1",
"toml_datetime",
"winnow 0.5.40",
]
@@ -8827,7 +8589,7 @@ version = "0.22.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
dependencies = [
"indexmap 2.11.4",
"indexmap 2.11.1",
"serde",
"serde_spanned",
"toml_datetime",
@@ -9305,7 +9067,7 @@ version = "4.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5afb1a60e207dca502682537fefcfd9921e71d0b83e9576060f09abc6efab23"
dependencies = [
"indexmap 2.11.4",
"indexmap 2.11.1",
"serde",
"serde_json",
"utoipa-gen",
@@ -9494,18 +9256,18 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "wasi"
version = "0.14.7+wasi-0.2.4"
version = "0.14.5+wasi-0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c"
checksum = "a4494f6290a82f5fe584817a676a34b9d6763e8d9d18204009fb31dceca98fd4"
dependencies = [
"wasip2",
]
[[package]]
name = "wasip2"
version = "1.0.1+wasi-0.2.4"
version = "1.0.0+wasi-0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
checksum = "03fa2761397e5bd52002cd7e73110c71af2109aca4e521a9f40473fe685b0a24"
dependencies = [
"wit-bindgen",
]
@@ -9521,9 +9283,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen"
version = "0.2.103"
version = "0.2.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab10a69fbd0a177f5f649ad4d8d3305499c42bab9aef2f7ff592d0ec8f833819"
checksum = "7e14915cadd45b529bb8d1f343c4ed0ac1de926144b746e2710f9cd05df6603b"
dependencies = [
"cfg-if",
"once_cell",
@@ -9534,9 +9296,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.103"
version = "0.2.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bb702423545a6007bbc368fde243ba47ca275e549c8a28617f56f6ba53b1d1c"
checksum = "e28d1ba982ca7923fd01448d5c30c6864d0a14109560296a162f80f305fb93bb"
dependencies = [
"bumpalo",
"log",
@@ -9548,9 +9310,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.53"
version = "0.4.51"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0b221ff421256839509adbb55998214a70d829d3a28c69b4a6672e9d2a42f67"
checksum = "0ca85039a9b469b38336411d6d6ced91f3fc87109a2a27b0c197663f5144dffe"
dependencies = [
"cfg-if",
"js-sys",
@@ -9561,9 +9323,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.103"
version = "0.2.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc65f4f411d91494355917b605e1480033152658d71f722a90647f56a70c88a0"
checksum = "7c3d463ae3eff775b0c45df9da45d68837702ac35af998361e2c84e7c5ec1b0d"
dependencies = [
"quote 1.0.40",
"wasm-bindgen-macro-support",
@@ -9571,9 +9333,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.103"
version = "0.2.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffc003a991398a8ee604a401e194b6b3a39677b3173d6e74495eb51b82e99a32"
checksum = "7bb4ce89b08211f923caf51d527662b75bdc9c9c7aab40f86dcb9fb85ac552aa"
dependencies = [
"proc-macro2",
"quote 1.0.40",
@@ -9584,9 +9346,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.103"
version = "0.2.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "293c37f4efa430ca14db3721dfbe48d8c33308096bd44d80ebaa775ab71ba1cf"
checksum = "f143854a3b13752c6950862c906306adb27c7e839f7414cec8fea35beab624c1"
dependencies = [
"unicode-ident",
]
@@ -9615,9 +9377,9 @@ dependencies = [
[[package]]
name = "web-sys"
version = "0.3.80"
version = "0.3.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fbe734895e869dc429d78c4b433f8d17d95f8d05317440b4fad5ab2d33e596dc"
checksum = "77e4b637749ff0d92b8fad63aa1f7cff3cbe125fd49c175cd6345e7272638b12"
dependencies = [
"js-sys",
"wasm-bindgen",
@@ -10124,9 +9886,9 @@ dependencies = [
[[package]]
name = "wit-bindgen"
version = "0.46.0"
version = "0.45.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
checksum = "5c573471f125075647d03df72e026074b7203790d41351cd6edc96f46bcccd36"
[[package]]
name = "writeable"

View File

@@ -34,7 +34,6 @@ COPY crates/services/january/Cargo.toml ./crates/services/january/
COPY crates/services/gifbox/Cargo.toml ./crates/services/gifbox/
COPY crates/daemons/crond/Cargo.toml ./crates/daemons/crond/
COPY crates/daemons/pushd/Cargo.toml ./crates/daemons/pushd/
COPY crates/daemons/voice-ingress/Cargo.toml ./crates/daemons/voice-ingress/
RUN sh /tmp/build-image-layer.sh deps
# Build all apps

View File

@@ -30,7 +30,6 @@ COPY crates/services/january/Cargo.toml ./crates/services/january/
COPY crates/services/gifbox/Cargo.toml ./crates/services/gifbox/
COPY crates/daemons/crond/Cargo.toml ./crates/daemons/crond/
COPY crates/daemons/pushd/Cargo.toml ./crates/daemons/pushd/
COPY crates/daemons/voice-ingress/Cargo.toml ./crates/daemons/voice-ingress/
RUN sh /tmp/build-image-layer.sh deps
# Build all apps

View File

@@ -26,11 +26,6 @@ january = "http://local.revolt.chat:14705"
voso_legacy = ""
voso_legacy_ws = ""
# Public urls for livekit nodes
# each entry here should have a corresponding entry under `api.livekit.nodes`
[hosts.livekit]
worldwide = "ws://local.revolt.chat:14706"
[api]
[api.smtp]
@@ -45,17 +40,8 @@ port = 14025
use_tls = false
use_starttls = false
[api.livekit]
# Config for livekit nodes
# Make sure to change the secret when deploying
# The key and secret should match the values livekit is using
[api.livekit.nodes.worldwide]
url = "http://livekit"
lat = 0.0
lon = 0.0
key = "worldwide_key"
secret = "ZjCofRlfm6GGtjlifmNpCDkcQbEIIVC0"
[api.security]
token_secret = "trolt"
[files.s3]
# S3 protocol endpoint

View File

@@ -40,7 +40,7 @@ services:
# Rabbit
rabbit:
image: rabbitmq:4-management
image: rabbitmq:3-management
environment:
RABBITMQ_DEFAULT_USER: rabbituser
RABBITMQ_DEFAULT_PASS: rabbitpass

View File

@@ -1,5 +1,5 @@
# Build Stage
FROM ghcr.io/revoltchat/base:latest AS builder
FROM ghcr.io/stoatchat/base:latest AS builder
FROM debian:12 AS debian
# Bundle Stage

View File

@@ -136,7 +136,6 @@ impl handshake::server::Callback for WebsocketHandshakeCallback {
channels: false,
members: false,
emojis: false,
voice_states: false,
user_settings: Vec::new(),
channel_unreads: false,
policy_changes: false,
@@ -169,7 +168,6 @@ impl handshake::server::Callback for WebsocketHandshakeCallback {
"channels" => ready_payload_fields.channels = true,
"members" => ready_payload_fields.members = true,
"emojis" => ready_payload_fields.emojis = true,
"voice_states" => ready_payload_fields.voice_states = true,
"channel_unreads" => ready_payload_fields.channel_unreads = true,
"user_settings" => {
if let Some(subkey) = captures.get(1) {

View File

@@ -4,7 +4,6 @@ use futures::future::join_all;
use revolt_database::{
events::client::{EventV1, ReadyPayloadFields},
util::permissions::DatabasePermissionQuery,
voice::get_channel_voice_state,
Channel, Database, Member, MemberCompositeKey, Presence, RelationshipStatus,
};
use revolt_models::v0;
@@ -18,9 +17,8 @@ use super::state::{Cache, State};
impl Cache {
/// Check whether the current user can view a channel
pub async fn can_view_channel(&self, db: &Database, channel: &Channel) -> bool {
#[allow(deprecated)]
match &channel {
Channel::TextChannel { server, .. } => {
Channel::TextChannel { server, .. } | Channel::VoiceChannel { server, .. } => {
let member = self.members.get(server);
let server = self.servers.get(server);
let mut query =
@@ -212,28 +210,6 @@ impl State {
None
};
let voice_states = if fields.voice_states {
// fetch voice states for all the channels we can see
let mut voice_states = Vec::new();
for channel in channels.iter().filter(|c| {
matches!(
c,
Channel::DirectMessage { .. }
| Channel::Group { .. }
| Channel::TextChannel { voice: Some(_), .. }
)
}) {
if let Ok(Some(voice_state)) = get_channel_voice_state(channel).await {
voice_states.push(voice_state)
}
}
Some(voice_states)
} else {
None
};
// Copy data into local state cache.
self.cache.users = users.iter().cloned().map(|x| (x.id.clone(), x)).collect();
self.cache
@@ -292,8 +268,6 @@ impl State {
} else {
None
},
voice_states,
emojis,
user_settings,
channel_unreads,
@@ -311,14 +285,19 @@ impl State {
let id = &id.to_string();
for (channel_id, channel) in &self.cache.channels {
if channel.server() == Some(id) {
channel_ids.insert(channel_id.clone());
match channel {
Channel::TextChannel { server, .. } | Channel::VoiceChannel { server, .. } => {
if server == id {
channel_ids.insert(channel_id.clone());
if self.cache.can_view_channel(db, channel).await {
added_channels.push(channel_id.clone());
} else {
removed_channels.push(channel_id.clone());
if self.cache.can_view_channel(db, channel).await {
added_channels.push(channel_id.clone());
} else {
removed_channels.push(channel_id.clone());
}
}
}
_ => {}
}
}
@@ -486,7 +465,6 @@ impl State {
server,
channels,
emojis: _,
voice_states: _,
} => {
self.insert_subscription(id.clone()).await;

View File

@@ -1,9 +1,7 @@
use std::{env, sync::Arc};
use std::env;
use async_std::net::TcpListener;
use revolt_presence::clear_region;
use once_cell::sync::OnceCell;
use revolt_database::voice::VoiceClient;
#[macro_use]
extern crate log;
@@ -14,15 +12,6 @@ pub mod events;
mod database;
mod websocket;
pub static VOICE_CLIENT: OnceCell<Arc<VoiceClient>> = OnceCell::new();
pub fn get_voice_client() -> Arc<VoiceClient> {
VOICE_CLIENT
.get()
.expect("get_voice_client called before set")
.clone()
}
#[async_std::main]
async fn main() {
// Configure requirements for Bonfire.
@@ -35,8 +24,6 @@ async fn main() {
clear_region(None).await;
}
VOICE_CLIENT.set(Arc::new(VoiceClient::from_revolt_config().await)).unwrap();
// Setup a TCP listener to accept WebSocket connections on.
// By default, we bind to port 14703 on all interfaces.
let bind = env::var("HOST").unwrap_or_else(|_| "0.0.0.0:14703".into());

View File

@@ -17,9 +17,11 @@ use redis_kiss::{PayloadType, REDIS_PAYLOAD_TYPE, REDIS_URI};
use revolt_config::report_internal_error;
use revolt_database::{
events::{client::EventV1, server::ClientMessage},
util::oauth2,
iso8601_timestamp::Timestamp,
Database, User, UserHint,
};
use revolt_models::v0;
use revolt_presence::{create_session, delete_session};
use async_std::{
@@ -88,23 +90,51 @@ pub async fn client(db: &'static Database, stream: TcpStream, addr: SocketAddr)
return;
};
// Presume the token is a proper token first
let (user, session_id) = match User::from_token(db, token, UserHint::Any).await {
Ok(user) => user,
Err(err) => {
write
.send(config.encode(&EventV1::Error { data: err }))
Ok((user, session_id)) => {
db.update_session_last_seen(&session_id, Timestamp::now_utc())
.await
.ok();
return;
(user, session_id)
},
Err(err) => {
let revolt_config = revolt_config::config().await;
// If it fails to find the user from the token see if its an OAuth2 token
let res = match oauth2::decode_token(&revolt_config.api.security.token_secret, token) {
// Check if the OAuth2 token is allowed to establish an events websocket
Ok(claims) => if !claims.scopes.contains(&v0::OAuth2Scope::Events) {
// TODO: maybe a last_seen system for OAuth2 as well
db.fetch_user(&claims.sub).await.map(|user| (user, claims.jti))
} else {
Err(create_error!(MissingScope { scope: v0::OAuth2Scope::Events.to_string() }))
},
// If its expired return an error
Err(e) => if e.into_kind() == oauth2::JWTErrorKind::ExpiredSignature {
Err(create_error!(ExpiredToken))
} else {
// Finally re-return the error from User::from_token if everything else fails to avoid a confusing error
Err(err)
}
};
match res {
Ok(user) => user,
Err(err) => {
write
.send(config.encode(&EventV1::Error { data: err }))
.await
.ok();
return;
}
}
}
};
info!("User {addr:?} authenticated as @{}", user.username);
db.update_session_last_seen(&session_id, Timestamp::now_utc())
.await
.ok();
// Create local state.
let mut state = State::from(user, session_id);
let user_id = state.cache.user_id.clone();

View File

@@ -22,8 +22,6 @@ january = "http://local.revolt.chat/january"
voso_legacy = ""
voso_legacy_ws = ""
[hosts.livekit]
[rabbit]
host = "rabbit"
port = 5672
@@ -58,6 +56,8 @@ voso_legacy_token = ""
trust_cloudflare = false
# easypwned endpoint
easypwned = ""
# Secret used to encode and decode tokens
token_secret = ""
# Tenor API Key
tenor_key = ""
@@ -70,14 +70,9 @@ hcaptcha_sitekey = ""
# Maximum concurrent connections (to proxy server)
max_concurrent_connections = 50
[api.livekit]
# How long to ring devices for when calling in dms/groups, in seconds
call_ring_duration = 30
[api.livekit.nodes]
[api.users]
[pushd]
# this changes the names of the queues to not overlap
# prod/beta if they happen to be on the same exchange/instance.
@@ -94,7 +89,6 @@ message_queue = "notifications.origin.message"
mass_mention_queue = "notifications.origin.mass_mention" # handles messages that contain role or everyone mentions
fr_accepted_queue = "notifications.ingest.fr_accepted" # friend request accepted
fr_received_queue = "notifications.ingest.fr_received" # friend request received
dm_call_queue = "notifications.ingest.dm_call" # friend request received
generic_queue = "notifications.ingest.generic" # generic messages (title + body)
ack_queue = "notifications.process.ack" # updates badges for apple devices
@@ -238,18 +232,6 @@ message_attachments = 5
# Maximum number of servers the user can create/join
servers = 50
# Maximum audio frequency (Hz) in voice calls
voice_quality = 16000
# Whether the user can use video streams in voice calls
video = true
# Mamimum resolution (width, height) of video streams in voice calls
video_resolution = [1080, 720]
# Minimum and maximum aspect ratio of video streams in voice calls
video_aspect_ratio = [0.3, 2.5]
[features.limits.new_user.file_upload_size_limit]
# Maximum file size limits (in bytes)
attachments = 20_000_000
@@ -277,18 +259,6 @@ message_attachments = 5
# Maximum number of servers the user can create/join
servers = 100
# Maximum audio frequency (Hz) in voice calls
voice_quality = 16000
# Whether the user can use video streams in voice calls
video = true
# Mamimum resolution (width, height) of video streams in voice calls
video_resolution = [1080, 720]
# Minimum and maximum aspect ratio of video streams in voice calls
video_aspect_ratio = [0.3, 2.5]
[features.limits.default.file_upload_size_limit]
# Maximum file size limits (in bytes)
attachments = 20_000_000
@@ -307,7 +277,6 @@ process_message_delay_limit = 5
# Configuration for Sentry error reporting
api = ""
events = ""
voice_ingress = ""
files = ""
proxy = ""
pushd = ""

View File

@@ -125,7 +125,8 @@ pub struct Hosts {
pub events: String,
pub autumn: String,
pub january: String,
pub livekit: HashMap<String, String>,
pub voso_legacy: String,
pub voso_legacy_ws: String,
}
#[derive(Deserialize, Debug, Clone)]
@@ -189,6 +190,7 @@ pub struct ApiSecurity {
pub captcha: ApiSecurityCaptcha,
pub trust_cloudflare: bool,
pub easypwned: String,
pub token_secret: String,
pub tenor_key: String,
}
@@ -197,25 +199,6 @@ pub struct ApiWorkers {
pub max_concurrent_connections: usize,
}
#[derive(Deserialize, Debug, Clone)]
pub struct ApiLiveKit {
pub call_ring_duration: usize,
pub nodes: HashMap<String, LiveKitNode>,
}
#[derive(Deserialize, Debug, Clone)]
pub struct LiveKitNode {
pub url: String,
pub lat: f64,
pub lon: f64,
pub key: String,
pub secret: String,
// whether to hide the node in the nodes list
#[serde(default)]
pub private: bool,
}
#[derive(Deserialize, Debug, Clone)]
pub struct ApiUsers {
pub early_adopter_cutoff: Option<u64>,
@@ -227,7 +210,6 @@ pub struct Api {
pub smtp: ApiSmtp,
pub security: ApiSecurity,
pub workers: ApiWorkers,
pub livekit: ApiLiveKit,
pub users: ApiUsers,
}
@@ -240,7 +222,6 @@ pub struct Pushd {
// Queues
pub message_queue: String,
pub mass_mention_queue: String,
pub dm_call_queue: String,
pub fr_accepted_queue: String,
pub fr_received_queue: String,
pub generic_queue: String,
@@ -271,10 +252,6 @@ impl Pushd {
self.get_routing_key(self.mass_mention_queue.clone())
}
pub fn get_dm_call_routing_key(&self) -> String {
self.get_routing_key(self.dm_call_queue.clone())
}
pub fn get_fr_accepted_routing_key(&self) -> String {
self.get_routing_key(self.fr_accepted_queue.clone())
}
@@ -342,10 +319,6 @@ pub struct FeaturesLimits {
pub message_length: usize,
pub message_attachments: usize,
pub servers: usize,
pub voice_quality: u32,
pub video: bool,
pub video_resolution: [u32; 2],
pub video_aspect_ratio: [f32; 2],
pub file_upload_size_limit: HashMap<String, usize>,
}
@@ -390,7 +363,6 @@ pub struct Features {
pub struct Sentry {
pub api: String,
pub events: String,
pub voice_ingress: String,
pub files: String,
pub proxy: String,
pub pushd: String,

View File

@@ -53,6 +53,8 @@ linkify = { optional = true, version = "0.8.1" }
url-escape = { optional = true, version = "0.1.1" }
validator = { version = "0.16", features = ["derive"] }
isahc = { optional = true, version = "1.7", features = ["json"] }
jsonwebtoken = "9.3.1"
chrono = "0.4"
# Serialisation
serde_json = "1"
@@ -96,8 +98,3 @@ authifier = { version = "1.0.15" }
# RabbitMQ
amqprs = { version = "1.7.0" }
# Voice
livekit-api = "0.4.4"
livekit-protocol = "0.4.0"
livekit-runtime = { version = "0.3.1", features = ["tokio"] }

View File

@@ -2,8 +2,7 @@ use std::collections::HashSet;
use crate::events::rabbit::*;
use crate::User;
use amqprs::channel::{BasicPublishArguments, ExchangeDeclareArguments};
use amqprs::connection::OpenConnectionArguments;
use amqprs::channel::BasicPublishArguments;
use amqprs::{channel::Channel, connection::Connection, error::Error as AMQPError};
use amqprs::{BasicProperties, FieldTable};
use revolt_models::v0::PushNotification;
@@ -26,35 +25,6 @@ impl AMQP {
}
}
pub async fn new_auto() -> AMQP {
let config = revolt_config::config().await;
let connection = Connection::open(&OpenConnectionArguments::new(
&config.rabbit.host,
config.rabbit.port,
&config.rabbit.username,
&config.rabbit.password,
))
.await
.expect("Failed to connect to RabbitMQ");
let channel = connection
.open_channel(None)
.await
.expect("Failed to open RabbitMQ channel");
channel
.exchange_declare(
ExchangeDeclareArguments::new(&config.pushd.exchange, "direct")
.durable(true)
.finish(),
)
.await
.expect("Failed to declare exchange");
AMQP::new(connection, channel)
}
pub async fn friend_request_accepted(
&self,
accepted_request_user: &User,
@@ -270,50 +240,4 @@ impl AMQP {
)
.await
}
/// # DM Call Update
/// Used to send an update about a DM call, eg. start or end of a call.
/// Recipients can be used to narrow the scope of recipients, otherwise all recipients will be notified.
/// `ended` refers to the ringing period, not necessarily the call itself.
pub async fn dm_call_updated(
&self,
initiator_id: &str,
channel_id: &str,
started_at: Option<&str>,
ended: bool,
recipients: Option<Vec<String>>,
) -> Result<(), AMQPError> {
let config = revolt_config::config().await;
let payload = InternalDmCallPayload {
payload: DmCallPayload {
initiator_id: initiator_id.to_string(),
channel_id: channel_id.to_string(),
started_at: started_at.map(|f| f.to_string()),
ended,
},
recipients,
};
let payload = to_string(&payload).unwrap();
debug!(
"Sending dm call update payload on channel {}: {}",
config.pushd.get_dm_call_routing_key(),
payload
);
self.channel
.basic_publish(
BasicProperties::default()
.with_content_type("application/json")
.with_persistence(true)
.finish(),
payload.into(),
BasicPublishArguments::new(
&config.pushd.exchange,
&config.pushd.get_dm_call_routing_key(),
),
)
.await
}
}

View File

@@ -35,7 +35,7 @@ pub enum DatabaseInfo {
}
/// Database
#[derive(Clone, Debug)]
#[derive(Clone)]
pub enum Database {
/// Mock database
Reference(ReferenceDb),

View File

@@ -11,7 +11,6 @@ use serde::Serialize;
database_derived!(
/// MongoDB implementation
#[derive(Debug)]
pub struct MongoDb(pub ::mongodb::Client, pub String);
);

View File

@@ -5,13 +5,14 @@ use futures::lock::Mutex;
use crate::{
Bot, Channel, ChannelCompositeKey, ChannelUnread, Emoji, File, FileHash, Invite, Member,
MemberCompositeKey, Message, PolicyChange, RatelimitEvent, Report, Server, ServerBan, Snapshot,
User, UserSettings, Webhook,
User, UserSettings, Webhook, AuthorizedBotId, AuthorizedBot,
};
database_derived!(
/// Reference implementation
#[derive(Default, Debug)]
#[derive(Default)]
pub struct ReferenceDb {
pub authorized_bots: Arc<Mutex<HashMap<AuthorizedBotId, AuthorizedBot>>>,
pub bots: Arc<Mutex<HashMap<String, Bot>>>,
pub channels: Arc<Mutex<HashMap<String, Channel>>>,
pub channel_invites: Arc<Mutex<HashMap<String, Invite>>>,

View File

@@ -3,7 +3,10 @@ use revolt_result::Error;
use serde::{Deserialize, Serialize};
use revolt_models::v0::{
AppendMessage, Channel, ChannelUnread, ChannelVoiceState, Emoji, FieldsChannel, FieldsMember, FieldsMessage, FieldsRole, FieldsServer, FieldsUser, FieldsWebhook, Member, MemberCompositeKey, Message, PartialChannel, PartialMember, PartialMessage, PartialRole, PartialServer, PartialUser, PartialUserVoiceState, PartialWebhook, PolicyChange, RemovalIntention, Report, Server, User, UserSettings, UserVoiceState, Webhook
AppendMessage, Channel, ChannelUnread, Emoji, FieldsChannel, FieldsMember, FieldsMessage,
FieldsRole, FieldsServer, FieldsUser, FieldsWebhook, Member, MemberCompositeKey, Message,
PartialChannel, PartialMember, PartialMessage, PartialRole, PartialServer, PartialUser,
PartialWebhook, PolicyChange, RemovalIntention, Report, Server, User, UserSettings, Webhook,
};
use crate::Database;
@@ -24,7 +27,6 @@ pub struct ReadyPayloadFields {
pub channels: bool,
pub members: bool,
pub emojis: bool,
pub voice_states: bool,
pub user_settings: Vec<String>,
pub channel_unreads: bool,
pub policy_changes: bool,
@@ -38,7 +40,6 @@ impl Default for ReadyPayloadFields {
channels: true,
members: true,
emojis: true,
voice_states: true,
user_settings: Vec::new(),
channel_unreads: false,
policy_changes: true,
@@ -71,8 +72,6 @@ pub enum EventV1 {
members: Option<Vec<Member>>,
#[serde(skip_serializing_if = "Option::is_none")]
emojis: Option<Vec<Emoji>>,
#[serde(skip_serializing_if = "Option::is_none")]
voice_states: Option<Vec<ChannelVoiceState>>,
#[serde(skip_serializing_if = "Option::is_none")]
user_settings: Option<UserSettings>,
@@ -139,7 +138,6 @@ pub enum EventV1 {
server: Server,
channels: Vec<Channel>,
emojis: Vec<Emoji>,
voice_states: Vec<ChannelVoiceState>
},
/// Update existing server
@@ -272,31 +270,6 @@ pub enum EventV1 {
/// Auth events
Auth(AuthifierEvent),
/// Voice events
VoiceChannelJoin {
id: String,
state: UserVoiceState,
},
VoiceChannelLeave {
id: String,
user: String,
},
VoiceChannelMove {
user: String,
from: String,
to: String,
state: UserVoiceState
},
UserVoiceStateUpdate {
id: String,
channel_id: String,
data: PartialUserVoiceState,
},
UserMoveVoiceChannel {
node: String,
token: String
}
}
impl EventV1 {

View File

@@ -37,20 +37,6 @@ pub struct GenericPayload {
pub user: User,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct DmCallPayload {
pub initiator_id: String,
pub channel_id: String,
pub started_at: Option<String>,
pub ended: bool,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct InternalDmCallPayload {
pub payload: DmCallPayload,
pub recipients: Option<Vec<String>>,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "type", content = "data")]
#[allow(clippy::large_enum_variant)]
@@ -60,7 +46,6 @@ pub enum PayloadKind {
FRReceived(FRReceivedPayload),
BadgeUpdate(usize),
Generic(GenericPayload),
DmCallStartEnd(DmCallPayload),
}
#[derive(Serialize, Deserialize)]

View File

@@ -112,9 +112,6 @@ pub mod tasks;
mod amqp;
pub use amqp::amqp::AMQP;
pub mod voice;
/// Utility function to check if a boolean value is false
pub fn if_false(t: &bool) -> bool {
!t

View File

@@ -9,13 +9,14 @@ use crate::{
bson::{doc, from_bson, from_document, to_document, Bson, DateTime, Document},
options::FindOptions,
},
AbstractServers, Invite, MongoDb, User, DISCRIMINATOR_SEARCH_SPACE,
AbstractChannels, AbstractServers, Channel, Invite, MongoDb, User, DISCRIMINATOR_SEARCH_SPACE,
};
use bson::{oid::ObjectId, to_bson};
use futures::StreamExt;
use iso8601_timestamp::Timestamp;
use rand::seq::SliceRandom;
use revolt_permissions::{ChannelPermission, DEFAULT_WEBHOOK_PERMISSIONS};
use revolt_permissions::DEFAULT_WEBHOOK_PERMISSIONS;
use revolt_result::{Error, ErrorType};
use serde::{Deserialize, Serialize};
use unicode_segmentation::UnicodeSegmentation;
@@ -25,7 +26,7 @@ struct MigrationInfo {
revision: i32,
}
pub const LATEST_REVISION: i32 = 48; // MUST BE +1 to last migration
pub const LATEST_REVISION: i32 = 42; // MUST BE +1 to last migration
pub async fn migrate_database(db: &MongoDb) {
let migrations = db.col::<Document>("migrations");
@@ -913,7 +914,6 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
}
if revision <= 26 {
// Need to migrate fields on attachments, change `user_id`, `object_id`, etc to `parent`.
info!("Running migration [revision 26 / 15-05-2024]: fix invites being incorrectly serialized with wrong enum tagging.");
auto_derived!(
@@ -1080,14 +1080,6 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
channel_id: String,
}
#[allow(clippy::enum_variant_names)]
#[derive(serde::Serialize, serde::Deserialize)]
enum Channel {
Group { owner: String },
TextChannel { server: String },
VoiceChannel { server: String }
}
let webhooks = db
.db()
.collection::<WebhookShell>("channel_webhooks")
@@ -1099,8 +1091,8 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
.await;
for webhook in webhooks {
match db.col::<Channel>("channels").find_one(doc! { "_id": &webhook.channel_id }).await.unwrap() {
Some(channel) => {
match db.fetch_channel(&webhook.channel_id).await {
Ok(channel) => {
let creator_id = match channel {
Channel::Group { owner, .. } => owner,
Channel::TextChannel { server, .. }
@@ -1108,6 +1100,7 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
let server = db.fetch_server(&server).await.expect("server");
server.owner
}
_ => unreachable!("not server or group channel!"),
};
db.db()
@@ -1125,13 +1118,17 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
.await
.expect("update webhook");
}
None => {
Err(Error {
error_type: ErrorType::NotFound,
..
}) => {
db.db()
.collection::<WebhookShell>("channel_webhooks")
.delete_one(doc! { "_id": webhook._id })
.await
.expect("failed to delete invalid webhook");
}
Err(err) => panic!("{err:?}"),
}
}
}
@@ -1172,9 +1169,9 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
.expect("failed to update users");
}
if revision <= 43 {
if revision <= 41 {
info!(
"Running migration [revision 43 / 05-06-2025]: convert role ranks to uniform numbers."
"Running migration [revision 41 / 05-06-2025]: convert role ranks to uniform numbers."
);
#[derive(Serialize, Deserialize, Clone)]
@@ -1229,41 +1226,6 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
}
}
if revision <= 46 {
info!("Running migration [revision 46 / 29-04-2025]: Convert all `VoiceChannel`'s into `TextChannel`");
db.col::<Document>("channels")
.update_many(
doc! { "channel_type": "VoiceChannel" },
doc! {
"$set": {
"channel_type": "TextChannel",
"voice": {}
}
}
)
.await
.expect("Failed to update voice channels");
};
if revision <= 47 {
info!("Running migration [revision 47 / 29-04-2025]: Add Video to default permissions");
db.col::<Document>("servers")
.update_many(
doc! { },
doc! {
"$bit": {
"default_permissions": {
"or": ChannelPermission::Video as i64
},
}
}
)
.await
.expect("Failed to update default_permissions");
};
// Reminder to update LATEST_REVISION when adding new migrations.
LATEST_REVISION.max(revision)
}

View File

@@ -0,0 +1,5 @@
mod model;
mod ops;
pub use model::*;
pub use ops::*;

View File

@@ -0,0 +1,30 @@
use iso8601_timestamp::Timestamp;
use crate::OAuth2Scope;
auto_derived! (
/// Unique id of the user and bot
#[derive(Hash)]
pub struct AuthorizedBotId {
/// User id
pub user: String,
/// Bot Id
pub bot: String,
}
pub struct AuthorizedBot {
/// Unique Id
#[serde(rename = "_id")]
pub id: AuthorizedBotId,
/// When the authorized oauth2 bot connection was created at
pub created_at: Timestamp,
/// If and when the authorized oauth2 bot connection was revoked at
pub deauthorized_at: Option<Timestamp>,
/// Scopes the bot has access to
pub scope: Vec<OAuth2Scope>,
}
);

View File

@@ -0,0 +1,27 @@
use revolt_result::Result;
use crate::{AuthorizedBot, AuthorizedBotId};
mod mongodb;
mod reference;
#[async_trait]
pub trait AbstractAuthorizedBots: Sync + Send {
/// Insert emoji into database.
async fn insert_authorized_bot(&self, authorized_bot: &AuthorizedBot) -> Result<()>;
/// Fetch an authorized bot by its id
async fn fetch_authorized_bot(&self, id: &AuthorizedBotId) -> Result<AuthorizedBot>;
/// Fetch a users authorized bot by its id
async fn fetch_users_authorized_bots(&self, user_id: &str) -> Result<Vec<AuthorizedBot>>;
/// Deletes an authorized bot
async fn delete_authorized_bot(&self, id: &AuthorizedBotId) -> Result<()>;
/// Deauthorizes an authorized bot
async fn deauthorize_authorized_bot(&self, id: &AuthorizedBotId) -> Result<AuthorizedBot>;
// Fetches all authorized bots which have been deauthorized
async fn fetch_deauthorized_authorized_bots(&self) -> Result<Vec<AuthorizedBot>>;
}

View File

@@ -0,0 +1,71 @@
use bson::to_bson;
use revolt_result::Result;
use iso8601_timestamp::Timestamp;
use crate::{MongoDb, AuthorizedBot, AuthorizedBotId};
use super::AbstractAuthorizedBots;
static COL: &str = "authorized_bots";
#[async_trait]
impl AbstractAuthorizedBots for MongoDb {
/// Insert an authorized bot into database.
async fn insert_authorized_bot(&self, authorized_bot: &AuthorizedBot) -> Result<()> {
query!(self, insert_one, COL, &authorized_bot).map(|_| ())
}
/// Fetch an authorized bot by its id
async fn fetch_authorized_bot(&self, id: &AuthorizedBotId) -> Result<AuthorizedBot> {
query!(
self,
find_one,
COL,
doc! {
"_id.user": &id.user,
"_id.bot": &id.bot
}
)?.ok_or_else(|| create_error!(NotFound))
}
/// Fetch a users authorized bot by its id
async fn fetch_users_authorized_bots(&self, user_id: &str) -> Result<Vec<AuthorizedBot>> {
query!(self, find, COL, doc! { "_id.user": &user_id })
}
/// Deletes an authorized bot
async fn delete_authorized_bot(&self, id: &AuthorizedBotId) -> Result<()> {
query!(self, delete_one, COL, doc! { "_id.user": &id.user, "_id.bot": &id.bot }).map(|_| ())
}
/// Deauthorizes an authorized bot
async fn deauthorize_authorized_bot(&self, id: &AuthorizedBotId) -> Result<AuthorizedBot> {
self.col::<AuthorizedBot>(COL)
.find_one_and_update(
doc! {
"_id.user": &id.user,
"_id.bot": &id.bot
},
doc! {
"$set": {
"deauthorized_at": to_bson(&Timestamp::now_utc()).unwrap()
}
}
)
.await
.map_err(|_| create_database_error!("find_one_and_update", COL))
.and_then(|opt| opt.ok_or_else(|| create_database_error!("find_one_and_update", COL)))
}
// Fetches all authorized bots which have been deauthorized
async fn fetch_deauthorized_authorized_bots(&self) -> Result<Vec<AuthorizedBot>> {
query!(
self,
find,
COL,
doc! {
"deauthorized_at": { "$exists": true }
}
)
}
}

View File

@@ -0,0 +1,76 @@
use revolt_result::Result;
use iso8601_timestamp::Timestamp;
use crate::{ReferenceDb, AuthorizedBot, AuthorizedBotId};
use super::AbstractAuthorizedBots;
#[async_trait]
impl AbstractAuthorizedBots for ReferenceDb {
/// Insert an authorized bot into database.
async fn insert_authorized_bot(&self, authorized_bot: &AuthorizedBot) -> Result<()> {
let mut authorized_bots = self.authorized_bots.lock().await;
if authorized_bots.contains_key(&authorized_bot.id) {
Err(create_database_error!("insert", "authorized_bots"))
} else {
authorized_bots.insert(authorized_bot.id.clone(), authorized_bot.clone());
Ok(())
}
}
/// Fetch an authorized bot by its id
async fn fetch_authorized_bot(&self, id: &AuthorizedBotId) -> Result<AuthorizedBot> {
let authorized_bots = self.authorized_bots.lock().await;
authorized_bots.get(id).cloned().ok_or_else(|| create_error!(NotFound))
}
/// Fetch a users authorized bot by its id
async fn fetch_users_authorized_bots(&self, user_id: &str) -> Result<Vec<AuthorizedBot>> {
let authorized_bots = self.authorized_bots.lock().await;
Ok(authorized_bots
.values()
.filter(|authorized_bot| authorized_bot.id.user == user_id)
.cloned()
.collect()
)
}
/// Deletes an authorized bot
async fn delete_authorized_bot(&self, id: &AuthorizedBotId) -> Result<()> {
let mut authorized_bots = self.authorized_bots.lock().await;
if authorized_bots.remove(id).is_some() {
Ok(())
} else {
Err(create_error!(NotFound))
}
}
/// Deauthorizes an authorized bot
async fn deauthorize_authorized_bot(&self, id: &AuthorizedBotId) -> Result<AuthorizedBot> {
let mut authorized_bots = self.authorized_bots.lock().await;
if let Some(authorized_bot) = authorized_bots.get_mut(id) {
authorized_bot.deauthorized_at = Some(Timestamp::now_utc());
Ok(authorized_bot.clone())
} else {
Err(create_error!(NotFound))
}
}
// Fetches all authorized bots which have been deauthorized
async fn fetch_deauthorized_authorized_bots(&self) -> Result<Vec<AuthorizedBot>> {
let authorized_bots = self.authorized_bots.lock().await;
Ok(authorized_bots
.values()
.filter(|authorized_bot| authorized_bot.deauthorized_at.is_some())
.cloned()
.collect()
)
}
}

View File

@@ -1,5 +1,6 @@
use revolt_result::Result;
use ulid::Ulid;
use std::collections::HashMap;
use crate::{events::client::EventV1, BotInformation, Database, PartialUser, User};
@@ -35,6 +36,10 @@ auto_derived_partial!(
#[serde(skip_serializing_if = "String::is_empty", default)]
pub privacy_policy_url: String,
/// Oauth2 bot settings
#[serde(skip_serializing_if = "Option::is_none", default)]
pub oauth2: Option<BotOauth2>,
/// Enum of bot flags
#[serde(skip_serializing_if = "Option::is_none")]
pub flags: Option<i32>,
@@ -42,11 +47,52 @@ auto_derived_partial!(
"PartialBot"
);
auto_derived!(
#[derive(Copy, Hash)]
pub enum OAuth2Scope {
#[serde(rename = "read:identify")]
ReadIdentify,
#[serde(rename = "read:servers")]
ReadServers,
#[serde(rename = "write:files")]
WriteFiles,
#[serde(rename = "events")]
Events,
#[serde(rename = "full")]
Full,
}
pub struct OAuth2ScopeReasoning {
pub allow: String,
pub deny: String
}
);
auto_derived_partial!(
pub struct BotOauth2 {
/// Whether the oauth2 client is public and should not receive a secret key
#[serde(default)]
pub public: bool,
/// Secret key used for authorisation, not provided if the client is public
#[serde(default)]
pub secret: Option<String>,
/// Allowed redirects for the authorisation
#[serde(default)]
pub redirects: Vec<String>,
/// Mapping of allowed scopes and the reasonings
#[serde(default)]
pub allowed_scopes: HashMap<OAuth2Scope, OAuth2ScopeReasoning>,
},
"PartialBotOauth2"
);
auto_derived!(
/// Optional fields on bot object
pub enum FieldsBot {
Token,
InteractionsURL,
Oauth2,
Oauth2Secret,
}
);
@@ -63,11 +109,24 @@ impl Default for Bot {
interactions_url: Default::default(),
terms_of_service_url: Default::default(),
privacy_policy_url: Default::default(),
oauth2: Default::default(),
flags: Default::default(),
}
}
}
#[allow(clippy::derivable_impls)]
impl Default for BotOauth2 {
fn default() -> Self {
Self {
public: false,
secret: Some(nanoid::nanoid!(64)),
redirects: Vec::new(),
allowed_scopes: HashMap::new(),
}
}
}
#[allow(clippy::disallowed_methods)]
impl Bot {
/// Create a new bot
@@ -124,6 +183,14 @@ impl Bot {
FieldsBot::Token => self.token = nanoid::nanoid!(64),
FieldsBot::InteractionsURL => {
self.interactions_url = String::new();
},
FieldsBot::Oauth2 => self.oauth2 = None,
FieldsBot::Oauth2Secret => {
if let Some(oauth2) = &mut self.oauth2 {
if !oauth2.public {
oauth2.secret = Some(nanoid::nanoid!(64))
}
}
}
}
}

View File

@@ -87,6 +87,8 @@ impl IntoDocumentPath for FieldsBot {
match self {
FieldsBot::InteractionsURL => Some("interactions_url"),
FieldsBot::Token => None,
FieldsBot::Oauth2 => Some("oauth2"),
FieldsBot::Oauth2Secret => None,
}
}
}

View File

@@ -69,7 +69,7 @@ impl Invite {
creator: creator.id.clone(),
channel: id.clone(),
}),
Channel::TextChannel { id, server, .. } => {
Channel::TextChannel { id, server, .. } | Channel::VoiceChannel { id, server, .. } => {
Ok(Invite::Server {
code,
creator: creator.id.clone(),

View File

@@ -1,5 +1,4 @@
#![allow(deprecated)]
use std::{borrow::Cow, collections::HashMap};
use std::collections::HashMap;
use revolt_config::config;
use revolt_models::v0::{self, MessageAuthor};
@@ -9,7 +8,8 @@ use serde::{Deserialize, Serialize};
use ulid::Ulid;
use crate::{
events::client::EventV1, Database, File, PartialServer, Server, SystemMessage, User, AMQP,
events::client::EventV1, Database, File, PartialServer,
Server, SystemMessage, User, AMQP,
};
#[cfg(feature = "mongodb")]
@@ -106,18 +106,38 @@ auto_derived!(
/// Whether this channel is marked as not safe for work
#[serde(skip_serializing_if = "crate::if_false", default)]
nsfw: bool,
/// Voice Information for when this channel is also a voice channel
#[serde(skip_serializing_if = "Option::is_none")]
voice: Option<VoiceInformation>,
},
}
/// Voice channel belonging to a server
VoiceChannel {
/// Unique Id
#[serde(rename = "_id")]
id: String,
/// Id of the server this channel belongs to
server: String,
#[derive(Default)]
pub struct VoiceInformation {
/// Maximium amount of users allowed in the voice channel at once
#[serde(skip_serializing_if = "Option::is_none")]
pub max_users: Option<usize>,
/// Display name of the channel
name: String,
#[serde(skip_serializing_if = "Option::is_none")]
/// Channel description
description: Option<String>,
/// Custom icon attachment
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<File>,
/// Default permissions assigned to users in this channel
#[serde(skip_serializing_if = "Option::is_none")]
default_permissions: Option<OverrideField>,
/// Permissions assigned based on role to this channel
#[serde(
default = "HashMap::<String, OverrideField>::new",
skip_serializing_if = "HashMap::<String, OverrideField>::is_empty"
)]
role_permissions: HashMap<String, OverrideField>,
/// Whether this channel is marked as not safe for work
#[serde(skip_serializing_if = "crate::if_false", default)]
nsfw: bool,
},
}
);
@@ -144,8 +164,6 @@ auto_derived!(
pub default_permissions: Option<OverrideField>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_message_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub voice: Option<VoiceInformation>,
}
/// Optional fields on channel object
@@ -153,7 +171,6 @@ auto_derived!(
Description,
Icon,
DefaultPermissions,
Voice,
}
);
@@ -205,19 +222,16 @@ impl Channel {
default_permissions: None,
role_permissions: HashMap::new(),
nsfw: data.nsfw.unwrap_or(false),
voice: data.voice.map(|voice| voice.into()),
},
v0::LegacyServerChannelType::Voice => Channel::TextChannel {
v0::LegacyServerChannelType::Voice => Channel::VoiceChannel {
id: id.clone(),
server: server.id.to_owned(),
name: data.name,
description: data.description,
icon: None,
last_message_id: None,
default_permissions: None,
role_permissions: HashMap::new(),
nsfw: data.nsfw.unwrap_or(false),
voice: Some(data.voice.unwrap_or_default().into()),
},
};
@@ -418,28 +432,8 @@ impl Channel {
Channel::DirectMessage { id, .. }
| Channel::Group { id, .. }
| Channel::SavedMessages { id, .. }
| Channel::TextChannel { id, .. } => id,
}
}
/// Clone this channel's server id
pub fn server(&self) -> Option<&str> {
match self {
Channel::TextChannel { server, .. } => Some(server),
_ => None,
}
}
/// Gets this channel's voice information
pub fn voice(&self) -> Option<Cow<VoiceInformation>> {
match self {
Self::DirectMessage { .. } | Self::Group { .. } => {
Some(Cow::Owned(VoiceInformation::default()))
}
Self::TextChannel {
voice: Some(voice), ..
} => Some(Cow::Borrowed(voice)),
_ => None,
| Channel::TextChannel { id, .. }
| Channel::VoiceChannel { id, .. } => id,
}
}
@@ -456,6 +450,12 @@ impl Channel {
server,
role_permissions,
..
}
| Channel::VoiceChannel {
id,
server,
role_permissions,
..
} => {
db.set_channel_role_permission(id, role_id, permissions)
.await?;
@@ -502,7 +502,7 @@ impl Channel {
clear: remove.into_iter().map(|v| v.into()).collect(),
}
.p(match self {
Self::TextChannel { server, .. } => server.clone(),
Self::TextChannel { server, .. } | Self::VoiceChannel { server, .. } => server.clone(),
_ => id,
})
.await;
@@ -514,13 +514,17 @@ impl Channel {
pub fn remove_field(&mut self, field: &FieldsChannel) {
match field {
FieldsChannel::Description => match self {
Self::Group { description, .. } | Self::TextChannel { description, .. } => {
Self::Group { description, .. }
| Self::TextChannel { description, .. }
| Self::VoiceChannel { description, .. } => {
description.take();
}
_ => {}
},
FieldsChannel::Icon => match self {
Self::Group { icon, .. } | Self::TextChannel { icon, .. } => {
Self::Group { icon, .. }
| Self::TextChannel { icon, .. }
| Self::VoiceChannel { icon, .. } => {
icon.take();
}
_ => {}
@@ -529,17 +533,15 @@ impl Channel {
Self::TextChannel {
default_permissions,
..
}
| Self::VoiceChannel {
default_permissions,
..
} => {
default_permissions.take();
}
_ => {}
},
FieldsChannel::Voice => match self {
Self::TextChannel { voice, .. } => {
voice.take();
}
_ => {}
},
}
}
@@ -551,7 +553,6 @@ impl Channel {
}
/// Apply partial channel to channel
#[allow(deprecated)]
pub fn apply_options(&mut self, partial: PartialChannel) {
match self {
Self::SavedMessages { .. } => {}
@@ -600,7 +601,15 @@ impl Channel {
nsfw,
default_permissions,
role_permissions,
voice,
..
}
| Self::VoiceChannel {
name,
description,
icon,
nsfw,
default_permissions,
role_permissions,
..
} => {
if let Some(v) = partial.name {
@@ -626,10 +635,6 @@ impl Channel {
if let Some(v) = partial.default_permissions {
default_permissions.replace(v);
}
if let Some(v) = partial.voice {
voice.replace(v);
}
}
}
}
@@ -772,7 +777,6 @@ impl IntoDocumentPath for FieldsChannel {
FieldsChannel::Description => "description",
FieldsChannel::Icon => "icon",
FieldsChannel::DefaultPermissions => "default_permissions",
FieldsChannel::Voice => "voice",
})
}
}

View File

@@ -184,7 +184,7 @@ impl AbstractChannels for MongoDb {
async fn delete_channel(&self, channel: &Channel) -> Result<()> {
let id = channel.id().to_string();
let server_id = match channel {
Channel::TextChannel { server, .. } => {
Channel::TextChannel { server, .. } | Channel::VoiceChannel { server, .. } => {
Some(server)
}
_ => None,

View File

@@ -94,6 +94,9 @@ impl AbstractChannels for ReferenceDb {
match &mut channel {
Channel::TextChannel {
role_permissions, ..
}
| Channel::VoiceChannel {
role_permissions, ..
} => {
if role_permissions.get(role_id).is_some() {
role_permissions.remove(role_id);

View File

@@ -114,11 +114,6 @@ auto_derived!(
MessagePinned { id: String, by: String },
#[serde(rename = "message_unpinned")]
MessageUnpinned { id: String, by: String },
#[serde(rename = "call_started")]
CallStarted {
by: String,
finished_at: Option<Timestamp>,
},
}
/// Name and / or avatar override information
@@ -331,7 +326,9 @@ impl Message {
}
let server_id = match channel {
Channel::TextChannel { ref server, .. } => Some(server.clone()),
Channel::TextChannel { ref server, .. } | Channel::VoiceChannel { ref server, .. } => {
Some(server.clone())
}
_ => None,
};
@@ -443,7 +440,8 @@ impl Message {
}
// Verify replies are valid.
let mut replies = HashSet::new();
let mut replies = Vec::new();
if let Some(entries) = data.replies {
if entries.len() > config.features.limits.global.message_replies {
return Err(create_error!(TooManyReplies {
@@ -451,6 +449,8 @@ impl Message {
}));
}
replies.reserve(entries.len());
for ReplyIntent {
id,
mention,
@@ -464,7 +464,12 @@ impl Message {
user_mentions.insert(message.author.to_owned());
}
replies.insert(message.id);
// This is O(n^2), but this is faster than a HashSet
// when n < 20; as long as the message_replies limit
// is reasonable, this will be fast.
if !replies.contains(&message.id) {
replies.push(message.id);
}
}
// If the referenced message doesn't exist and fail_if_not_exists
// is set to false, send the message without the reply.
@@ -481,7 +486,6 @@ impl Message {
// Validate the mentions go to users in the channel/server
if !user_mentions.is_empty() {
#[allow(deprecated)]
match channel {
Channel::DirectMessage { ref recipients, .. }
| Channel::Group { ref recipients, .. } => {
@@ -489,7 +493,8 @@ impl Message {
user_mentions.retain(|m| recipients_hash.contains(m));
role_mentions.clear();
}
Channel::TextChannel { ref server, .. }=> {
Channel::TextChannel { ref server, .. }
| Channel::VoiceChannel { ref server, .. } => {
let mentions_vec = Vec::from_iter(user_mentions.iter().cloned());
let valid_members = db.fetch_members(server.as_str(), &mentions_vec[..]).await;
@@ -537,9 +542,7 @@ impl Message {
}
if !replies.is_empty() {
message
.replies
.replace(replies.into_iter().collect::<Vec<String>>());
message.replies.replace(replies);
}
// Calculate final message flags
@@ -681,6 +684,7 @@ impl Message {
)
.await?;
if !self.has_suppressed_notifications()
&& (self.mentions.is_some() || self.contains_mass_push_mention())
{
@@ -796,7 +800,7 @@ impl Message {
query: MessageQuery,
perspective: &User,
include_users: Option<bool>,
server_id: Option<&str>,
server_id: Option<String>,
) -> Result<BulkMessageResponse> {
let messages: Vec<v0::Message> = db
.fetch_messages(query)
@@ -839,7 +843,6 @@ impl Message {
v0::SystemMessage::MessageUnpinned { by, .. } => {
users.push(by.clone());
}
v0::SystemMessage::CallStarted { by, .. } => users.push(by.clone()),
}
}
users
@@ -854,7 +857,7 @@ impl Message {
users,
members: if let Some(server_id) = server_id {
Some(
db.fetch_members(server_id, &user_ids)
db.fetch_members(&server_id, &user_ids)
.await?
.into_iter()
.map(Into::into)

View File

@@ -1,4 +1,5 @@
mod admin_migrations;
mod authorized_bots;
mod bots;
mod channel_invites;
mod channel_unreads;
@@ -19,6 +20,7 @@ mod user_settings;
mod users;
pub use admin_migrations::*;
pub use authorized_bots::*;
pub use bots::*;
pub use channel_invites::*;
pub use channel_unreads::*;
@@ -46,6 +48,7 @@ use crate::MongoDb;
pub trait AbstractDatabase:
Sync
+ Send
+ authorized_bots::AbstractAuthorizedBots
+ admin_migrations::AbstractMigrations
+ bots::AbstractBots
+ channels::AbstractChannels

View File

@@ -1,21 +1,12 @@
use iso8601_timestamp::Timestamp;
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
use revolt_result::{create_error, Result};
use crate::voice::get_channel_voice_state;
use crate::{
events::client::EventV1, util::permissions::DatabasePermissionQuery, Channel,
Database, File, Server, SystemMessage, User,
events::client::EventV1, util::permissions::DatabasePermissionQuery, Channel, Database, File,
Server, SystemMessage, User,
};
fn default_true() -> bool {
true
}
fn is_true(x: &bool) -> bool {
*x
}
auto_derived_partial!(
/// Server Member
pub struct Member {
@@ -39,14 +30,6 @@ auto_derived_partial!(
/// Timestamp this member is timed out until
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout: Option<Timestamp>,
/// Whether the member is server-wide voice muted
#[serde(skip_serializing_if = "is_true", default = "default_true")]
pub can_publish: bool,
/// Whether the member is server-wide voice deafened
#[serde(skip_serializing_if = "is_true", default = "default_true")]
pub can_receive: bool,
// This value only exists in the database, not the models.
// If it is not-None, the database layer should return None to member fetching queries.
// pub pending_deletion_at: Option<Timestamp>
@@ -70,8 +53,6 @@ auto_derived!(
Avatar,
Roles,
Timeout,
CanReceive,
CanPublish,
JoinedAt,
}
@@ -92,8 +73,6 @@ impl Default for Member {
avatar: None,
roles: vec![],
timeout: None,
can_publish: true,
can_receive: true,
}
}
}
@@ -148,14 +127,6 @@ impl Member {
let emojis = db.fetch_emoji_by_parent_id(&server.id).await?;
let mut voice_states = Vec::new();
for channel in &channels {
if let Ok(Some(voice_state)) = get_channel_voice_state(channel).await {
voice_states.push(voice_state)
}
}
EventV1::ServerMemberJoin {
id: server.id.clone(),
user: user.id.clone(),
@@ -173,7 +144,6 @@ impl Member {
.map(|channel| channel.into())
.collect(),
emojis: emojis.into_iter().map(|emoji| emoji.into()).collect(),
voice_states
}
.private(user.id.clone())
.await;
@@ -228,8 +198,6 @@ impl Member {
FieldsMember::Nickname => self.nickname = None,
FieldsMember::Roles => self.roles.clear(),
FieldsMember::Timeout => self.timeout = None,
FieldsMember::CanReceive => self.can_receive = true,
FieldsMember::CanPublish => self.can_publish = true,
}
}

View File

@@ -336,8 +336,6 @@ impl IntoDocumentPath for FieldsMember {
FieldsMember::Nickname => "nickname",
FieldsMember::Roles => "roles",
FieldsMember::Timeout => "timeout",
FieldsMember::CanPublish => "is_publishing",
FieldsMember::CanReceive => "is_receiving",
})
}
}

View File

@@ -1,8 +1,10 @@
use axum::{extract::{FromRef, FromRequestParts}, http::request::Parts};
use revolt_config::config;
use revolt_models::v0;
use revolt_result::{create_error, Error, Result};
use crate::{Database, User};
use crate::{util::oauth2, Database, OAuth2Scope, User};
#[async_trait::async_trait]
impl<S> FromRequestParts<S> for User
@@ -23,6 +25,24 @@ where
{
let session = db.fetch_session_by_token(session_token).await?;
db.fetch_user(&session.user_id).await
} else if let Some(Ok(header_oauth_token)) = parts.headers.get("x-oauth2-token").map(|v| v.to_str()) {
let config = config().await;
let claims = oauth2::decode_token(
&config.api.security.token_secret,
header_oauth_token,
).map_err(|_| create_error!(NotAuthenticated))?;
let required_scope: v0::OAuth2Scope = parts.extensions.get::<OAuth2Scope>()
.copied()
.ok_or_else(|| create_error!(NotAuthenticated))?
.into();
if claims.scopes.contains(&v0::OAuth2Scope::Full) || claims.scopes.contains(&required_scope) {
db.fetch_user(&claims.sub).await
} else {
Err(create_error!(MissingScope { scope: required_scope.to_string() }))
}
} else {
Err(create_error!(NotAuthenticated))
}

View File

@@ -1,7 +1,10 @@
use authifier::models::Session;
use revolt_config::config;
use revolt_models::v0;
use rocket::http::Status;
use rocket::request::{self, FromRequest, Outcome, Request};
use crate::util::oauth2;
use crate::{Database, User};
#[rocket::async_trait]
@@ -19,12 +22,38 @@ impl<'r> FromRequest<'r> for User {
.next()
.map(|x| x.to_string());
let header_oauth_token = request
.headers()
.get("x-oauth2-token")
.next()
.map(|x| x.to_string());
if let Some(bot_token) = header_bot_token {
if let Ok(bot) = db.fetch_bot_by_token(&bot_token).await {
if let Ok(user) = db.fetch_user(&bot.id).await {
return Some(user);
}
}
} else if let Some(header_oauth_token) = header_oauth_token {
let config = config().await;
let claims = oauth2::decode_token(
&config.api.security.token_secret,
&header_oauth_token,
)
.ok()?;
// access the scope required for the route stored in the request local cache set via `OAuth2Scoped`
let required_scope: v0::OAuth2Scope = request.local_cache(|| None::<crate::OAuth2Scope>)
.as_ref()
.copied()?
.into();
if claims.scopes.contains(&v0::OAuth2Scope::Full) || claims.scopes.contains(&required_scope) {
if let Ok(user) = db.fetch_user(&claims.sub).await {
return Some(user);
}
}
} else if let Outcome::Success(session) = request.guard::<Session>().await {
if let Ok(user) = db.fetch_user(&session.user_id).await {
return Some(user);

View File

@@ -14,7 +14,7 @@ use validator::HasLen;
use revolt_result::Result;
use super::DelayedTask;
use crate::Channel::TextChannel;
use crate::Channel::{TextChannel, VoiceChannel};
/// Enumeration of possible events
#[derive(Debug, Eq, PartialEq)]
@@ -191,14 +191,17 @@ pub async fn handle_ack_event(
.await
.expect("Failed to fetch channel from db");
if let TextChannel { server, .. } = channel {
if let Err(err) =
amqp.mass_mention_message_sent(server, mass_mentions).await
{
revolt_config::capture_error(&err);
match channel {
TextChannel { server, .. } | VoiceChannel { server, .. } => {
if let Err(err) =
amqp.mass_mention_message_sent(server, mass_mentions).await
{
revolt_config::capture_error(&err);
}
}
_ => {
panic!("Unknown channel type when sending mass mention event");
}
} else {
panic!("Unknown channel type when sending mass mention event");
}
}
}

View File

@@ -33,6 +33,7 @@ impl From<crate::Bot> for Bot {
interactions_url: value.interactions_url,
terms_of_service_url: value.terms_of_service_url,
privacy_policy_url: value.privacy_policy_url,
oauth2: value.oauth2.map(|oauth2| oauth2.into()),
flags: value.flags.unwrap_or_default() as u32,
}
}
@@ -43,6 +44,8 @@ impl From<FieldsBot> for crate::FieldsBot {
match value {
FieldsBot::InteractionsURL => crate::FieldsBot::InteractionsURL,
FieldsBot::Token => crate::FieldsBot::Token,
FieldsBot::Oauth2 => crate::FieldsBot::Oauth2,
FieldsBot::Oauth2Secret => crate::FieldsBot::Oauth2Secret,
}
}
}
@@ -52,6 +55,78 @@ impl From<crate::FieldsBot> for FieldsBot {
match value {
crate::FieldsBot::InteractionsURL => FieldsBot::InteractionsURL,
crate::FieldsBot::Token => FieldsBot::Token,
crate::FieldsBot::Oauth2 => FieldsBot::Oauth2,
crate::FieldsBot::Oauth2Secret => FieldsBot::Oauth2Secret,
}
}
}
impl From<BotOauth2> for crate::BotOauth2 {
fn from(value: BotOauth2) -> Self {
crate::BotOauth2 {
public: value.public,
secret: value.secret,
redirects: value.redirects,
allowed_scopes: value.allowed_scopes
.into_iter()
.map(|(scope, value)| (scope.into(), value.into()))
.collect(),
}
}
}
impl From<crate::BotOauth2> for BotOauth2 {
fn from(value: crate::BotOauth2) -> Self {
BotOauth2 {
public: value.public,
secret: value.secret,
redirects: value.redirects,
allowed_scopes: value.allowed_scopes
.into_iter()
.map(|(scope, value)| (scope.into(), value.into()))
.collect(),
}
}
}
impl From<crate::OAuth2Scope> for OAuth2Scope {
fn from(value: crate::OAuth2Scope) -> Self {
match value {
crate::OAuth2Scope::ReadIdentify => OAuth2Scope::ReadIdentify,
crate::OAuth2Scope::ReadServers => OAuth2Scope::ReadServers,
crate::OAuth2Scope::WriteFiles => OAuth2Scope::WriteFiles,
crate::OAuth2Scope::Events => OAuth2Scope::Events,
crate::OAuth2Scope::Full => OAuth2Scope::Full,
}
}
}
impl From<OAuth2Scope> for crate::OAuth2Scope {
fn from(value: OAuth2Scope) -> Self {
match value {
OAuth2Scope::ReadIdentify => crate::OAuth2Scope::ReadIdentify,
OAuth2Scope::ReadServers => crate::OAuth2Scope::ReadServers,
OAuth2Scope::WriteFiles => crate::OAuth2Scope::WriteFiles,
OAuth2Scope::Events => crate::OAuth2Scope::Events,
OAuth2Scope::Full => crate::OAuth2Scope::Full,
}
}
}
impl From<crate::OAuth2ScopeReasoning> for OAuth2ScopeReasoning {
fn from(value: crate::OAuth2ScopeReasoning) -> Self {
OAuth2ScopeReasoning {
allow: value.allow,
deny: value.deny,
}
}
}
impl From<OAuth2ScopeReasoning> for crate::OAuth2ScopeReasoning {
fn from(value: OAuth2ScopeReasoning) -> Self {
crate::OAuth2ScopeReasoning {
allow: value.allow,
deny: value.deny,
}
}
}
@@ -143,7 +218,6 @@ impl From<crate::FieldsWebhook> for FieldsWebhook {
}
impl From<crate::Channel> for Channel {
#[allow(deprecated)]
fn from(value: crate::Channel) -> Self {
match value {
crate::Channel::SavedMessages { id, user } => Channel::SavedMessages { id, user },
@@ -189,7 +263,6 @@ impl From<crate::Channel> for Channel {
default_permissions,
role_permissions,
nsfw,
voice,
} => Channel::TextChannel {
id,
server,
@@ -200,14 +273,31 @@ impl From<crate::Channel> for Channel {
default_permissions,
role_permissions,
nsfw,
voice: voice.map(|voice| voice.into()),
},
crate::Channel::VoiceChannel {
id,
server,
name,
description,
icon,
default_permissions,
role_permissions,
nsfw,
} => Channel::VoiceChannel {
id,
server,
name,
description,
icon: icon.map(|file| file.into()),
default_permissions,
role_permissions,
nsfw,
},
}
}
}
impl From<Channel> for crate::Channel {
#[allow(deprecated)]
fn from(value: Channel) -> crate::Channel {
match value {
Channel::SavedMessages { id, user } => crate::Channel::SavedMessages { id, user },
@@ -253,7 +343,6 @@ impl From<Channel> for crate::Channel {
default_permissions,
role_permissions,
nsfw,
voice,
} => crate::Channel::TextChannel {
id,
server,
@@ -264,7 +353,25 @@ impl From<Channel> for crate::Channel {
default_permissions,
role_permissions,
nsfw,
voice: voice.map(|voice| voice.into()),
},
Channel::VoiceChannel {
id,
server,
name,
description,
icon,
default_permissions,
role_permissions,
nsfw,
} => crate::Channel::VoiceChannel {
id,
server,
name,
description,
icon: icon.map(|file| file.into()),
default_permissions,
role_permissions,
nsfw,
},
}
}
@@ -283,7 +390,6 @@ impl From<crate::PartialChannel> for PartialChannel {
role_permissions: value.role_permissions,
default_permissions: value.default_permissions,
last_message_id: value.last_message_id,
voice: value.voice.map(|voice| voice.into())
}
}
}
@@ -301,7 +407,6 @@ impl From<PartialChannel> for crate::PartialChannel {
role_permissions: value.role_permissions,
default_permissions: value.default_permissions,
last_message_id: value.last_message_id,
voice: value.voice.map(|voice| voice.into())
}
}
}
@@ -312,7 +417,6 @@ impl From<FieldsChannel> for crate::FieldsChannel {
FieldsChannel::Description => crate::FieldsChannel::Description,
FieldsChannel::Icon => crate::FieldsChannel::Icon,
FieldsChannel::DefaultPermissions => crate::FieldsChannel::DefaultPermissions,
FieldsChannel::Voice => crate::FieldsChannel::Voice,
}
}
}
@@ -323,7 +427,6 @@ impl From<crate::FieldsChannel> for FieldsChannel {
crate::FieldsChannel::Description => FieldsChannel::Description,
crate::FieldsChannel::Icon => FieldsChannel::Icon,
crate::FieldsChannel::DefaultPermissions => FieldsChannel::DefaultPermissions,
crate::FieldsChannel::Voice => FieldsChannel::Voice,
}
}
}
@@ -515,7 +618,6 @@ impl From<crate::SystemMessage> for SystemMessage {
crate::SystemMessage::UserRemove { id, by } => Self::UserRemove { id, by },
crate::SystemMessage::MessagePinned { id, by } => Self::MessagePinned { id, by },
crate::SystemMessage::MessageUnpinned { id, by } => Self::MessageUnpinned { id, by },
crate::SystemMessage::CallStarted { by, finished_at } => Self::CallStarted { by, finished_at }
}
}
}
@@ -612,8 +714,6 @@ impl From<crate::Member> for Member {
avatar: value.avatar.map(|f| f.into()),
roles: value.roles,
timeout: value.timeout,
can_publish: value.can_publish,
can_receive: value.can_receive,
}
}
}
@@ -627,8 +727,6 @@ impl From<Member> for crate::Member {
avatar: value.avatar.map(|f| f.into()),
roles: value.roles,
timeout: value.timeout,
can_publish: value.can_publish,
can_receive: value.can_receive,
}
}
}
@@ -642,8 +740,6 @@ impl From<crate::PartialMember> for PartialMember {
avatar: value.avatar.map(|f| f.into()),
roles: value.roles,
timeout: value.timeout,
can_publish: value.can_publish,
can_receive: value.can_receive,
}
}
}
@@ -657,8 +753,6 @@ impl From<PartialMember> for crate::PartialMember {
avatar: value.avatar.map(|f| f.into()),
roles: value.roles,
timeout: value.timeout,
can_publish: value.can_publish,
can_receive: value.can_receive,
}
}
}
@@ -688,8 +782,6 @@ impl From<crate::FieldsMember> for FieldsMember {
crate::FieldsMember::Nickname => FieldsMember::Nickname,
crate::FieldsMember::Roles => FieldsMember::Roles,
crate::FieldsMember::Timeout => FieldsMember::Timeout,
crate::FieldsMember::CanReceive => FieldsMember::CanReceive,
crate::FieldsMember::CanPublish => FieldsMember::CanPublish,
crate::FieldsMember::JoinedAt => FieldsMember::JoinedAt,
}
}
@@ -702,8 +794,6 @@ impl From<FieldsMember> for crate::FieldsMember {
FieldsMember::Nickname => crate::FieldsMember::Nickname,
FieldsMember::Roles => crate::FieldsMember::Roles,
FieldsMember::Timeout => crate::FieldsMember::Timeout,
FieldsMember::CanReceive => crate::FieldsMember::CanReceive,
FieldsMember::CanPublish => crate::FieldsMember::CanPublish,
FieldsMember::JoinedAt => crate::FieldsMember::JoinedAt,
}
}
@@ -1373,18 +1463,42 @@ impl From<FieldsMessage> for crate::FieldsMessage {
}
}
impl From<VoiceInformation> for crate::VoiceInformation {
fn from(value: VoiceInformation) -> Self {
crate::VoiceInformation {
max_users: value.max_users
impl From<AuthorizedBotId> for crate::AuthorizedBotId {
fn from(value: AuthorizedBotId) -> Self {
crate::AuthorizedBotId {
user: value.user,
bot: value.bot
}
}
}
impl From<crate::VoiceInformation> for VoiceInformation {
fn from(value: crate::VoiceInformation) -> Self {
VoiceInformation {
max_users: value.max_users
impl From<crate::AuthorizedBotId> for AuthorizedBotId {
fn from(value: crate::AuthorizedBotId) -> Self {
AuthorizedBotId {
user: value.user,
bot: value.bot
}
}
}
impl From<AuthorizedBot> for crate::AuthorizedBot {
fn from(value: AuthorizedBot) -> Self {
crate::AuthorizedBot {
id: value.id.into(),
created_at: value.created_at,
deauthorized_at: value.deauthorized_at,
scope: value.scope.into_iter().map(|scope| scope.into()).collect(),
}
}
}
impl From<crate::AuthorizedBot> for AuthorizedBot {
fn from(value: crate::AuthorizedBot) -> Self {
AuthorizedBot {
id: value.id.into(),
created_at: value.created_at,
deauthorized_at: value.deauthorized_at,
scope: value.scope.into_iter().map(|scope| scope.into()).collect(),
}
}
}

View File

@@ -144,6 +144,10 @@ impl<'z> BulkDatabasePermissionQuery<'z> {
Channel::TextChannel {
default_permissions,
..
}
| Channel::VoiceChannel {
default_permissions,
..
} => default_permissions.unwrap_or_default().into(),
_ => Default::default(),
}
@@ -152,14 +156,16 @@ impl<'z> BulkDatabasePermissionQuery<'z> {
}
}
#[allow(dead_code, deprecated)]
#[allow(dead_code)]
fn get_channel_type(&mut self) -> ChannelType {
if let Some(channel) = &self.channel {
match channel {
Channel::DirectMessage { .. } => ChannelType::DirectMessage,
Channel::Group { .. } => ChannelType::Group,
Channel::SavedMessages { .. } => ChannelType::SavedMessages,
Channel::TextChannel { .. } => ChannelType::ServerChannel,
Channel::TextChannel { .. } | Channel::VoiceChannel { .. } => {
ChannelType::ServerChannel
}
}
} else {
ChannelType::Unknown
@@ -173,6 +179,9 @@ impl<'z> BulkDatabasePermissionQuery<'z> {
match channel {
Channel::TextChannel {
role_permissions, ..
}
| Channel::VoiceChannel {
role_permissions, ..
} => role_permissions,
_ => panic!("Not supported for non-server channels"),
}
@@ -199,6 +208,12 @@ async fn calculate_members_permissions<'a>(
role_permissions,
default_permissions,
..
}
| Channel::VoiceChannel {
id,
role_permissions,
default_permissions,
..
} => (id, role_permissions, default_permissions),
_ => panic!("Calculation of member permissions must be done on a server channel"),
};

View File

@@ -1,24 +0,0 @@
use crate::Database;
use revolt_result::Result;
/// Formats a user's name depending on their optional features and location.
/// Factors in server display names and user display names before falling back to username#discriminator.
/// Passing a server in which the user is not a member will result in an Err.
pub async fn format_display_name(
db: &Database,
user_id: &str,
server_id: Option<&str>,
) -> Result<String> {
if let Some(server_id) = server_id {
let member = db.fetch_member(server_id, user_id).await?;
if let Some(nick) = member.nickname {
return Ok(nick);
}
}
let user = db.fetch_user(user_id).await?;
if let Some(display) = user.display_name {
return Ok(display);
}
Ok(format!("{}#{}", user.username, user.discriminator))
}

View File

@@ -1,9 +1,7 @@
pub mod bridge;
pub mod bulk_permissions;
mod funcs;
pub mod idempotency;
pub mod permissions;
pub mod reference;
pub mod test_fixtures;
pub use funcs::*;
pub mod oauth2;

View File

@@ -0,0 +1,17 @@
use std::marker::PhantomData;
use axum::{extract::FromRequestParts, http::request::Parts};
use revolt_result::{Error, Result};
use super::{OAuth2Scoped, scopes::OAuth2Scope};
#[rocket::async_trait]
impl<S: Send + Sync, Scope: OAuth2Scope> FromRequestParts<S> for OAuth2Scoped<Scope> {
type Rejection = Error;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self> {
parts.extensions.insert(Scope::SCOPE);
Ok(OAuth2Scoped { _scope: PhantomData })
}
}

View File

@@ -0,0 +1,120 @@
use chrono::{TimeDelta, Utc};
use jsonwebtoken::{decode, encode, errors::Error, DecodingKey, EncodingKey, Header, Validation};
use redis_kiss::AsyncCommands;
use revolt_models::v0;
use revolt_result::Result;
use serde::{Deserialize, Serialize};
pub mod scopes;
pub use scopes::OAuth2Scoped;
#[cfg(feature = "rocket")]
pub mod rocket;
#[cfg(feature = "axum")]
pub mod axum;
pub use jsonwebtoken::errors::{Error as JWTError, ErrorKind as JWTErrorKind};
use ulid::Ulid;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum TokenType {
Auth,
Access,
Refresh,
}
impl TokenType {
pub fn lifetime(self) -> TimeDelta {
match self {
TokenType::Access => TimeDelta::weeks(1),
TokenType::Auth => TimeDelta::minutes(5),
TokenType::Refresh => TimeDelta::weeks(4),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub jti: String,
pub sub: String,
pub exp: i64,
pub r#type: TokenType,
pub client_id: String,
pub scopes: Vec<v0::OAuth2Scope>,
pub redirect_uri: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub code_challange_method: Option<v0::OAuth2CodeChallangeMethod>,
}
#[allow(clippy::too_many_arguments)]
pub fn encode_token(
token_secret: &str,
token_type: TokenType,
user_id: String,
client_id: String,
redirect_uri: String,
scopes: Vec<v0::OAuth2Scope>,
code_challange_method: Option<v0::OAuth2CodeChallangeMethod>,
) -> Result<String, Error> {
let now = Utc::now();
let exp = now.checked_add_signed(token_type.lifetime()).unwrap();
println!("{now:?} {exp:}");
let claims = Claims {
jti: Ulid::new().to_string(),
sub: user_id,
exp: exp.timestamp(),
r#type: token_type,
client_id,
scopes,
redirect_uri,
code_challange_method,
};
let encoding_key = EncodingKey::from_secret(token_secret.as_bytes());
encode(&Header::default(), &claims, &encoding_key)
}
pub fn decode_token(token_secret: &str, code: &str) -> Result<Claims, Error> {
let decoding_key = DecodingKey::from_secret(token_secret.as_bytes());
let data = decode(
code,
&decoding_key,
&Validation::new(jsonwebtoken::Algorithm::HS256),
)?;
Ok(data.claims)
}
pub async fn add_code_challange(token: &str, code_challenge: &str) -> Result<()> {
let mut conn = redis_kiss::get_connection()
.await
.map_err(|_| create_error!(InternalError))?;
conn.pset_ex::<_, _, ()>(
format!("oauth2:{token}:code_challenge"),
code_challenge,
TokenType::Access.lifetime().num_milliseconds() as usize,
)
.await
.map_err(|_| create_error!(InternalError))?;
Ok(())
}
pub async fn get_code_challange(token: &str) -> Result<Option<String>> {
let mut conn = redis_kiss::get_connection()
.await
.map_err(|_| create_error!(InternalError))?;
conn.get(format!("oauth2:{token}:code_challenge"))
.await
.map_err(|_| create_error!(InternalError))
}

View File

@@ -0,0 +1,53 @@
use std::{convert::Infallible, marker::PhantomData};
use revolt_okapi::openapi3::{OAuthFlows, SecurityScheme, SecuritySchemeData};
use revolt_rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
use rocket::{request::{self, FromRequest}, Request};
use super::{OAuth2Scoped, scopes::OAuth2Scope};
#[rocket::async_trait]
impl<'r, Scope: OAuth2Scope> FromRequest<'r> for OAuth2Scoped<Scope> {
type Error = Infallible;
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
request.local_cache(|| Some(Scope::SCOPE));
request::Outcome::Success(OAuth2Scoped { _scope: PhantomData })
}
}
impl<'r, Scope: OAuth2Scope> OpenApiFromRequest<'r> for OAuth2Scoped<Scope> {
fn from_request_input(
_gen: &mut revolt_rocket_okapi::r#gen::OpenApiGenerator,
_name: String,
_required: bool,
) -> revolt_rocket_okapi::Result<revolt_rocket_okapi::request::RequestHeaderInput> {
Ok(RequestHeaderInput::Security(
"OAuth2".to_owned(),
SecurityScheme {
description: None,
extensions: Default::default(),
data: SecuritySchemeData::OAuth2 {
flows: OAuthFlows::AuthorizationCode {
authorization_url: "todo".to_string(),
token_url: "todo".to_string(),
refresh_url: Some("todo".to_string()),
scopes: revolt_okapi::map! {
"read:identify".to_string() => "".to_string(),
"read:servers".to_string() => "".to_string(),
"write:files".to_string() => "".to_string(),
"events".to_string() => "".to_string(),
"full".to_string() => "".to_string(),
},
extensions: Default::default()
}
}
},
revolt_okapi::map! {
"OAuth2".to_owned() => vec![Scope::MODEL.to_string()]
},
))
}
}

View File

@@ -0,0 +1,29 @@
use std::marker::PhantomData;
pub struct OAuth2Scoped<Scope> {
pub(crate) _scope: PhantomData<Scope>
}
pub trait OAuth2Scope {
const SCOPE: crate::OAuth2Scope;
const MODEL: revolt_models::v0::OAuth2Scope;
}
macro_rules! define_oauth2_scope {
($struct_name:ident) => {
pub struct $struct_name;
impl OAuth2Scope for $struct_name {
const SCOPE: crate::OAuth2Scope = crate::OAuth2Scope::$struct_name;
const MODEL: revolt_models::v0::OAuth2Scope = revolt_models::v0::OAuth2Scope::$struct_name;
}
};
}
// This must match the OAuth2Scope enum
// TODO: automatically sync this
define_oauth2_scope!(ReadIdentify);
define_oauth2_scope!(ReadServers);
define_oauth2_scope!(WriteFiles);
define_oauth2_scope!(Events);
define_oauth2_scope!(Full);

View File

@@ -185,26 +185,9 @@ impl PermissionQuery for DatabasePermissionQuery<'_> {
}
}
async fn do_we_have_publish_overwrites(&mut self) -> bool {
if let Some(member) = &self.member {
member.can_publish
} else {
true
}
}
async fn do_we_have_receive_overwrites(&mut self) -> bool {
if let Some(member) = &self.member {
member.can_receive
} else {
true
}
}
// * For calculating channel permission
/// Get the type of the channel
#[allow(deprecated)]
async fn get_channel_type(&mut self) -> ChannelType {
if let Some(channel) = &self.channel {
match channel {
@@ -216,7 +199,9 @@ impl PermissionQuery for DatabasePermissionQuery<'_> {
Cow::Borrowed(Channel::SavedMessages { .. })
| Cow::Owned(Channel::SavedMessages { .. }) => ChannelType::SavedMessages,
Cow::Borrowed(Channel::TextChannel { .. })
| Cow::Owned(Channel::TextChannel { .. }) => ChannelType::ServerChannel,
| Cow::Owned(Channel::TextChannel { .. })
| Cow::Borrowed(Channel::VoiceChannel { .. })
| Cow::Owned(Channel::VoiceChannel { .. }) => ChannelType::ServerChannel,
}
} else {
ChannelType::Unknown
@@ -240,6 +225,14 @@ impl PermissionQuery for DatabasePermissionQuery<'_> {
| Cow::Owned(Channel::TextChannel {
default_permissions,
..
})
| Cow::Borrowed(Channel::VoiceChannel {
default_permissions,
..
})
| Cow::Owned(Channel::VoiceChannel {
default_permissions,
..
}) => default_permissions.unwrap_or_default().into(),
_ => Default::default(),
}
@@ -257,6 +250,12 @@ impl PermissionQuery for DatabasePermissionQuery<'_> {
})
| Cow::Owned(Channel::TextChannel {
role_permissions, ..
})
| Cow::Borrowed(Channel::VoiceChannel {
role_permissions, ..
})
| Cow::Owned(Channel::VoiceChannel {
role_permissions, ..
}) => {
if let Some(server) = &self.server {
let member_roles = self
@@ -344,10 +343,11 @@ impl PermissionQuery for DatabasePermissionQuery<'_> {
/// (this will only ever be called for server channels, use unimplemented!() for other code paths)
async fn set_server_from_channel(&mut self) {
if let Some(channel) = &self.channel {
#[allow(deprecated)]
match channel {
Cow::Borrowed(Channel::TextChannel { server, .. })
| Cow::Owned(Channel::TextChannel { server, .. }) => {
| Cow::Owned(Channel::TextChannel { server, .. })
| Cow::Borrowed(Channel::VoiceChannel { server, .. })
| Cow::Owned(Channel::VoiceChannel { server, .. }) => {
if let Some(known_server) =
// I'm not sure why I can't just pattern match both at once here?
// It throws some weird error and the provided fix doesn't work :/

View File

@@ -1,564 +0,0 @@
use crate::{
events::client::EventV1,
models::{Channel, User},
util::{permissions::DatabasePermissionQuery, reference::Reference},
Database, Server,
};
use iso8601_timestamp::{Duration, Timestamp};
use livekit_protocol::ParticipantPermission;
use redis_kiss::{get_connection as _get_connection, redis::Pipeline, AsyncCommands, Conn};
use revolt_config::FeaturesLimits;
use revolt_models::v0::{self, PartialUserVoiceState, UserVoiceState};
use revolt_permissions::{calculate_channel_permissions, ChannelPermission, PermissionValue};
use revolt_result::{create_error, Result, ToRevoltError};
mod voice_client;
pub use voice_client::VoiceClient;
async fn get_connection() -> Result<Conn> {
_get_connection().await.to_internal_error()
}
pub async fn raise_if_in_voice(user: &User, channel_id: &str) -> Result<()> {
let mut conn = get_connection().await?;
if user.bot.is_some()
// bots can be in as many voice channels as it wants so we just check if its already connected to the one its trying to connect to
&& conn.sismember(format!("vc:{}", &user.id), channel_id)
.await
.to_internal_error()?
{
Err(create_error!(AlreadyConnected))
} else if conn
.scard::<_, u32>(format!("vc:{}", &user.id)) // check if the current vc set is empty
.await
.to_internal_error()?
> 0
{
Err(create_error!(NotConnected))
} else {
Ok(())
}
}
pub async fn set_channel_node(channel: &str, node: &str) -> Result<()> {
get_connection()
.await?
.set(format!("node:{channel}"), node)
.await
.to_internal_error()
}
pub async fn get_channel_node(channel: &str) -> Result<Option<String>> {
get_connection()
.await?
.get(format!("node:{channel}"))
.await
.to_internal_error()
}
pub async fn get_user_voice_channels(user_id: &str) -> Result<Vec<String>> {
get_connection()
.await?
.smembers(format!("vc:{user_id}"))
.await
.to_internal_error()
}
pub async fn set_user_moved_from_voice(
old_channel: &str,
new_channel: &str,
user_id: &str,
) -> Result<()> {
get_connection()
.await?
.set_ex(
format!("moved_from:{user_id}:{old_channel}"),
new_channel,
10,
)
.await
.to_internal_error()
}
pub async fn get_user_moved_from_voice(channel_id: &str, user_id: &str) -> Result<Option<String>> {
get_connection()
.await?
.get_del(format!("moved_from:{user_id}:{channel_id}"))
.await
.to_internal_error()
}
pub async fn set_user_moved_to_voice(
new_channel: &str,
old_channel: &str,
user_id: &str,
) -> Result<()> {
get_connection()
.await?
.set_ex(format!("moved_to:{user_id}:{new_channel}"), old_channel, 10)
.await
.to_internal_error()
}
pub async fn get_user_moved_to_voice(channel_id: &str, user_id: &str) -> Result<Option<String>> {
get_connection()
.await?
.get_del(format!("moved_to:{user_id}:{channel_id}"))
.await
.to_internal_error()
}
pub async fn is_in_voice_channel(user_id: &str, channel_id: &str) -> Result<bool> {
get_connection()
.await?
.sismember(format!("vc:{user_id}"), channel_id)
.await
.to_internal_error()
}
pub async fn get_user_voice_channel_in_server(
user_id: &str,
server_id: &str,
) -> Result<Option<String>> {
let mut conn = get_connection().await?;
let unique_key = format!("{user_id}:{server_id}");
conn.get(&unique_key).await.to_internal_error()
}
pub fn get_allowed_sources(
limits: &FeaturesLimits,
permissions: PermissionValue,
) -> Vec<&'static str> {
let mut allowed_sources = Vec::new();
if permissions.has(ChannelPermission::Speak as u64) {
allowed_sources.push("microphone")
};
if permissions.has(ChannelPermission::Video as u64) && limits.video {
allowed_sources.extend(["camera", "screen_share", "screen_share_audio"]);
};
allowed_sources
}
pub async fn create_voice_state(
channel_id: &str,
server_id: Option<&str>,
user_id: &str,
joined_at: Timestamp,
) -> Result<UserVoiceState> {
let unique_key = format!("{}:{}", &user_id, server_id.unwrap_or(channel_id));
let voice_state = UserVoiceState {
joined_at,
id: user_id.to_string(),
is_receiving: true,
is_publishing: false,
screensharing: false,
camera: false,
};
Pipeline::new()
.sadd(format!("vc_members:{channel_id}"), user_id)
.sadd(format!("vc:{user_id}"), channel_id)
.set(&unique_key, channel_id)
.set(
format!("joined_at:{unique_key}"),
joined_at
.duration_since(Timestamp::UNIX_EPOCH)
.whole_milliseconds() as i64,
)
.set(
format!("is_publishing:{unique_key}"),
voice_state.is_publishing,
)
.set(
format!("is_receiving:{unique_key}"),
voice_state.is_receiving,
)
.set(
format!("screensharing:{unique_key}"),
voice_state.screensharing,
)
.set(format!("camera:{unique_key}"), voice_state.camera)
.query_async::<_, ()>(&mut get_connection().await?.into_inner())
.await
.to_internal_error()?;
Ok(voice_state)
}
pub async fn delete_voice_state(
channel_id: &str,
server_id: Option<&str>,
user_id: &str,
) -> Result<()> {
let unique_key = format!("{}:{}", &user_id, server_id.unwrap_or(channel_id));
Pipeline::new()
.srem(format!("vc_members:{channel_id}"), user_id)
.srem(format!("vc:{user_id}"), channel_id)
.del(&[
format!("joined_at:{unique_key}"),
format!("is_publishing:{unique_key}"),
format!("is_receiving:{unique_key}"),
format!("screensharing:{unique_key}"),
format!("camera:{unique_key}"),
unique_key.clone(),
])
.query_async(&mut get_connection().await?.into_inner())
.await
.to_internal_error()
}
pub async fn delete_channel_voice_state(
channel_id: &str,
server_id: Option<&str>,
user_ids: &[String],
) -> Result<()> {
let parent_id = server_id.unwrap_or(channel_id);
let mut pipeline = Pipeline::new();
pipeline.del(format!("vc_members:{channel_id}"));
for user_id in user_ids {
let unique_key = format!("{user_id}:{parent_id}");
pipeline.srem(format!("vc:{user_id}"), channel_id).del(&[
format!("joined_at:{unique_key}"),
format!("is_publishing:{unique_key}"),
format!("is_receiving:{unique_key}"),
format!("screensharing:{unique_key}"),
format!("camera:{unique_key}"),
unique_key.clone(),
]);
}
pipeline
.query_async(&mut get_connection().await?.into_inner())
.await
.to_internal_error()
}
pub async fn update_voice_state_tracks(
channel_id: &str,
server_id: Option<&str>,
user_id: &str,
added: bool,
track: i32,
) -> Result<PartialUserVoiceState> {
let partial = match track {
/* TrackSource::Unknown */ 0 => PartialUserVoiceState::default(),
/* TrackSource::Camera */
1 => PartialUserVoiceState {
camera: Some(added),
..Default::default()
},
/* TrackSource::Microphone */
2 => PartialUserVoiceState {
is_publishing: Some(added),
..Default::default()
},
/* TrackSource::ScreenShare | TrackSource::ScreenShareAudio */
3 | 4 => PartialUserVoiceState {
screensharing: Some(added),
..Default::default()
},
_ => unreachable!(),
};
update_voice_state(channel_id, server_id, user_id, &partial).await?;
Ok(partial)
}
pub async fn update_voice_state(
channel_id: &str,
server_id: Option<&str>,
user_id: &str,
partial: &PartialUserVoiceState,
) -> Result<()> {
let unique_key = format!("{}:{}", &user_id, server_id.unwrap_or(channel_id));
let mut pipeline = Pipeline::new();
if let Some(camera) = &partial.camera {
pipeline.set(format!("camera:{unique_key}"), camera);
};
if let Some(is_publishing) = &partial.is_publishing {
pipeline.set(format!("is_publishing:{unique_key}"), is_publishing);
}
if let Some(is_receiving) = &partial.is_receiving {
pipeline.set(format!("is_receiving:{unique_key}"), is_receiving);
}
if let Some(screensharing) = &partial.screensharing {
pipeline.set(format!("screensharing:{unique_key}"), screensharing);
}
pipeline
.query_async(&mut get_connection().await?.into_inner())
.await
.to_internal_error()
}
pub async fn get_voice_channel_members(channel_id: &str) -> Result<Option<Vec<String>>> {
get_connection()
.await?
.smembers::<_, Option<Vec<String>>>(format!("vc_members:{channel_id}"))
.await
.to_internal_error()
.map(|opt| opt.and_then(|v| if v.is_empty() { None } else { Some(v) }))
}
pub async fn get_voice_state(
channel_id: &str,
server_id: Option<&str>,
user_id: &str,
) -> Result<Option<UserVoiceState>> {
let unique_key = format!("{}:{}", user_id, server_id.unwrap_or(channel_id));
let (joined_at, is_publishing, is_receiving, screensharing, camera) = get_connection()
.await?
.mget(&[
format!("joined_at:{unique_key}"),
format!("is_publishing:{unique_key}"),
format!("is_receiving:{unique_key}"),
format!("screensharing:{unique_key}"),
format!("camera:{unique_key}"),
])
.await
.to_internal_error()?;
match (
joined_at,
is_publishing,
is_receiving,
screensharing,
camera,
) {
(
Some(joined_at),
Some(is_publishing),
Some(is_receiving),
Some(screensharing),
Some(camera),
) => Ok(Some(v0::UserVoiceState {
joined_at: Timestamp::UNIX_EPOCH
.checked_add(Duration::milliseconds(joined_at))
.unwrap(),
id: user_id.to_string(),
is_receiving,
is_publishing,
screensharing,
camera,
})),
_ => Ok(None),
}
}
pub async fn get_channel_voice_state(channel: &Channel) -> Result<Option<v0::ChannelVoiceState>> {
let members = get_voice_channel_members(channel.id()).await?;
let server = channel.server();
if let Some(members) = members {
let mut participants = Vec::with_capacity(members.len());
for user_id in members {
if let Some(voice_state) = get_voice_state(channel.id(), server, &user_id).await? {
participants.push(voice_state);
} else {
log::info!("Voice state not found but member in voice channel members, removing.");
delete_voice_state(channel.id(), server, &user_id).await?;
}
}
// In case a user voice state failed to be fetched, the vec's capacity will be larger than the length, shrink it
participants.shrink_to_fit();
Ok(Some(v0::ChannelVoiceState {
id: channel.id().to_string(),
participants,
}))
} else {
Ok(None)
}
}
pub async fn move_user(user: &str, from: &str, to: &str) -> Result<()> {
get_connection()
.await?
.smove(
format!("vc-members-{from}"),
format!("vc-members-{to}"),
user,
)
.await
.to_internal_error()
}
pub async fn sync_voice_permissions(
db: &Database,
voice_client: &VoiceClient,
channel: &Channel,
server: Option<&Server>,
role_id: Option<&str>,
) -> Result<()> {
let node = get_channel_node(channel.id()).await?.unwrap();
for user_id in get_voice_channel_members(channel.id())
.await?
.iter()
.flatten()
{
let user = Reference::from_unchecked(user_id).as_user(db).await?;
sync_user_voice_permissions(db, voice_client, &node, &user, channel, server, role_id)
.await?;
}
Ok(())
}
pub async fn sync_user_voice_permissions(
db: &Database,
voice_client: &VoiceClient,
node: &str,
user: &User,
channel: &Channel,
server: Option<&Server>,
role_id: Option<&str>,
) -> Result<()> {
let channel_id = channel.id();
let server_id = server.as_ref().map(|s| s.id.as_str());
let member = match server_id {
Some(server_id) => Some(
Reference::from_unchecked(&user.id)
.as_member(db, server_id)
.await?,
),
None => None,
};
if role_id.is_none_or(|role_id| {
member
.as_ref()
.is_none_or(|member| member.roles.iter().any(|r| r == role_id))
}) {
let voice_state = get_voice_state(channel_id, server_id, &user.id)
.await?
.unwrap();
let mut query = DatabasePermissionQuery::new(db, user)
.channel(channel)
.user(user);
if let (Some(server), Some(member)) = (server, member.as_ref()) {
query = query.member(member).server(server)
}
let permissions = calculate_channel_permissions(&mut query).await;
let limits = user.limits().await;
let mut update_event = PartialUserVoiceState {
id: Some(user.id.clone()),
..Default::default()
};
let before = update_event.clone();
let can_video =
limits.video && permissions.has_channel_permission(ChannelPermission::Video);
let can_speak = permissions.has_channel_permission(ChannelPermission::Speak);
let can_listen = permissions.has_channel_permission(ChannelPermission::Listen);
update_event.camera = voice_state.camera.then_some(can_video);
update_event.screensharing = voice_state.screensharing.then_some(can_video);
update_event.is_publishing = voice_state.is_publishing.then_some(can_speak);
update_voice_state(channel_id, server_id, &user.id, &update_event).await?;
voice_client
.update_permissions(
node,
user,
channel_id,
ParticipantPermission {
can_subscribe: can_listen,
can_publish: can_speak,
can_publish_data: can_speak,
..Default::default()
},
)
.await?;
if update_event != before {
EventV1::UserVoiceStateUpdate {
id: user.id.clone(),
channel_id: channel_id.to_string(),
data: update_event,
}
.p(channel_id.to_string())
.await;
};
};
Ok(())
}
pub async fn set_channel_call_started_system_message(
channel_id: &str,
message_id: &str,
) -> Result<()> {
get_connection()
.await?
.set(format!("call_started_message:{channel_id}"), message_id)
.await
.to_internal_error()
}
pub async fn take_channel_call_started_system_message(channel_id: &str) -> Result<Option<String>> {
get_connection()
.await?
.get_del(format!("call_started_message:{channel_id}"))
.await
.to_internal_error()
}
pub async fn set_call_notification_recipients(
channel_id: &str,
user_id: &str,
recipients: &[String],
) -> Result<()> {
get_connection()
.await?
.set_ex(
format!("call_notification_recipients:{channel_id}-{user_id}"),
recipients,
10,
)
.await
.to_internal_error()
}
pub async fn get_call_notification_recipients(
channel_id: &str,
user_id: &str,
) -> Result<Option<Vec<String>>> {
get_connection()
.await?
.get_del(format!(
"call_notification_recipients:{channel_id}-{user_id}"
))
.await
.to_internal_error()
}

View File

@@ -1,156 +0,0 @@
use crate::{
models::{Channel, User},
Database,
};
use livekit_api::{
access_token::{AccessToken, VideoGrants},
services::room::{CreateRoomOptions, RoomClient as InnerRoomClient, UpdateParticipantOptions},
};
use livekit_protocol::{ParticipantInfo, ParticipantPermission, Room};
use revolt_config::{config, LiveKitNode};
use revolt_permissions::{ChannelPermission, PermissionValue};
use revolt_result::{create_error, Result, ToRevoltError};
use std::{collections::HashMap, time::Duration};
use super::get_allowed_sources;
#[derive(Debug)]
pub struct RoomClient {
pub client: InnerRoomClient,
pub node: LiveKitNode,
}
#[derive(Debug)]
pub struct VoiceClient {
pub rooms: HashMap<String, RoomClient>,
}
impl VoiceClient {
pub fn new(nodes: HashMap<String, LiveKitNode>) -> Self {
Self {
rooms: nodes
.into_iter()
.map(|(name, node)| {
(
name,
RoomClient {
client: InnerRoomClient::with_api_key(
&node.url,
&node.key,
&node.secret,
),
node,
},
)
})
.collect(),
}
}
pub fn is_enabled(&self) -> bool {
!self.rooms.is_empty()
}
pub async fn from_revolt_config() -> Self {
let config = config().await;
Self::new(config.api.livekit.nodes.clone())
}
pub fn get_node(&self, name: &str) -> Result<&RoomClient> {
self.rooms
.get(name)
.ok_or_else(|| create_error!(UnknownNode))
}
pub async fn create_token(
&self,
node: &str,
db: &Database,
user: &User,
permissions: PermissionValue,
channel: &Channel,
) -> Result<String> {
let room = self.get_node(node)?;
let limits = user.limits().await;
let allowed_sources = get_allowed_sources(&limits, permissions);
AccessToken::with_api_key(&room.node.key, &room.node.secret)
.with_name(&format!("{}#{}", user.username, user.discriminator))
.with_identity(&user.id)
.with_metadata(
&serde_json::to_string(&user.clone().into(db, None).await).to_internal_error()?,
)
.with_ttl(Duration::from_secs(10))
.with_grants(VideoGrants {
room_join: true,
can_publish: true,
can_publish_data: false,
can_publish_sources: allowed_sources
.into_iter()
.map(ToString::to_string)
.collect(),
can_subscribe: permissions.has_channel_permission(ChannelPermission::Listen),
room: channel.id().to_string(),
..Default::default()
})
.to_jwt()
.to_internal_error()
}
pub async fn create_room(&self, node: &str, channel: &Channel) -> Result<Room> {
let room = self.get_node(node)?;
room.client
.create_room(
channel.id(),
CreateRoomOptions {
empty_timeout: 5 * 60, // 5 minutes,
..Default::default()
},
)
.await
.to_internal_error()
}
pub async fn update_permissions(
&self,
node: &str,
user: &User,
channel_id: &str,
new_permissions: ParticipantPermission,
) -> Result<ParticipantInfo> {
let room = self.get_node(node)?;
room.client
.update_participant(
channel_id,
&user.id,
UpdateParticipantOptions {
permission: Some(new_permissions),
..Default::default()
},
)
.await
.to_internal_error()
}
pub async fn remove_user(&self, node: &str, user_id: &str, channel_id: &str) -> Result<()> {
let room = self.get_node(node)?;
room.client
.remove_participant(channel_id, user_id)
.await
.to_internal_error()
}
pub async fn delete_room(&self, node: &str, channel_id: &str) -> Result<()> {
let room = self.get_node(node)?;
room.client
.delete_room(channel_id)
.await
.to_internal_error()
}
}

View File

@@ -0,0 +1,34 @@
use iso8601_timestamp::Timestamp;
use crate::v0::{PublicBot, OAuth2Scope};
auto_derived!(
/// Unique id of the user and bot
pub struct AuthorizedBotId {
/// User id
pub user: String,
/// Bot Id
pub bot: String,
}
pub struct AuthorizedBot {
/// Unique Id
#[serde(rename = "_id")]
pub id: AuthorizedBotId,
/// When the authorized oauth2 bot connection was created at
pub created_at: Timestamp,
/// If and when the authorized oauth2 bot connection was revoked at
pub deauthorized_at: Option<Timestamp>,
/// Scopes the bot has access to
pub scope: Vec<OAuth2Scope>,
}
pub struct AuthorizedBotsResponse {
pub public_bot: PublicBot,
pub authorized_bot: AuthorizedBot,
}
);

View File

@@ -1,4 +1,8 @@
use super::User;
use super::{User, OAuth2Scope, OAuth2ScopeReasoning};
use std::collections::HashMap;
#[cfg(feature = "validator")]
use validator::Validate;
auto_derived!(
/// Bot
@@ -48,6 +52,13 @@ auto_derived!(
)]
pub privacy_policy_url: String,
/// Oauth2 bot settings
#[cfg_attr(
feature = "serde",
serde(skip_serializing_if = "Option::is_none", default)
)]
pub oauth2: Option<BotOauth2>,
/// Enum of bot flags
#[cfg_attr(
feature = "serde",
@@ -60,6 +71,8 @@ auto_derived!(
pub enum FieldsBot {
Token,
InteractionsURL,
Oauth2,
Oauth2Secret,
}
/// Flags that may be attributed to a bot
@@ -101,7 +114,7 @@ auto_derived!(
/// Bot Details
#[derive(Default)]
#[cfg_attr(feature = "validator", derive(validator::Validate))]
#[cfg_attr(feature = "validator", derive(Validate))]
pub struct DataCreateBot {
/// Bot username
#[cfg_attr(
@@ -113,7 +126,7 @@ auto_derived!(
/// New Bot Details
#[derive(Default)]
#[cfg_attr(feature = "validator", derive(validator::Validate))]
#[cfg_attr(feature = "validator", derive(Validate))]
pub struct DataEditBot {
/// Bot username
#[cfg_attr(
@@ -131,11 +144,24 @@ auto_derived!(
/// Interactions URL
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 2048)))]
pub interactions_url: Option<String>,
#[cfg_attr(feature = "validator", validate)]
pub oauth2: Option<DataEditBotOauth2>,
/// Fields to remove from bot object
#[cfg_attr(feature = "serde", serde(default))]
pub remove: Vec<FieldsBot>,
}
#[derive(Default)]
#[cfg_attr(feature = "validator", derive(Validate))]
pub struct DataEditBotOauth2 {
pub public: Option<bool>,
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 10)))]
pub redirects: Option<Vec<String>>,
pub allowed_scopes: Option<HashMap<OAuth2Scope, OAuth2ScopeReasoning>>
}
/// Where we are inviting a bot to
#[serde(untagged)]
pub enum InviteBotDestination {
@@ -170,3 +196,22 @@ auto_derived!(
pub user: User,
}
);
auto_derived_partial!(
/// Bot Oauth2 information
pub struct BotOauth2 {
/// Whether the oauth client is public and should not receive a secret key
#[serde(default)]
pub public: bool,
/// Secret key used for authorisation, not provided if the client is public
#[serde(default)]
pub secret: Option<String>,
/// Allowed redirects for the authorisation
#[serde(default)]
pub redirects: Vec<String>,
/// Mapping of allowed scopes and the reasonings
#[serde(default)]
pub allowed_scopes: HashMap<OAuth2Scope, OAuth2ScopeReasoning>,
},
"PartialBotOauth2"
);

View File

@@ -1,5 +1,4 @@
#![allow(deprecated)]
use super::{File, UserVoiceState};
use super::File;
use revolt_permissions::{Override, OverrideField};
use std::collections::{HashMap, HashSet};
@@ -108,21 +107,44 @@ auto_derived!(
serde(skip_serializing_if = "crate::if_false", default)
)]
nsfw: bool,
/// Voice Information for when this channel is also a voice channel
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
voice: Option<VoiceInformation>,
},
}
/// Voice channel belonging to a server
VoiceChannel {
/// Unique Id
#[cfg_attr(feature = "serde", serde(rename = "_id"))]
id: String,
/// Id of the server this channel belongs to
server: String,
/// Voice information for a channel
#[derive(Default)]
#[cfg_attr(feature = "validator", derive(validator::Validate))]
pub struct VoiceInformation {
/// Maximium amount of users allowed in the voice channel at once
#[cfg_attr(feature = "validator", validate(range(min = 1)))]
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub max_users: Option<usize>,
/// Display name of the channel
name: String,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
/// Channel description
description: Option<String>,
/// Custom icon attachment
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
icon: Option<File>,
/// Default permissions assigned to users in this channel
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
default_permissions: Option<OverrideField>,
/// Permissions assigned based on role to this channel
#[cfg_attr(
feature = "serde",
serde(
default = "HashMap::<String, OverrideField>::new",
skip_serializing_if = "HashMap::<String, OverrideField>::is_empty"
)
)]
role_permissions: HashMap<String, OverrideField>,
/// Whether this channel is marked as not safe for work
#[cfg_attr(
feature = "serde",
serde(skip_serializing_if = "crate::if_false", default)
)]
nsfw: bool,
},
}
/// Partial representation of a channel
@@ -148,8 +170,6 @@ auto_derived!(
pub default_permissions: Option<OverrideField>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub last_message_id: Option<String>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub voice: Option<VoiceInformation>,
}
/// Optional fields on channel object
@@ -157,7 +177,6 @@ auto_derived!(
Description,
Icon,
DefaultPermissions,
Voice,
}
/// New webhook information
@@ -186,9 +205,6 @@ auto_derived!(
/// Whether this channel is archived
pub archived: Option<bool>,
/// Voice Information for voice channels
pub voice: Option<VoiceInformation>,
/// Fields to remove from channel
#[cfg_attr(feature = "serde", serde(default))]
pub remove: Vec<FieldsChannel>,
@@ -244,10 +260,6 @@ auto_derived!(
/// Whether this channel is age restricted
#[serde(skip_serializing_if = "Option::is_none")]
pub nsfw: Option<bool>,
/// Voice Information for when this channel is also a voice channel
#[serde(skip_serializing_if = "Option::is_none")]
pub voice: Option<VoiceInformation>,
}
/// New default permissions
@@ -258,7 +270,7 @@ auto_derived!(
permissions: u64,
},
Field {
/// Allow / deny values to set for members in this server channel
/// Allow / deny values to set for members in this `TextChannel` or `VoiceChannel`
permissions: Override,
},
}
@@ -277,32 +289,9 @@ auto_derived!(
}
/// Voice server token response
pub struct CreateVoiceUserResponse {
pub struct LegacyCreateVoiceUserResponse {
/// Token for authenticating with the voice server
pub token: String,
/// Url of the livekit server to connect to
pub url: String,
}
/// Voice state for a channel
pub struct ChannelVoiceState {
pub id: String,
/// The states of the users who are connected to the channel
pub participants: Vec<UserVoiceState>,
}
/// Join a voice channel
pub struct DataJoinCall {
/// Name of the node to join
pub node: Option<String>,
/// Whether to force disconnect any other existing voice connections
///
/// Useful for disconnecting on another device and joining on a new.
pub force_disconnect: Option<bool>,
/// Users which should be notified of the call starting
///
/// Only used when the user is the first one connected.
pub recipients: Option<Vec<String>>,
token: String,
}
);
@@ -313,7 +302,8 @@ impl Channel {
Channel::DirectMessage { id, .. }
| Channel::Group { id, .. }
| Channel::SavedMessages { id, .. }
| Channel::TextChannel { id, .. } => id,
| Channel::TextChannel { id, .. }
| Channel::VoiceChannel { id, .. } => id,
}
}
@@ -325,7 +315,9 @@ impl Channel {
match self {
Channel::DirectMessage { .. } => None,
Channel::SavedMessages { .. } => Some("Saved Messages"),
Channel::TextChannel { name, .. } | Channel::Group { name, .. } => Some(name),
Channel::TextChannel { name, .. }
| Channel::Group { name, .. }
| Channel::VoiceChannel { name, .. } => Some(name),
}
}
}

View File

@@ -132,8 +132,6 @@ auto_derived!(
MessagePinned { id: String, by: String },
#[serde(rename = "message_unpinned")]
MessageUnpinned { id: String, by: String },
#[serde(rename = "call_started")]
CallStarted { by: String, finished_at: Option<Timestamp> },
}
/// Name and / or avatar override information
@@ -447,7 +445,6 @@ impl From<SystemMessage> for String {
}
SystemMessage::MessagePinned { .. } => "Message pinned.".to_string(),
SystemMessage::MessageUnpinned { .. } => "Message unpinned.".to_string(),
SystemMessage::CallStarted { .. } => "Call started.".to_string(),
}
}
}

View File

@@ -1,3 +1,4 @@
mod authorized_bots;
mod bots;
mod channel_invites;
mod channel_unreads;
@@ -7,6 +8,7 @@ mod embeds;
mod emojis;
mod files;
mod messages;
mod oauth2;
mod policy_changes;
mod safety_reports;
mod server_bans;
@@ -15,6 +17,7 @@ mod servers;
mod user_settings;
mod users;
pub use authorized_bots::*;
pub use bots::*;
pub use channel_invites::*;
pub use channel_unreads::*;
@@ -24,6 +27,7 @@ pub use embeds::*;
pub use emojis::*;
pub use files::*;
pub use messages::*;
pub use oauth2::*;
pub use policy_changes::*;
pub use safety_reports::*;
pub use server_bans::*;

View File

@@ -0,0 +1,140 @@
use crate::v0::{PublicBot, User};
use std::{collections::HashMap, fmt::Display};
auto_derived!(
pub struct OAuth2AuthorizeAuthResponse {
/// Redirect URI which will contain the access token
pub redirect_uri: String,
}
pub struct OAuth2ScopeReasoning {
pub allow: String,
pub deny: String
}
pub struct OAuth2AuthorizeInfoResponse {
pub bot: PublicBot,
pub user: User,
pub allowed_scopes: HashMap<OAuth2Scope, OAuth2ScopeReasoning>
}
#[derive(Copy)]
#[cfg_attr(feature = "serde", serde(rename = "lowercase"))]
#[cfg_attr(feature = "rocket", derive(rocket::FromFormField))]
pub enum OAuth2ResponseType {
#[cfg_attr(feature = "rocket", field(value = "code"))]
Code,
#[cfg_attr(feature = "rocket", field(value = "token"))]
Token,
}
#[derive(Copy)]
#[cfg_attr(feature = "rocket", derive(rocket::FromFormField))]
pub enum OAuth2GrantType {
#[cfg_attr(feature = "rocket", field(value = "authorization_code"))]
#[cfg_attr(feature = "serde", serde(rename = "authorization_code"))]
AuthorizationCode,
#[cfg_attr(feature = "rocket", field(value = "implicit"))]
#[cfg_attr(feature = "serde", serde(rename = "implicit"))]
Implicit,
#[cfg_attr(feature = "rocket", field(value = "refresh_token"))]
#[cfg_attr(feature = "serde", serde(rename = "refresh_token"))]
RefreshToken
}
#[derive(Copy)]
#[cfg_attr(feature = "rocket", derive(rocket::FromFormField))]
pub enum OAuth2CodeChallangeMethod {
#[cfg_attr(feature = "rocket", field(value = "plain"))]
#[cfg_attr(feature = "serde", serde(rename = "plain"))]
Plain,
S256
}
#[cfg_attr(feature = "rocket", derive(rocket::FromForm))]
pub struct OAuth2AuthorizationForm {
pub client_id: String,
pub scope: String,
pub redirect_uri: String,
pub response_type: OAuth2ResponseType,
pub state: Option<String>,
pub code_challenge: Option<String>,
pub code_challenge_method: Option<OAuth2CodeChallangeMethod>,
}
#[cfg_attr(feature = "rocket", derive(rocket::FromForm))]
pub struct OAuth2TokenExchangeForm {
pub grant_type: OAuth2GrantType,
pub client_id: String,
pub client_secret: Option<String>,
/// Authorization code
pub code: Option<String>,
// Refresh token to generate new access token
pub refresh_token: Option<String>,
pub code_verifier: Option<String>,
}
pub struct OAuth2TokenExchangeResponse {
pub access_token: String,
pub refresh_token: Option<String>,
pub token_type: String,
pub scope: String,
}
#[derive(Copy, Hash)]
#[cfg_attr(feature = "serde", serde(rename = "snake_case"))]
pub enum OAuth2Scope {
#[cfg_attr(feature = "serde", serde(rename = "read:identify"))]
ReadIdentify,
#[cfg_attr(feature = "serde", serde(rename = "read:servers"))]
ReadServers,
#[cfg_attr(feature = "serde", serde(rename = "write:files"))]
WriteFiles,
#[cfg_attr(feature = "serde", serde(rename = "events"))]
Events,
#[cfg_attr(feature = "serde", serde(rename = "full"))]
Full,
}
);
impl Display for OAuth2Scope {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
OAuth2Scope::ReadIdentify => "read:identify",
OAuth2Scope::ReadServers => "read:servers",
OAuth2Scope::WriteFiles => "write:files",
OAuth2Scope::Events => "events",
OAuth2Scope::Full => "full",
})
}
}
impl OAuth2Scope {
#[allow(clippy::should_implement_trait)]
pub fn from_str(str: &str) -> Option<OAuth2Scope> {
match str {
"read:identify" => Some(OAuth2Scope::ReadIdentify),
"read:servers" => Some(OAuth2Scope::ReadServers),
"events" => Some(OAuth2Scope::Events),
"full" => Some(OAuth2Scope::Full),
_ => None,
}
}
pub fn scopes_from_str(string: &str) -> Option<Vec<OAuth2Scope>> {
let mut scopes = Vec::new();
for scope in string.split(' ') {
if let Some(scope) = OAuth2Scope::from_str(scope) {
scopes.push(scope);
} else {
return None;
}
}
Some(scopes)
}
}

View File

@@ -31,14 +31,6 @@ pub static RE_COLOUR: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"(?i)^(?:[a-z ]+|var\(--[a-z\d-]+\)|rgba?\([\d, ]+\)|#[a-f0-9]+|(repeating-)?(linear|conic|radial)-gradient\(([a-z ]+|var\(--[a-z\d-]+\)|rgba?\([\d, ]+\)|#[a-f0-9]+|\d+deg)([ ]+(\d{1,3}%|0))?(,[ ]*([a-z ]+|var\(--[a-z\d-]+\)|rgba?\([\d, ]+\)|#[a-f0-9]+)([ ]+(\d{1,3}%|0))?)+\))$").unwrap()
});
fn default_true() -> bool {
true
}
fn is_true(x: &bool) -> bool {
*x
}
auto_derived_partial!(
/// Server Member
pub struct Member {
@@ -65,13 +57,6 @@ auto_derived_partial!(
/// Timestamp this member is timed out until
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub timeout: Option<Timestamp>,
/// Whether the member is server-wide voice muted
#[serde(skip_serializing_if = "is_true", default = "default_true")]
pub can_publish: bool,
/// Whether the member is server-wide voice deafened
#[serde(skip_serializing_if = "is_true", default = "default_true")]
pub can_receive: bool,
},
"PartialMember"
);
@@ -92,8 +77,6 @@ auto_derived!(
Avatar,
Roles,
Timeout,
CanReceive,
CanPublish,
JoinedAt,
}
@@ -141,12 +124,6 @@ auto_derived!(
pub roles: Option<Vec<String>>,
/// Timestamp this member is timed out until
pub timeout: Option<Timestamp>,
/// server-wide voice muted
pub can_publish: Option<bool>,
/// server-wide voice deafened
pub can_receive: Option<bool>,
/// voice channel to move to if already in a voice channel
pub voice_channel: Option<String>,
/// Fields to remove from channel object
#[cfg_attr(feature = "serde", serde(default))]
pub remove: Vec<FieldsMember>,

View File

@@ -1,4 +1,3 @@
use iso8601_timestamp::Timestamp;
use once_cell::sync::Lazy;
use regex::Regex;
@@ -280,19 +279,6 @@ auto_derived!(
}
);
auto_derived_partial!(
/// Voice State information for a user
pub struct UserVoiceState {
pub id: String,
pub joined_at: Timestamp,
pub is_receiving: bool,
pub is_publishing: bool,
pub screensharing: bool,
pub camera: bool,
},
"PartialUserVoiceState"
);
pub trait CheckRelationship {
fn with(&self, user: &str) -> RelationshipStatus;
}

View File

@@ -61,15 +61,6 @@ pub async fn calculate_server_permissions<P: PermissionQuery>(query: &mut P) ->
permissions.apply(role_override);
}
if !query.do_we_have_publish_overwrites().await {
permissions.revoke(ChannelPermission::Speak as u64);
permissions.revoke(ChannelPermission::Video as u64);
}
if !query.do_we_have_receive_overwrites().await {
permissions.revoke(ChannelPermission::Listen as u64);
}
if query.are_we_timed_out().await {
permissions.restrict(*ALLOW_IN_TIMEOUT);
}

View File

@@ -89,8 +89,6 @@ pub enum ChannelPermission {
DeafenMembers = 1 << 34,
/// Move members between voice channels
MoveMembers = 1 << 35,
/// Listen to other users
Listen = 1 << 36,
// * Channel permissions two electric boogaloo
/// Mention everyone and online members
@@ -132,9 +130,7 @@ pub static DEFAULT_PERMISSION: Lazy<u64> = Lazy::new(|| {
+ ChannelPermission::SendEmbeds
+ ChannelPermission::UploadFiles
+ ChannelPermission::Connect
+ ChannelPermission::Speak
+ ChannelPermission::Listen
+ ChannelPermission::Video
+ ChannelPermission::Speak,
)
});

View File

@@ -39,7 +39,7 @@ pub enum DataPermissionPoly {
permissions: u64,
},
Field {
/// Allow / deny values to set for members in this server channel
/// Allow / deny values to set for members in this `TextChannel` or `VoiceChannel`
permissions: Override,
},
}

View File

@@ -64,14 +64,6 @@ async fn validate_user_permissions() {
unreachable!()
}
async fn do_we_have_publish_overwrites(&mut self) -> bool {
true
}
async fn do_we_have_receive_overwrites(&mut self) -> bool {
true
}
async fn get_channel_type(&mut self) -> ChannelType {
ChannelType::DirectMessage
}
@@ -161,14 +153,6 @@ async fn validate_group_permissions() {
unreachable!()
}
async fn do_we_have_publish_overwrites(&mut self) -> bool {
true
}
async fn do_we_have_receive_overwrites(&mut self) -> bool {
true
}
async fn get_channel_type(&mut self) -> ChannelType {
ChannelType::Group
}
@@ -270,14 +254,6 @@ async fn validate_server_permissions() {
false
}
async fn do_we_have_publish_overwrites(&mut self) -> bool {
true
}
async fn do_we_have_receive_overwrites(&mut self) -> bool {
true
}
async fn get_channel_type(&mut self) -> ChannelType {
ChannelType::ServerChannel
}
@@ -370,14 +346,6 @@ async fn validate_timed_out_member() {
true
}
async fn do_we_have_publish_overwrites(&mut self) -> bool {
true
}
async fn do_we_have_receive_overwrites(&mut self) -> bool {
true
}
async fn get_channel_type(&mut self) -> ChannelType {
ChannelType::ServerChannel
}

View File

@@ -39,12 +39,6 @@ pub trait PermissionQuery {
/// Is our perspective user timed out on this server?
async fn are_we_timed_out(&mut self) -> bool;
/// Is the member muted?
async fn do_we_have_publish_overwrites(&mut self) -> bool;
/// Is the member deafend?
async fn do_we_have_receive_overwrites(&mut self) -> bool;
// * For calculating channel permission
/// Get the type of the channel

View File

@@ -32,7 +32,5 @@ rocket = { optional = true, version = "0.5.0-rc.2", default-features = false }
revolt_rocket_okapi = { version = "0.10.0", optional = true }
revolt_okapi = { version = "0.9.1", optional = true }
# utilities
log = "0.4"
# Axum
axum = { version = "0.7.5", optional = true }

View File

@@ -75,14 +75,12 @@ impl IntoResponse for Error {
ErrorType::NotFound => StatusCode::NOT_FOUND,
ErrorType::NoEffect => StatusCode::OK,
ErrorType::FailedValidation { .. } => StatusCode::BAD_REQUEST,
ErrorType::LiveKitUnavailable => StatusCode::BAD_REQUEST,
ErrorType::NotConnected => StatusCode::BAD_REQUEST,
ErrorType::NotAVoiceChannel => StatusCode::BAD_REQUEST,
ErrorType::AlreadyConnected => StatusCode::BAD_REQUEST,
ErrorType::UnknownNode => StatusCode::BAD_REQUEST,
ErrorType::InvalidFlagValue => StatusCode::BAD_REQUEST,
ErrorType::FeatureDisabled { .. } => StatusCode::BAD_REQUEST,
ErrorType::MissingScope { .. } => StatusCode::UNAUTHORIZED,
ErrorType::ExpiredToken => StatusCode::UNAUTHORIZED,
ErrorType::ProxyError => StatusCode::BAD_REQUEST,
ErrorType::FileTooSmall => StatusCode::UNPROCESSABLE_ENTITY,
ErrorType::FileTooLarge { .. } => StatusCode::UNPROCESSABLE_ENTITY,

View File

@@ -1,4 +1,3 @@
use std::panic::Location;
use std::fmt::Display;
#[cfg(feature = "serde")]
@@ -52,7 +51,7 @@ impl std::error::Error for Error {}
#[cfg_attr(feature = "serde", serde(tag = "type"))]
#[cfg_attr(feature = "schemas", derive(JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ErrorType {
/// This error was not labeled :(
LabelMe,
@@ -159,12 +158,6 @@ pub enum ErrorType {
error: String,
},
// ? Voice errors
LiveKitUnavailable,
NotAVoiceChannel,
AlreadyConnected,
NotConnected,
UnknownNode,
// ? Micro-service errors
ProxyError,
FileTooSmall,
@@ -175,6 +168,12 @@ pub enum ErrorType {
ImageProcessingFailed,
NoEmbedData,
// ? OAuth2 Errors
ExpiredToken,
MissingScope {
scope: String
},
// ? Legacy errors
VosoUnavailable,
@@ -204,57 +203,6 @@ macro_rules! create_database_error {
};
}
#[macro_export]
#[cfg(debug_assertions)]
macro_rules! query {
( $self: ident, $type: ident, $collection: expr, $($rest:expr),+ ) => {
Ok($self.$type($collection, $($rest),+).await.unwrap())
};
}
#[macro_export]
#[cfg(not(debug_assertions))]
macro_rules! query {
( $self: ident, $type: ident, $collection: expr, $($rest:expr),+ ) => {
$self.$type($collection, $($rest),+).await
.map_err(|_| create_database_error!(stringify!($type), $collection))
};
}
pub trait ToRevoltError<T> {
#[track_caller]
fn to_internal_error(self) -> Result<T, Error>;
}
impl<T, E: std::fmt::Debug> ToRevoltError<T> for Result<T, E> {
#[track_caller]
fn to_internal_error(self) -> Result<T, Error> {
let loc = Location::caller();
self
.map_err(|_| {
Error {
error_type: ErrorType::InternalError,
location: format!("{}:{}:{}", loc.file(), loc.line(), loc.column())
}
})
}
}
impl<T> ToRevoltError<T> for Option<T> {
#[track_caller]
fn to_internal_error(self) -> Result<T, Error> {
let loc = Location::caller();
self.ok_or_else(|| {
Error {
error_type: ErrorType::InternalError,
location: format!("{}:{}:{}", loc.file(), loc.line(), loc.column())
}
})
}
}
#[cfg(test)]
mod tests {
use crate::ErrorType;

View File

@@ -78,23 +78,21 @@ impl<'r> Responder<'r, 'static> for Error {
ErrorType::InvalidSession => Status::Unauthorized,
ErrorType::NotAuthenticated => Status::Unauthorized,
ErrorType::DuplicateNonce => Status::Conflict,
ErrorType::VosoUnavailable => Status::BadRequest,
ErrorType::NotFound => Status::NotFound,
ErrorType::NoEffect => Status::Ok,
ErrorType::FailedValidation { .. } => Status::BadRequest,
ErrorType::LiveKitUnavailable => Status::BadRequest,
ErrorType::NotAVoiceChannel => Status::BadRequest,
ErrorType::AlreadyConnected => Status::BadRequest,
ErrorType::NotConnected => Status::BadRequest,
ErrorType::UnknownNode => Status::BadRequest,
ErrorType::FeatureDisabled { .. } => Status::BadRequest,
ErrorType::MissingScope { .. } => Status::Unauthorized,
ErrorType::ExpiredToken => Status::Unauthorized,
ErrorType::ProxyError => Status::BadRequest,
ErrorType::FileTooSmall => Status::UnprocessableEntity,
ErrorType::FileTooLarge { .. } => Status::UnprocessableEntity,
ErrorType::FileTypeNotAllowed => Status::BadRequest,
ErrorType::ImageProcessingFailed => Status::InternalServerError,
ErrorType::NoEmbedData => Status::BadRequest,
ErrorType::VosoUnavailable => Status::BadRequest,
};
// Serialize the error data structure into JSON.

View File

@@ -1,5 +1,5 @@
# Build Stage
FROM ghcr.io/revoltchat/base:latest AS builder
FROM ghcr.io/stoatchat/base:latest AS builder
FROM debian:12 AS debian
# Bundle Stage

View File

@@ -4,6 +4,8 @@ use revolt_result::Result;
use tasks::{file_deletion, prune_dangling_files, prune_members};
use tokio::try_join;
use crate::tasks::prune_authorized_bots;
pub mod tasks;
#[tokio::main]
@@ -14,6 +16,7 @@ async fn main() -> Result<()> {
try_join!(
file_deletion::task(db.clone()),
prune_dangling_files::task(db.clone()),
prune_authorized_bots::task(db.clone()),
prune_members::task(db.clone())
)
.map(|_| ())

View File

@@ -1,3 +1,4 @@
pub mod file_deletion;
pub mod prune_dangling_files;
pub mod prune_authorized_bots;
pub mod prune_members;

View File

@@ -0,0 +1,22 @@
use revolt_database::{iso8601_timestamp::{Duration, Timestamp}, util::oauth2::TokenType, Database};
use revolt_result::Result;
use tokio::time::sleep;
pub async fn task(db: Database) -> Result<()> {
let lifetime = Duration::new(TokenType::Access.lifetime().num_seconds(), 0);
loop {
let deauthorized_bots = db.fetch_deauthorized_authorized_bots().await?;
for bot in deauthorized_bots {
if let Some(deauthorized_at) = &bot.deauthorized_at {
if deauthorized_at.saturating_add(lifetime) < Timestamp::now_utc() {
db.delete_authorized_bot(&bot.id).await?;
};
};
};
// 1 hour
sleep(std::time::Duration::from_secs(60 * 60)).await;
}
}

View File

@@ -1,5 +1,5 @@
# Build Stage
FROM ghcr.io/revoltchat/base:latest AS builder
FROM ghcr.io/stoatchat/base:latest AS builder
FROM debian:12 AS debian
# Bundle Stage

View File

@@ -1,168 +0,0 @@
use std::collections::HashMap;
use crate::consumers::inbound::internal::*;
use amqprs::{
channel::{BasicPublishArguments, Channel},
connection::Connection,
consumer::AsyncConsumer,
BasicProperties, Deliver,
};
use anyhow::Result;
use async_trait::async_trait;
use log::debug;
use revolt_database::{events::rabbit::*, Database};
pub struct DmCallConsumer {
#[allow(dead_code)]
db: Database,
authifier_db: authifier::Database,
conn: Option<Connection>,
channel: Option<Channel>,
}
impl Channeled for DmCallConsumer {
fn get_connection(&self) -> Option<&Connection> {
if self.conn.is_none() {
None
} else {
Some(self.conn.as_ref().unwrap())
}
}
fn get_channel(&self) -> Option<&Channel> {
if self.channel.is_none() {
None
} else {
Some(self.channel.as_ref().unwrap())
}
}
fn set_connection(&mut self, conn: Connection) {
self.conn = Some(conn);
}
fn set_channel(&mut self, channel: Channel) {
self.channel = Some(channel)
}
}
impl DmCallConsumer {
pub fn new(db: Database, authifier_db: authifier::Database) -> DmCallConsumer {
DmCallConsumer {
db,
authifier_db,
conn: None,
channel: None,
}
}
async fn consume_event(
&mut self,
_channel: &Channel,
_deliver: Deliver,
_basic_properties: BasicProperties,
content: Vec<u8>,
) -> Result<()> {
let content = String::from_utf8(content)?;
let _p: InternalDmCallPayload = serde_json::from_str(content.as_str())?;
let payload = _p.payload;
debug!("Received dm call start/stop event");
let (revolt_database::Channel::DirectMessage { recipients, .. }
| revolt_database::Channel::Group { recipients, .. }) =
self.db.fetch_channel(&payload.channel_id).await?
else {
warn!(
"Discarding dm call start/stop event for non-dm/group channel {}",
payload.channel_id
);
return Ok(());
};
let call_recipients = if let Some(user_recipients) = _p.recipients {
user_recipients
.into_iter()
.filter(|user_id| recipients.contains(user_id) && user_id != &payload.initiator_id)
.collect()
} else {
recipients
.into_iter()
.filter(|user_id| user_id != &payload.initiator_id)
.collect::<Vec<_>>()
};
let config = revolt_config::config().await;
for user_id in call_recipients {
if let Ok(sessions) = self.authifier_db.find_sessions(&user_id).await {
for session in sessions {
if let Some(sub) = session.subscription {
let mut sendable = PayloadToService {
notification: PayloadKind::DmCallStartEnd(payload.clone()),
token: sub.auth,
user_id: session.user_id,
session_id: session.id,
extras: HashMap::new(),
};
let args: BasicPublishArguments;
if sub.endpoint == "apn" {
args = BasicPublishArguments::new(
config.pushd.exchange.as_str(),
config.pushd.apn.queue.as_str(),
)
.finish();
} else if sub.endpoint == "fcm" {
args = BasicPublishArguments::new(
config.pushd.exchange.as_str(),
config.pushd.fcm.queue.as_str(),
)
.finish();
} else {
// web push (vapid)
args = BasicPublishArguments::new(
config.pushd.exchange.as_str(),
config.pushd.vapid.queue.as_str(),
)
.finish();
sendable.extras.insert("p265dh".to_string(), sub.p256dh);
sendable
.extras
.insert("endpoint".to_string(), sub.endpoint.clone());
}
let payload = serde_json::to_string(&sendable)?;
publish_message(self, payload.into(), args).await;
}
}
}
}
Ok(())
}
}
#[allow(unused_variables)]
#[async_trait]
impl AsyncConsumer for DmCallConsumer {
/// This consumer handles delegating messages into their respective platform queues.
async fn consume(
&mut self,
channel: &Channel,
deliver: Deliver,
basic_properties: BasicProperties,
content: Vec<u8>,
) {
if let Err(err) = self
.consume_event(channel, deliver, basic_properties, content)
.await
{
revolt_config::capture_anyhow(&err);
warn!("Failed to process dm call start/stop event: {err:?}");
}
}
}

View File

@@ -1,5 +1,4 @@
pub mod ack;
pub mod dm_call;
pub mod fr_accepted;
pub mod fr_received;
pub mod generic;

View File

@@ -47,32 +47,6 @@ impl<'a> PayloadLike for MessagePayload<'a> {
}
}
#[derive(Serialize, Debug)]
struct CallStartStopPayload<'a> {
aps: APS<'a>,
#[serde(skip_serializing)]
options: NotificationOptions<'a>,
#[serde(skip_serializing)]
device_token: &'a str,
initiator_id: &'a str,
#[serde(rename = "camelCase")]
channel_id: &'a str,
#[serde(rename = "camelCase")]
started_at: &'a str,
#[serde(rename = "camelCase")]
ended: bool,
}
impl<'a> PayloadLike for CallStartStopPayload<'a> {
fn get_device_token(&self) -> &'a str {
self.device_token
}
fn get_options(&self) -> &NotificationOptions {
&self.options
}
}
// region: consumer
pub struct ApnsOutboundConsumer {
@@ -89,11 +63,10 @@ impl ApnsOutboundConsumer {
// in a dm it should just be "Sendername".
// not sure how feasible all those are given the PushNotification object as it currently stands.
#[allow(deprecated)]
match &notification.channel {
Channel::DirectMessage { .. } => notification.author.clone(),
Channel::Group { name, .. } => format!("{}, #{}", notification.author, name),
Channel::TextChannel { name, .. } => {
Channel::TextChannel { name, .. } | Channel::VoiceChannel { name, .. } => {
format!("{} in #{}", notification.author, name)
}
_ => "Unknown".to_string(),
@@ -336,7 +309,6 @@ impl ApnsOutboundConsumer {
);
resp = self.client.send(apn_payload).await;
}
PayloadKind::BadgeUpdate(badge) => {
let apn_payload = Payload {
aps: APS {
@@ -351,35 +323,6 @@ impl ApnsOutboundConsumer {
debug!("Sending badge update for user: {:}", &payload.user_id);
resp = self.client.send(apn_payload).await;
}
PayloadKind::DmCallStartEnd(alert) => {
let started_at = alert.started_at.map_or(String::new(), |f| f.clone());
let apn_payload = CallStartStopPayload {
aps: APS {
alert: None,
badge: self.get_badge_count(&payload.user_id).await,
sound: None,
thread_id: None,
content_available: None,
category: None,
mutable_content: Some(1),
url_args: None,
},
device_token: &payload.token,
options: payload_options.clone(),
initiator_id: &alert.initiator_id,
channel_id: &alert.channel_id,
started_at: &started_at,
ended: alert.ended,
};
debug!(
"Sending call start/stop notification for user: {:}",
&payload.user_id
);
resp = self.client.send(apn_payload).await;
}
}
if let Err(err) = resp {

View File

@@ -5,12 +5,11 @@ use amqprs::{channel::Channel as AmqpChannel, consumer::AsyncConsumer, BasicProp
use anyhow::{anyhow, bail, Result};
use async_trait::async_trait;
use fcm_v1::{
android::{AndroidConfig, AndroidMessagePriority},
android::AndroidConfig,
auth::{Authenticator, ServiceAccountKey},
message::{Message, Notification},
Client, Error as FcmError,
};
use revolt_config::config;
use revolt_database::{events::rabbit::*, Database};
use revolt_models::v0::{Channel, PushNotification};
use serde_json::Value;
@@ -28,11 +27,10 @@ impl FcmOutboundConsumer {
// in a dm it should just be "Sendername".
// not sure how feasible all those are given the PushNotification object as it currently stands.
#[allow(deprecated)]
match &notification.channel {
Channel::DirectMessage { .. } => notification.author.clone(),
Channel::Group { name, .. } => format!("{}, #{}", notification.author, name),
Channel::TextChannel { name, .. } => {
Channel::TextChannel { name, .. } | Channel::VoiceChannel { name, .. } => {
format!("{} in #{}", notification.author, name)
}
_ => "Unknown".to_string(),
@@ -171,37 +169,6 @@ impl FcmOutboundConsumer {
resp = self.client.send(&msg).await;
}
PayloadKind::DmCallStartEnd(alert) => {
let mut data: HashMap<String, Value> = HashMap::new();
data.insert(
"initiator_id".to_string(),
Value::String(alert.initiator_id),
);
data.insert("channel_id".to_string(), Value::String(alert.channel_id));
data.insert(
"started_at".to_string(),
Value::String(alert.started_at.unwrap_or_else(|| "".to_string())),
);
data.insert("ended".to_string(), Value::Bool(alert.ended));
let msg = Message {
token: Some(payload.token),
notification: None,
data: Some(data),
android: Some(AndroidConfig {
priority: Some(AndroidMessagePriority::High),
ttl: Some(format!(
"{}s",
config().await.api.livekit.call_ring_duration
)),
..Default::default()
}),
..Default::default()
};
resp = self.client.send(&msg).await;
}
PayloadKind::BadgeUpdate(_) => {
bail!("FCM cannot handle badge updates and they should not be sent here.");
}

View File

@@ -8,7 +8,7 @@ use base64::{
engine::{self},
Engine as _,
};
use revolt_database::{events::rabbit::*, util::format_display_name, Database};
use revolt_database::{events::rabbit::*, Database};
use web_push::{
ContentEncoding, IsahcWebPushClient, SubscriptionInfo, SubscriptionKeys, VapidSignatureBuilder,
WebPushClient, WebPushError, WebPushMessageBuilder,
@@ -107,33 +107,6 @@ impl VapidOutboundConsumer {
PayloadKind::MessageNotification(alert) => {
payload_body = serde_json::to_string(&alert)?;
}
PayloadKind::DmCallStartEnd(alert) => {
let initiator_name = if let Some(server_id) =
self.db.fetch_channel(&alert.channel_id).await?.server()
{
format_display_name(&self.db, &alert.initiator_id, Some(server_id)).await
} else {
format_display_name(&self.db, &alert.initiator_id, None).await
}?;
let channel = self.db.fetch_channel(&alert.channel_id).await?;
let mut body = HashMap::new();
match channel {
revolt_database::Channel::DirectMessage { .. } => {
body.insert("body", format!("{} is calling you", initiator_name));
}
revolt_database::Channel::Group { name, .. } => {
body.insert(
"body",
format!("{} is calling your group, {}", initiator_name, name),
);
}
_ => bail!("Invalid DmCallStart/End channel type"),
}
payload_body = serde_json::to_string(&body)?;
}
PayloadKind::BadgeUpdate(_) => {
bail!("Vapid cannot handle badge updates and they should not be sent here.");
}

View File

@@ -16,9 +16,8 @@ use tokio::sync::Notify;
mod consumers;
use consumers::{
inbound::{
ack::AckConsumer, dm_call::DmCallConsumer, fr_accepted::FRAcceptedConsumer,
fr_received::FRReceivedConsumer, generic::GenericConsumer,
mass_mention::MassMessageConsumer, message::MessageConsumer,
ack::AckConsumer, fr_accepted::FRAcceptedConsumer, fr_received::FRReceivedConsumer,
generic::GenericConsumer, mass_mention::MassMessageConsumer, message::MessageConsumer,
},
outbound::{apn::ApnsOutboundConsumer, fcm::FcmOutboundConsumer, vapid::VapidOutboundConsumer},
};
@@ -103,7 +102,6 @@ async fn main() {
.await,
);
// inbound: Mass Mentions
connections.push(
make_queue_and_consume(
&config,
@@ -115,18 +113,6 @@ async fn main() {
.await,
);
// inbound: Dm Calls
connections.push(
make_queue_and_consume(
&config,
&config.pushd.dm_call_queue,
config.pushd.get_dm_call_routing_key().as_str(),
None,
DmCallConsumer::new(db.clone(), authifier.clone()),
)
.await,
);
if !config.pushd.apn.pkcs8.is_empty() {
connections.push(
make_queue_and_consume(

View File

@@ -1 +0,0 @@
/target

View File

@@ -1,48 +0,0 @@
[package]
name = "revolt-voice-ingress"
version = "0.7.1"
license = "AGPL-3.0-or-later"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
# util
log = "*"
sentry = "0.31.5"
lru = "0.7.6"
ulid = "0.5.0"
redis-kiss = "0.1.4"
chrono = "0.4.15"
# Serde
serde_json = "1.0.79"
rmp-serde = "1.0.0"
serde = "1.0.136"
# Http
rocket = { version = "0.5.0-rc.2", features = ["json"] }
rocket_empty = "0.1.1"
# Async
futures = "0.3.21"
async-std = { version = "1.8.0", features = [
"tokio1",
"tokio02",
"attributes",
] }
# Core
revolt-result = { path = "../../core/result" }
revolt-models = { path = "../../core/models" }
revolt-config = { path = "../../core/config" }
revolt-database = { path = "../../core/database" }
revolt-permissions = { path = "../../core/permissions" }
# Voice
livekit-api = "0.4.4"
livekit-protocol = "0.4.0"
livekit-runtime = { version = "0.3.1", features = ["tokio"] }
# RabbitMQ
amqprs = { version = "1.7.0" }

View File

@@ -1,11 +0,0 @@
# Build Stage
FROM ghcr.io/revoltchat/base:latest AS builder
FROM debian:12 AS debian
# Bundle Stage
FROM gcr.io/distroless/cc-debian12:nonroot
COPY --from=builder /home/rust/src/target/release/revolt-voice-ingress ./
COPY --from=debian /usr/bin/uname /usr/bin/uname
USER nonroot
CMD ["./revolt-voice-ingress"]

View File

@@ -1,256 +0,0 @@
use chrono::DateTime;
use livekit_api::{access_token::TokenVerifier, webhooks::WebhookReceiver};
use livekit_protocol::TrackType;
use revolt_database::{
events::client::EventV1,
iso8601_timestamp::{Duration, Timestamp},
util::reference::Reference,
voice::{
create_voice_state, delete_voice_state, get_call_notification_recipients,
get_user_moved_from_voice, get_user_moved_to_voice, get_voice_channel_members,
set_channel_call_started_system_message, take_channel_call_started_system_message,
update_voice_state_tracks, VoiceClient,
},
Database, PartialMessage, SystemMessage, AMQP,
};
use revolt_models::v0;
use revolt_result::{Result, ToRevoltError};
use rocket::{post, State};
use rocket_empty::EmptyResponse;
use ulid::Ulid;
use crate::guard::AuthHeader;
#[post("/<node>", data = "<body>")]
pub async fn ingress(
db: &State<Database>,
voice_client: &State<VoiceClient>,
amqp: &State<AMQP>,
node: &str,
auth_header: AuthHeader<'_>,
body: &str,
) -> Result<EmptyResponse> {
log::debug!("received event: {body:?}");
let config = revolt_config::config().await;
let node_info = config
.api
.livekit
.nodes
.get(node)
.to_internal_error()
.inspect_err(|_| {
log::error!("Unknown node {node}, make sure livekit has the correct node name set and matches `hosts.livekit` and `api.livekit.nodes` in the Revolt config.")
})?;
let webhook_receiver = WebhookReceiver::new(TokenVerifier::with_api_key(
&node_info.key,
&node_info.secret,
));
let event = webhook_receiver
.receive(body, &auth_header)
.to_internal_error()?;
let channel_id = event.room.as_ref().map(|r| &r.name);
let user_id = event.participant.as_ref().map(|r| &r.identity);
match event.event.as_str() {
// User joined a channel
"participant_joined" => {
let channel_id = channel_id.to_internal_error()?;
let user_id = user_id.to_internal_error()?;
let channel = Reference::from_unchecked(channel_id).as_channel(db).await?;
let joined_at = Timestamp::UNIX_EPOCH
.checked_add(Duration::seconds(event.created_at))
.unwrap();
let voice_state =
create_voice_state(channel_id, channel.server(), user_id, joined_at).await?;
// Only publish one event when a user is moved from one channel to another.
if let Some(moved_from) = get_user_moved_to_voice(channel_id, user_id).await? {
EventV1::VoiceChannelMove {
user: user_id.to_string(),
from: moved_from,
to: channel_id.to_string(),
state: voice_state,
}
.p(channel_id.to_string())
.await;
} else {
EventV1::VoiceChannelJoin {
id: channel_id.to_string(),
state: voice_state,
}
.p(channel_id.to_string())
.await;
};
// First user who joined - send call started system message.
if event.room.as_ref().unwrap().num_participants == 1 {
let user = Reference::from_unchecked(user_id).as_user(db).await?;
let message_id =
Ulid::from_datetime(DateTime::from_timestamp_secs(event.created_at).unwrap())
.to_string();
let mut call_started_message = SystemMessage::CallStarted {
by: user_id.to_string(),
finished_at: None,
}
.into_message(channel.id().to_string());
call_started_message.id = message_id;
set_channel_call_started_system_message(channel.id(), &call_started_message.id)
.await?;
call_started_message
.send(
db,
Some(amqp),
v0::MessageAuthor::System {
username: &user.username,
avatar: user.avatar.as_ref().map(|file| file.id.as_ref()),
},
None,
None,
&channel,
false,
)
.await?;
let recipients = get_call_notification_recipients(&channel_id, &user_id).await?;
let now = joined_at.format_short().to_string();
if let Err(e) = amqp
.dm_call_updated(&user.id, channel.id(), Some(&now), false, recipients)
.await
{
revolt_config::capture_error(&e);
}
}
}
// User left a channel
"participant_left" => {
let channel_id = channel_id.to_internal_error()?;
let user_id = user_id.to_internal_error()?;
let channel = Reference::from_unchecked(channel_id).as_channel(db).await?;
delete_voice_state(channel_id, channel.server(), user_id).await?;
// Dont send leave event when a user is moved
if get_user_moved_from_voice(channel_id, user_id)
.await?
.is_none()
{
EventV1::VoiceChannelLeave {
id: channel_id.clone(),
user: user_id.clone(),
}
.p(channel_id.clone())
.await;
};
// Update CallStarted system message if everyone has left with the end time
let members = get_voice_channel_members(channel_id).await?;
if members.is_none_or(|m| m.is_empty()) {
// The channel is empty so send out an "end" message for ringing
if let Err(e) = amqp
.dm_call_updated(user_id, channel_id, None, true, None)
.await
{
revolt_config::capture_internal_error!(&e);
}
if let Some(system_message_id) =
take_channel_call_started_system_message(channel_id).await?
{
// Could have been deleted
if let Ok(mut message) = Reference::from_unchecked(&system_message_id)
.as_message(db)
.await
{
if let Some(SystemMessage::CallStarted { finished_at, .. }) =
&mut message.system
{
*finished_at = Some(Timestamp::now_utc());
message
.update(
db,
PartialMessage {
system: message.system.clone(),
..Default::default()
},
Vec::new(),
)
.await?;
} else {
log::error!("Broken State: Call started message ID ({}) does not contain a CallStarted system message.", &message.id)
}
};
};
}
}
// Audio/video track was started/stopped
"track_published" | "track_unpublished" => {
let channel_id = channel_id.to_internal_error()?;
let user_id = user_id.to_internal_error()?;
let track = event.track.as_ref().to_internal_error()?;
let channel = Reference::from_unchecked(channel_id).as_channel(db).await?;
let user = Reference::from_unchecked(user_id).as_user(db).await?;
let user_limits = user.limits().await;
// forbid any size which goes over the limit and also limit the aspect ratio to stop people from making too tall or too wide and bypassing the limit.
// TODO: figure out how to track audio stream quality
if event.event == "track_published"
&& (track.r#type == TrackType::Data as i32
|| (track.r#type == TrackType::Video as i32
&& (user_limits.video_resolution[0] != 0
&& user_limits.video_resolution[1] != 0
&& track.width * track.height
> user_limits.video_resolution[0]
* user_limits.video_resolution[1])
|| (user_limits.video_aspect_ratio[0]
!= user_limits.video_aspect_ratio[1]
&& !(user_limits.video_aspect_ratio[0]
..=user_limits.video_aspect_ratio[1])
.contains(&(track.width as f32 / track.height as f32)))))
{
voice_client.remove_user(node, user_id, channel_id).await?;
delete_voice_state(channel_id, channel.server(), user_id).await?;
} else {
let partial = update_voice_state_tracks(
channel_id,
channel.server(),
user_id,
event.event == "track_published", // to avoid duplicating this entire case twice
track.source,
)
.await?;
EventV1::UserVoiceStateUpdate {
id: user_id.clone(),
channel_id: channel_id.clone(),
data: partial,
}
.p(channel_id.clone())
.await;
}
}
_ => {}
};
Ok(EmptyResponse)
}

View File

@@ -1,28 +0,0 @@
use revolt_result::{create_error, Error};
use rocket::{
http::Status,
request::{FromRequest, Outcome},
Request,
};
pub struct AuthHeader<'a>(&'a str);
#[rocket::async_trait]
impl<'r> FromRequest<'r> for AuthHeader<'r> {
type Error = Error;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
match request.headers().get("Authorization").next() {
Some(token) => Outcome::Success(Self(token)),
None => Outcome::Error((Status::Unauthorized, create_error!(NotAuthenticated))),
}
}
}
impl std::ops::Deref for AuthHeader<'_> {
type Target = str;
fn deref(&self) -> &Self::Target {
self.0
}
}

View File

@@ -1,37 +0,0 @@
use std::env;
use revolt_database::DatabaseInfo;
use revolt_database::{voice::VoiceClient, AMQP};
use revolt_result::Result;
use rocket::{build, routes, Config};
use std::net::Ipv4Addr;
mod api;
mod guard;
#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
revolt_config::configure!(voice_ingress);
let amqp = AMQP::new_auto().await;
let database = DatabaseInfo::Auto.connect().await.unwrap();
let voice_client = VoiceClient::from_revolt_config().await;
let _rocket = build()
.manage(database)
.manage(voice_client)
.manage(amqp)
.mount("/", routes![api::ingress])
.configure(Config {
port: 8500,
address: Ipv4Addr::new(0, 0, 0, 0).into(),
..Default::default()
})
.ignite()
.await?
.launch()
.await?;
Ok(())
}

View File

@@ -83,9 +83,8 @@ revolt-result = { path = "../core/result", features = ["rocket", "okapi"] }
revolt-permissions = { path = "../core/permissions", features = ["schemas"] }
revolt-ratelimits = { path = "../core/ratelimits", features = ["rocket"] }
# voice
livekit-api = "0.4.4"
livekit-protocol = "0.4.0"
# oauth2
pkce = "0.2.0"
[build-dependencies]
vergen = "7.5.0"

View File

@@ -1,5 +1,5 @@
# Build Stage
FROM ghcr.io/revoltchat/base:latest AS builder
FROM ghcr.io/stoatchat/base:latest AS builder
FROM debian:12 AS debian
# Bundle Stage

View File

@@ -25,7 +25,6 @@ use amqprs::{
use async_std::channel::unbounded;
use authifier::AuthifierEvent;
use rocket::data::ToByteUnit;
use revolt_database::voice::VoiceClient;
pub async fn web() -> Rocket<Build> {
// Get settings
@@ -36,7 +35,6 @@ pub async fn web() -> Rocket<Build> {
// Setup database
let db = revolt_database::DatabaseInfo::Auto.connect().await.unwrap();
log::info!("database_here {db:?}");
db.migrate_database().await.unwrap();
// Setup Authifier event channel
@@ -92,16 +90,6 @@ pub async fn web() -> Rocket<Build> {
)
.into();
let swagger_0_8 = revolt_rocket_okapi::swagger_ui::make_swagger_ui(
&revolt_rocket_okapi::swagger_ui::SwaggerUIConfig {
url: "/0.8/openapi.json".to_owned(),
..Default::default()
},
)
.into();
// Voice handler
let voice_client = VoiceClient::new(config.api.livekit.nodes.clone());
// Configure Rabbit
let connection = Connection::open(&OpenConnectionArguments::new(
&config.rabbit.host,
@@ -149,7 +137,6 @@ pub async fn web() -> Rocket<Build> {
.manage(db)
.manage(amqp)
.manage(cors.clone())
.manage(voice_client)
.manage(ratelimits)
.attach(ratelimiter::RatelimitFairing)
.attach(cors)

View File

@@ -1,4 +1,4 @@
use revolt_database::{util::reference::Reference, voice::{delete_voice_state, get_channel_node, get_user_voice_channels, VoiceClient}, Database, User};
use revolt_database::{util::reference::Reference, Database, User};
use revolt_result::{create_error, Result};
use rocket::State;
use rocket_empty::EmptyResponse;
@@ -10,7 +10,6 @@ use rocket_empty::EmptyResponse;
#[delete("/<target>")]
pub async fn delete_bot(
db: &State<Database>,
voice_client: &State<VoiceClient>,
user: User,
target: Reference<'_>,
) -> Result<EmptyResponse> {
@@ -19,18 +18,7 @@ pub async fn delete_bot(
return Err(create_error!(NotFound));
}
bot.delete(db).await?;
for channel_id in get_user_voice_channels(&bot.id).await? {
let node = get_channel_node(&channel_id).await?.unwrap();
let channel = Reference::from_unchecked(&channel_id).as_channel(db).await?;
voice_client.remove_user(&node, &bot.id, &channel_id).await?;
delete_voice_state(&channel_id, channel.server(), &bot.id).await?;
}
Ok(EmptyResponse)
bot.delete(db).await.map(|_| EmptyResponse)
}
#[cfg(test)]

View File

@@ -37,6 +37,7 @@ pub async fn edit_bot(
if data.public.is_none()
&& data.analytics.is_none()
&& data.interactions_url.is_none()
&& data.oauth2.is_none()
&& data.remove.is_empty()
{
return Ok(Json(v0::BotWithUserResponse {
@@ -49,17 +50,43 @@ pub async fn edit_bot(
public,
analytics,
interactions_url,
oauth2,
remove,
..
} = data;
let partial = PartialBot {
let mut partial = PartialBot {
public,
analytics,
interactions_url,
..Default::default()
};
if let Some(edit_oauth2) = oauth2 {
let mut oauth2 = bot.oauth2.clone().unwrap_or_default();
if let Some(public) = edit_oauth2.public {
if oauth2.public && !public {
oauth2.secret = Some(nanoid::nanoid!(64))
} else if !oauth2.public && public {
oauth2.secret = None;
};
oauth2.public = public;
}
oauth2.redirects = edit_oauth2.redirects.unwrap_or(oauth2.redirects);
oauth2.allowed_scopes = edit_oauth2.allowed_scopes
.map(|scopes|scopes
.into_iter()
.map(|(scope, value)| (scope.into(), value.into()))
.collect()
)
.unwrap_or(oauth2.allowed_scopes);
partial.oauth2 = Some(oauth2)
}
bot.update(
db,
partial,

View File

@@ -1,8 +1,5 @@
use revolt_database::{
util::{permissions::DatabasePermissionQuery, reference::Reference},
voice::{
delete_channel_voice_state, delete_voice_state, get_channel_node, get_voice_channel_members, is_in_voice_channel, VoiceClient
},
Channel, Database, PartialChannel, User, AMQP,
};
use revolt_models::v0;
@@ -18,7 +15,6 @@ use rocket_empty::EmptyResponse;
#[delete("/<target>?<options..>")]
pub async fn delete(
db: &State<Database>,
voice_client: &State<VoiceClient>,
amqp: &State<AMQP>,
user: User,
target: Reference<'_>,
@@ -30,57 +26,34 @@ pub async fn delete(
permissions.throw_if_lacking_channel_permission(ChannelPermission::ViewChannel)?;
#[allow(deprecated)]
match &channel {
Channel::SavedMessages { .. } => Err(create_error!(NoEffect))?,
Channel::DirectMessage { .. } => {
channel
.update(
db,
PartialChannel {
active: Some(false),
..Default::default()
},
vec![],
)
.await?
}
Channel::Group { .. } => {
channel
.remove_user_from_group(
db,
amqp,
&user,
None,
options.leave_silently.unwrap_or_default(),
)
.await?;
if is_in_voice_channel(&user.id, channel.id()).await? {
let node = get_channel_node(channel.id()).await?.unwrap();
voice_client
.remove_user(&node, &user.id, channel.id())
.await?;
delete_voice_state(channel.id(), None, &user.id).await?;
};
}
Channel::TextChannel { .. } => {
Channel::SavedMessages { .. } => Err(create_error!(NoEffect)),
Channel::DirectMessage { .. } => channel
.update(
db,
PartialChannel {
active: Some(false),
..Default::default()
},
vec![],
)
.await
.map(|_| EmptyResponse),
Channel::Group { .. } => channel
.remove_user_from_group(
db,
amqp,
&user,
None,
options.leave_silently.unwrap_or_default(),
)
.await
.map(|_| EmptyResponse),
Channel::TextChannel { .. } | Channel::VoiceChannel { .. } => {
permissions.throw_if_lacking_channel_permission(ChannelPermission::ManageChannel)?;
channel.delete(db).await?;
if let Some(users) = get_voice_channel_members(channel.id()).await? {
let node = get_channel_node(channel.id()).await?.unwrap();
voice_client.delete_room(&node, channel.id()).await?;
delete_channel_voice_state(channel.id(), channel.server(), &users).await?;
};
channel.delete(db).await.map(|_| EmptyResponse)
}
};
Ok(EmptyResponse)
}
}
#[cfg(test)]

View File

@@ -1,5 +1,6 @@
use revolt_database::{
util::{permissions::DatabasePermissionQuery, reference::Reference}, voice::{delete_channel_voice_state, get_channel_node, get_voice_channel_members, VoiceClient}, Channel, Database, File, PartialChannel, SystemMessage, User, AMQP
util::{permissions::DatabasePermissionQuery, reference::Reference},
Channel, Database, File, PartialChannel, SystemMessage, User, AMQP,
};
use revolt_models::v0;
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
@@ -14,7 +15,6 @@ use validator::Validate;
#[patch("/<target>", data = "<data>")]
pub async fn edit(
db: &State<Database>,
voice_client: &State<VoiceClient>,
amqp: &State<AMQP>,
user: User,
target: Reference<'_>,
@@ -38,7 +38,6 @@ pub async fn edit(
&& data.icon.is_none()
&& data.nsfw.is_none()
&& data.owner.is_none()
&& data.voice.is_none()
&& data.remove.is_empty()
{
return Ok(Json(channel.into()));
@@ -96,6 +95,22 @@ pub async fn edit(
icon,
nsfw,
..
}
| Channel::TextChannel {
id,
name,
description,
icon,
nsfw,
..
}
| Channel::VoiceChannel {
id,
name,
description,
icon,
nsfw,
..
} => {
if data.remove.contains(&v0::FieldsChannel::Icon) {
if let Some(icon) = &icon {
@@ -136,139 +151,73 @@ pub async fn edit(
}
// Send out mutation system messages.
if let Some(name) = &partial.name {
SystemMessage::ChannelRenamed {
name: name.to_string(),
by: user.id.clone(),
}
.into_message(channel.id().to_string())
.send(
db,
Some(amqp),
user.as_author_for_system(),
None,
None,
&channel,
false,
)
.await
.ok();
}
if partial.description.is_some() {
SystemMessage::ChannelDescriptionChanged {
by: user.id.clone(),
}
.into_message(channel.id().to_string())
.send(
db,
Some(amqp),
user.as_author_for_system(),
None,
None,
&channel,
false,
)
.await
.ok();
}
if partial.icon.is_some() {
SystemMessage::ChannelIconChanged {
by: user.id.clone(),
}
.into_message(channel.id().to_string())
.send(
db,
Some(amqp),
user.as_author_for_system(),
None,
None,
&channel,
false,
)
.await
.ok();
}
}
Channel::TextChannel {
id,
name,
description,
icon,
nsfw,
voice,
..
} => {
if data.remove.contains(&v0::FieldsChannel::Icon) {
if let Some(icon) = &icon {
db.mark_attachment_as_deleted(&icon.id).await?;
}
}
for field in &data.remove {
match field {
v0::FieldsChannel::Description => {
description.take();
if let Channel::Group { .. } = &channel {
if let Some(name) = &partial.name {
SystemMessage::ChannelRenamed {
name: name.to_string(),
by: user.id.clone(),
}
v0::FieldsChannel::Icon => {
icon.take();
.into_message(channel.id().to_string())
.send(
db,
Some(amqp),
user.as_author_for_system(),
None,
None,
&channel,
false,
)
.await
.ok();
}
if partial.description.is_some() {
SystemMessage::ChannelDescriptionChanged {
by: user.id.clone(),
}
v0::FieldsChannel::Voice => {
voice.take();
.into_message(channel.id().to_string())
.send(
db,
Some(amqp),
user.as_author_for_system(),
None,
None,
&channel,
false,
)
.await
.ok();
}
if partial.icon.is_some() {
SystemMessage::ChannelIconChanged {
by: user.id.clone(),
}
_ => {}
.into_message(channel.id().to_string())
.send(
db,
Some(amqp),
user.as_author_for_system(),
None,
None,
&channel,
false,
)
.await
.ok();
}
}
if let Some(icon_id) = data.icon {
partial.icon = Some(File::use_channel_icon(db, &icon_id, id, &user.id).await?);
*icon = partial.icon.clone();
}
if let Some(new_name) = data.name {
*name = new_name.clone();
partial.name = Some(new_name);
}
if let Some(new_description) = data.description {
partial.description = Some(new_description);
*description = partial.description.clone();
}
if let Some(new_nsfw) = data.nsfw {
*nsfw = new_nsfw;
partial.nsfw = Some(new_nsfw);
}
if let Some(new_voice) = data.voice {
*voice = Some(new_voice.clone().into());
partial.voice = Some(new_voice.into());
}
channel
.update(
db,
partial,
data.remove.into_iter().map(|f| f.into()).collect(),
)
.await?;
}
_ => return Err(create_error!(InvalidOperation)),
};
channel
.update(
db,
partial,
data.remove
.into_iter()
.map(|f| f.into())
.collect(),
)
.await?;
if channel.voice().is_none() {
if let Some(users) = get_voice_channel_members(channel.id()).await? {
let node = get_channel_node(channel.id()).await?.unwrap();
voice_client.delete_room(&node, channel.id()).await?;
delete_channel_voice_state(channel.id(), channel.server(), &users).await?;
};
}
Ok(Json(channel.into()))
}

View File

@@ -1,4 +1,4 @@
use revolt_database::{util::reference::Reference, voice::{delete_voice_state, get_channel_node, is_in_voice_channel, VoiceClient}, Channel, Database, User, AMQP};
use revolt_database::{util::reference::Reference, Channel, Database, User, AMQP};
use revolt_permissions::ChannelPermission;
use revolt_result::{create_error, Result};
@@ -12,7 +12,6 @@ use rocket_empty::EmptyResponse;
#[delete("/<target>/recipients/<member>")]
pub async fn remove_member(
db: &State<Database>,
voice_client: &State<VoiceClient>,
amqp: &State<AMQP>,
user: User,
target: Reference<'_>,
@@ -24,37 +23,32 @@ pub async fn remove_member(
let channel = target.as_channel(db).await?;
if let Channel::Group { owner, recipients, .. } = &channel {
if &user.id != owner {
return Err(create_error!(MissingPermission {
permission: ChannelPermission::ManageChannel.to_string()
}));
match &channel {
Channel::Group {
owner, recipients, ..
} => {
if &user.id != owner {
return Err(create_error!(MissingPermission {
permission: ChannelPermission::ManageChannel.to_string()
}));
}
let member = member.as_user(db).await?;
if user.id == member.id {
return Err(create_error!(CannotRemoveYourself));
}
if !recipients.iter().any(|x| *x == member.id) {
return Err(create_error!(NotInGroup));
}
channel
.remove_user_from_group(db, amqp, &member, Some(&user.id), false)
.await
.map(|_| EmptyResponse)
}
let member = member.as_user(db).await?;
if user.id == member.id {
return Err(create_error!(CannotRemoveYourself));
}
if !recipients.contains(&member.id) {
return Err(create_error!(NotInGroup));
}
channel
.remove_user_from_group(db, amqp, &member, Some(&user.id), false)
.await?;
} else {
return Err(create_error!(InvalidOperation))
};
if is_in_voice_channel(&user.id, channel.id()).await? {
let node = get_channel_node(channel.id()).await?.unwrap();
voice_client.remove_user(&node, &user.id, channel.id()).await?;
delete_voice_state(channel.id(), None, &user.id).await?;
};
Ok(EmptyResponse)
_ => Err(create_error!(InvalidOperation)),
}
}
#[cfg(test)]

View File

@@ -1,6 +1,6 @@
use revolt_database::{
util::{permissions::DatabasePermissionQuery, reference::Reference},
Database, Message, MessageFilter, MessageQuery, MessageTimePeriod, User,
Channel, Database, Message, MessageFilter, MessageQuery, MessageTimePeriod, User,
};
use revolt_models::v0::{self, MessageSort};
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
@@ -65,7 +65,12 @@ pub async fn query(
},
&user,
include_users,
channel.server(),
match channel {
Channel::TextChannel { server, .. } | Channel::VoiceChannel { server, .. } => {
Some(server)
}
_ => None,
},
)
.await
.map(Json)

View File

@@ -1,6 +1,6 @@
use revolt_database::{
util::{permissions::DatabasePermissionQuery, reference::Reference},
Database, Message, MessageFilter, MessageQuery, MessageTimePeriod, User,
Channel, Database, Message, MessageFilter, MessageQuery, MessageTimePeriod, User,
};
use revolt_models::v0;
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
@@ -31,7 +31,7 @@ pub async fn search(
})?;
if options.query.is_some() && options.pinned.is_some() {
return Err(create_error!(InvalidOperation));
return Err(create_error!(InvalidOperation))
}
let channel = target.as_channel(db).await?;
@@ -69,7 +69,12 @@ pub async fn search(
},
&user,
include_users,
channel.server(),
match channel {
Channel::TextChannel { server, .. } | Channel::VoiceChannel { server, .. } => {
Some(server)
}
_ => None,
},
)
.await
.map(Json)

View File

@@ -151,7 +151,6 @@ mod test {
name: "Hidden Channel".to_string(),
description: None,
nsfw: Some(false),
voice: None
},
true,
)
@@ -194,7 +193,6 @@ mod test {
d: ChannelPermission::ViewChannel as i64,
}),
last_message_id: None,
voice: None,
};
locked_channel
.update(&harness.db, partial, vec![])
@@ -289,8 +287,6 @@ mod test {
avatar: None,
timeout: None,
roles: Some(second_member_roles),
can_publish: None,
can_receive: None
};
second_member
.update(&harness.db, partial, vec![])
@@ -617,8 +613,6 @@ mod test {
nickname: None,
roles: Some(vec![role_id.clone()]),
timeout: None,
can_publish: None,
can_receive: None
},
vec![],
)

Some files were not shown because too many files have changed in this diff Show More