mirror of
https://forgejo.ellis.link/continuwuation/continuwuity/
synced 2026-04-25 11:22:09 +00:00
Compare commits
221 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9fde835673 | ||
|
|
bf9d498621 | ||
|
|
f8cf57c1fb | ||
|
|
26a6d349dc | ||
|
|
77c0c13a83 | ||
|
|
36b8de1339 | ||
|
|
29a6065bae | ||
|
|
f4c8b77377 | ||
|
|
85400d15bc | ||
|
|
13334a88ca | ||
|
|
351062eb82 | ||
|
|
001523ec81 | ||
|
|
0a5f18ed83 | ||
|
|
16ce62302a | ||
|
|
0068624cd6 | ||
|
|
2837151dba | ||
|
|
3d8757c896 | ||
|
|
b175892178 | ||
|
|
d8a1996e24 | ||
|
|
a934a7f687 | ||
|
|
1638be0339 | ||
|
|
ea2343850f | ||
|
|
fcfb323cd5 | ||
|
|
84a8e36120 | ||
|
|
47f9c69eff | ||
|
|
73af171830 | ||
|
|
9654dd9218 | ||
|
|
dea5fee6a3 | ||
|
|
4d42a29c51 | ||
|
|
7b0e830f4c | ||
|
|
e7b2c14280 | ||
|
|
bb5f2556c3 | ||
|
|
f047675a63 | ||
|
|
f4db6292b3 | ||
|
|
fcb9d04d9e | ||
|
|
ffc41cb01f | ||
|
|
e4bcbb8088 | ||
|
|
e4ba34a638 | ||
|
|
d5e7befaa9 | ||
|
|
1157140657 | ||
|
|
fb49e37067 | ||
|
|
8923c9a227 | ||
|
|
2b7e0dcb80 | ||
|
|
e790785db8 | ||
|
|
6b65a8fc86 | ||
|
|
a79ae7d1a2 | ||
|
|
156199a218 | ||
|
|
c16e5b50eb | ||
|
|
47ca835c20 | ||
|
|
dc3d9ebbf1 | ||
|
|
c1bcdeaf01 | ||
|
|
08efebd5af | ||
|
|
ddacda9ecf | ||
|
|
1e4b1e516e | ||
|
|
fadb2de5bf | ||
|
|
edd42974e5 | ||
|
|
e0fd84149d | ||
|
|
23690fd837 | ||
|
|
867050df9e | ||
|
|
50e66a2976 | ||
|
|
4d0fc41222 | ||
|
|
152ae705a0 | ||
|
|
54e6a41404 | ||
|
|
c3f00f4d15 | ||
|
|
43300ea41e | ||
|
|
17a54bc4f8 | ||
|
|
f540bed61e | ||
|
|
2cf472a69b | ||
|
|
b2d8da489c | ||
|
|
025afb61cb | ||
|
|
40d53563fc | ||
|
|
5db816277b | ||
|
|
efa70b9e78 | ||
|
|
bac795de5f | ||
|
|
f69f4c479c | ||
|
|
992f725362 | ||
|
|
0e56d1c7a2 | ||
|
|
b4d5282123 | ||
|
|
15ad7523aa | ||
|
|
eb6e509ad8 | ||
|
|
4432c06c86 | ||
|
|
bc5ecb0c72 | ||
|
|
f1b41ce6e3 | ||
|
|
826b1d1d62 | ||
|
|
c40ed0c98e | ||
|
|
2d9aab2e79 | ||
|
|
66679c7522 | ||
|
|
a2afdbe1fa | ||
|
|
f86ab0cd03 | ||
|
|
7b8ef3b070 | ||
|
|
83ef4eecc7 | ||
|
|
52ccad04a6 | ||
|
|
8fe19a6ef0 | ||
|
|
fd96f597cd | ||
|
|
982f9eb780 | ||
|
|
aeb6fbe70f | ||
|
|
d264935625 | ||
|
|
28cd784972 | ||
|
|
6662aa21ef | ||
|
|
9b9a91f6ef | ||
|
|
94b805de0b | ||
|
|
eded585f79 | ||
|
|
a552321287 | ||
|
|
f98bfbbdcd | ||
|
|
e9ab548445 | ||
|
|
15184d1a79 | ||
|
|
0c6bbde25f | ||
|
|
13aa353765 | ||
|
|
ac941a801a | ||
|
|
f261d44edb | ||
|
|
849cfdcdfa | ||
|
|
1470331f7e | ||
|
|
dcaa96a79f | ||
|
|
101a966922 | ||
|
|
57940f38ea | ||
|
|
22f8c339fc | ||
|
|
c896acb729 | ||
|
|
7f1bc490d6 | ||
|
|
1091c30845 | ||
|
|
12d9e454db | ||
|
|
82b973a8b1 | ||
|
|
71ee31a014 | ||
|
|
69b4ec81b6 | ||
|
|
fe0969e7ca | ||
|
|
2e3e14b045 | ||
|
|
f51d4237c7 | ||
|
|
d8a87258d6 | ||
|
|
3da2242730 | ||
|
|
5add9a8c34 | ||
|
|
5b1642f641 | ||
|
|
eb94aa7079 | ||
|
|
24884c3b9b | ||
|
|
a0a002b17f | ||
|
|
f632b06e6d | ||
|
|
1f88866612 | ||
|
|
ccef1a4c8b | ||
|
|
5c258f41c8 | ||
|
|
15126ee1b2 | ||
|
|
e37ac56dba | ||
|
|
a74613be96 | ||
|
|
a95ded167f | ||
|
|
95121b6e05 | ||
|
|
e6884ef13a | ||
|
|
49033db2b8 | ||
|
|
ddc8c3b46c | ||
|
|
ea95627dce | ||
|
|
c3e751542d | ||
|
|
4b765aa17c | ||
|
|
954cfc6bb7 | ||
|
|
2f85a5c1ac | ||
|
|
7e50db4193 | ||
|
|
7a3cc3941e | ||
|
|
ca82b59c6f | ||
|
|
3b5607ecdc | ||
|
|
96f6a75bc8 | ||
|
|
68f42baf73 | ||
|
|
271959ee27 | ||
|
|
c423a83656 | ||
|
|
4e975887cf | ||
|
|
8bb69eb81d | ||
|
|
2100618d47 | ||
|
|
936d2915e2 | ||
|
|
f014231644 | ||
|
|
7d487d53d8 | ||
|
|
d7d874f88d | ||
|
|
ee864bcd9e | ||
|
|
111cbea6fc | ||
|
|
85f734ec74 | ||
|
|
2468e0c3de | ||
|
|
f841c2356d | ||
|
|
c64adbec0e | ||
|
|
4458efa2b2 | ||
|
|
5c0bf29122 | ||
|
|
91b49a7786 | ||
|
|
5a17fbccf5 | ||
|
|
5ed95ea357 | ||
|
|
ccfa939bd3 | ||
|
|
263e338088 | ||
|
|
2fb43dd38d | ||
|
|
59efabbbc2 | ||
|
|
010e4ee35a | ||
|
|
992c0a1e58 | ||
|
|
9b20c6918f | ||
|
|
3dc91525ce | ||
|
|
a88f913a17 | ||
|
|
4343218957 | ||
|
|
b116984e46 | ||
|
|
b0ac5255c8 | ||
|
|
29fc5b9b52 | ||
|
|
3ccd9ea326 | ||
|
|
8a2ae401df | ||
|
|
f465d77ad3 | ||
|
|
2fd6f6b0ff | ||
|
|
8b6018d77d | ||
|
|
463f1a1287 | ||
|
|
04fc87ad07 | ||
|
|
dc573f4562 | ||
|
|
74826dcb94 | ||
|
|
b20c4e0539 | ||
|
|
fb8a2846df | ||
|
|
04971d0430 | ||
|
|
f098532b09 | ||
|
|
60927c1c72 | ||
|
|
03296412ab | ||
|
|
934ab6a4fe | ||
|
|
1378399f9d | ||
|
|
09680f653f | ||
|
|
39f19c483a | ||
|
|
39c0f4ea3d | ||
|
|
405167fc3f | ||
|
|
b13ea4ff45 | ||
|
|
100fc5e0f7 | ||
|
|
96f9d64111 | ||
|
|
30ad5da5f1 | ||
|
|
ce0ca96df4 | ||
|
|
4851ad26e2 | ||
|
|
328759a60f | ||
|
|
463fa4fd53 | ||
|
|
db494e0d68 | ||
|
|
4788040458 | ||
|
|
06531993f6 |
@@ -18,3 +18,6 @@ max_line_length = 80
|
||||
|
||||
[*.nix]
|
||||
indent_size = 2
|
||||
|
||||
[*.rs]
|
||||
indent_style = tab
|
||||
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Sync repository
|
||||
uses: https://github.com/https://github.com/actions/checkout@v4
|
||||
uses: https://github.com/actions/checkout@v4
|
||||
|
||||
- name: Tag comparison check
|
||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||
|
||||
259
.github/workflows/ci.yml
vendored
259
.github/workflows/ci.yml
vendored
@@ -27,6 +27,16 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
# sccache only on main repo
|
||||
SCCACHE_GHA_ENABLED: "${{ (github.event.pull_request.draft != true) && (vars.DOCKER_USERNAME != '') && (vars.GITLAB_USERNAME != '') && (vars.SCCACHE_ENDPOINT != '') && (github.event.pull_request.user.login != 'renovate[bot]') && 'true' || 'false' }}"
|
||||
RUSTC_WRAPPER: "${{ (github.event.pull_request.draft != true) && (vars.DOCKER_USERNAME != '') && (vars.GITLAB_USERNAME != '') && (vars.SCCACHE_ENDPOINT != '') && (github.event.pull_request.user.login != 'renovate[bot]') && 'sccache' || '' }}"
|
||||
SCCACHE_BUCKET: "${{ (github.event.pull_request.draft != true) && (vars.DOCKER_USERNAME != '') && (vars.GITLAB_USERNAME != '') && (vars.SCCACHE_ENDPOINT != '') && (github.event.pull_request.user.login != 'renovate[bot]') && 'sccache' || '' }}"
|
||||
SCCACHE_S3_USE_SSL: ${{ vars.SCCACHE_S3_USE_SSL }}
|
||||
SCCACHE_REGION: ${{ vars.SCCACHE_REGION }}
|
||||
SCCACHE_ENDPOINT: ${{ vars.SCCACHE_ENDPOINT }}
|
||||
SCCACHE_CACHE_MULTIARCH: ${{ vars.SCCACHE_CACHE_MULTIARCH }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
# Required to make some things output color
|
||||
TERM: ansi
|
||||
# Publishing to my nix binary cache
|
||||
@@ -43,6 +53,8 @@ env:
|
||||
show-trace = true
|
||||
extra-substituters = https://attic.kennel.juneis.dog/conduit https://attic.kennel.juneis.dog/conduwuit https://cache.lix.systems https://conduwuit.cachix.org
|
||||
extra-trusted-public-keys = conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk= conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE= cache.lix.systems:aBnZUw8zA7H35Cz2RyKFVs3H4PlGTLawyY5KRbvJR8o= conduwuit.cachix.org-1:MFRm6jcnfTf0jSAbmvLfhO3KBMt4px+1xaereWXp8Xg=
|
||||
# complement uses libolm
|
||||
NIXPKGS_ALLOW_INSECURE: 1
|
||||
|
||||
permissions:
|
||||
packages: write
|
||||
@@ -52,6 +64,8 @@ jobs:
|
||||
tests:
|
||||
name: Test
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
CARGO_PROFILE: "test"
|
||||
steps:
|
||||
- name: Free Disk Space (Ubuntu)
|
||||
uses: jlumbroso/free-disk-space@main
|
||||
@@ -118,15 +132,39 @@ jobs:
|
||||
- name: Prepare build environment
|
||||
run: |
|
||||
echo 'source $HOME/.nix-profile/share/nix-direnv/direnvrc' > "$HOME/.direnvrc"
|
||||
nix profile install --inputs-from . nixpkgs#direnv nixpkgs#nix-direnv
|
||||
nix profile install --impure --inputs-from . nixpkgs#direnv nixpkgs#nix-direnv
|
||||
direnv allow
|
||||
nix develop .#all-features --command true
|
||||
nix develop .#all-features --command true --impure
|
||||
|
||||
- name: Cache CI dependencies
|
||||
run: |
|
||||
bin/nix-build-and-cache ci
|
||||
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||
ATTEMPTS=3
|
||||
SUCCESS=false
|
||||
while (( ATTEMPTS-- > 0 ))
|
||||
do
|
||||
bin/nix-build-and-cache ci
|
||||
if [[ $? == 0 ]]; then
|
||||
SUCCESS=true
|
||||
break
|
||||
else
|
||||
sleep 3
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $SUCCESS == "false" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# use sccache for Rust
|
||||
- name: Run sccache-cache
|
||||
if: (github.event.pull_request.draft != true) && (vars.DOCKER_USERNAME != '') && (vars.GITLAB_USERNAME != '') && (vars.SCCACHE_ENDPOINT != '') && (github.event.pull_request.user.login != 'renovate[bot]')
|
||||
uses: mozilla-actions/sccache-action@main
|
||||
|
||||
# use rust-cache
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
cache-all-crates: "true"
|
||||
|
||||
- name: Run CI tests
|
||||
run: |
|
||||
@@ -180,6 +218,10 @@ jobs:
|
||||
echo '```' >> $GITHUB_STEP_SUMMARY
|
||||
fi
|
||||
|
||||
- name: Run cargo clean test artifacts
|
||||
run: |
|
||||
cargo clean --profile test
|
||||
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
@@ -190,6 +232,9 @@ jobs:
|
||||
- target: aarch64-unknown-linux-musl
|
||||
- target: x86_64-unknown-linux-musl
|
||||
steps:
|
||||
- name: Free Disk Space (Ubuntu)
|
||||
uses: jlumbroso/free-disk-space@main
|
||||
|
||||
- name: Sync repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
@@ -240,16 +285,43 @@ jobs:
|
||||
- name: Prepare build environment
|
||||
run: |
|
||||
echo 'source $HOME/.nix-profile/share/nix-direnv/direnvrc' > "$HOME/.direnvrc"
|
||||
nix profile install --inputs-from . nixpkgs#direnv nixpkgs#nix-direnv
|
||||
nix profile install --impure --inputs-from . nixpkgs#direnv nixpkgs#nix-direnv
|
||||
direnv allow
|
||||
nix develop .#all-features --command true
|
||||
nix develop .#all-features --command true --impure
|
||||
|
||||
# use sccache for Rust
|
||||
- name: Run sccache-cache
|
||||
if: (github.event.pull_request.draft != true) && (vars.DOCKER_USERNAME != '') && (vars.GITLAB_USERNAME != '') && (vars.SCCACHE_ENDPOINT != '') && (github.event.pull_request.user.login != 'renovate[bot]')
|
||||
uses: mozilla-actions/sccache-action@main
|
||||
|
||||
# use rust-cache
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
cache-all-crates: "true"
|
||||
|
||||
- name: Build static ${{ matrix.target }}
|
||||
run: |
|
||||
CARGO_DEB_TARGET_TUPLE=$(echo ${{ matrix.target }} | grep -o -E '^([^-]*-){3}[^-]*')
|
||||
SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)
|
||||
|
||||
bin/nix-build-and-cache just .#static-${{ matrix.target }}-all-features
|
||||
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||
ATTEMPTS=3
|
||||
SUCCESS=false
|
||||
while (( ATTEMPTS-- > 0 ))
|
||||
do
|
||||
bin/nix-build-and-cache just .#static-${{ matrix.target }}-all-features
|
||||
if [[ $? == 0 ]]; then
|
||||
SUCCESS=true
|
||||
break
|
||||
else
|
||||
sleep 3
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $SUCCESS == "false" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -v -p target/release/
|
||||
mkdir -v -p target/$CARGO_DEB_TARGET_TUPLE/release/
|
||||
cp -v -f result/bin/conduit target/release/conduwuit
|
||||
@@ -259,6 +331,66 @@ jobs:
|
||||
mv -v target/release/conduwuit static-${{ matrix.target }}
|
||||
mv -v target/release/${{ matrix.target }}.deb ${{ matrix.target }}.deb
|
||||
|
||||
# quick smoke test of the x86_64 static release binary
|
||||
- name: Run x86_64 static release binary
|
||||
run: |
|
||||
# GH actions default runners are x86_64 only
|
||||
if file result/bin/conduit | grep x86-64; then
|
||||
result/bin/conduit --version
|
||||
fi
|
||||
|
||||
- name: Build static debug ${{ matrix.target }}
|
||||
run: |
|
||||
CARGO_DEB_TARGET_TUPLE=$(echo ${{ matrix.target }} | grep -o -E '^([^-]*-){3}[^-]*')
|
||||
SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)
|
||||
|
||||
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||
ATTEMPTS=3
|
||||
SUCCESS=false
|
||||
while (( ATTEMPTS-- > 0 ))
|
||||
do
|
||||
bin/nix-build-and-cache just .#static-${{ matrix.target }}-all-features-debug
|
||||
if [[ $? == 0 ]]; then
|
||||
SUCCESS=true
|
||||
break
|
||||
else
|
||||
sleep 3
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $SUCCESS == "false" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# > warning: dev profile is not supported and will be a hard error in the future. cargo-deb is for making releases, and it doesn't make sense to use it with dev profiles.
|
||||
# so we need to coerce cargo-deb into thinking this is a release binary
|
||||
mkdir -v -p target/release/
|
||||
mkdir -v -p target/$CARGO_DEB_TARGET_TUPLE/release/
|
||||
cp -v -f result/bin/conduit target/release/conduwuit
|
||||
cp -v -f result/bin/conduit target/$CARGO_DEB_TARGET_TUPLE/release/conduwuit
|
||||
# -p conduit is the main crate name
|
||||
direnv exec . cargo deb --verbose --no-build --no-strip -p conduit --target=$CARGO_DEB_TARGET_TUPLE --output target/release/${{ matrix.target }}-debug.deb
|
||||
mv -v target/release/conduwuit static-${{ matrix.target }}-debug
|
||||
mv -v target/release/${{ matrix.target }}-debug.deb ${{ matrix.target }}-debug.deb
|
||||
|
||||
# quick smoke test of the x86_64 static debug binary
|
||||
- name: Run x86_64 static debug binary
|
||||
run: |
|
||||
# GH actions default runners are x86_64 only
|
||||
if file result/bin/conduit | grep x86-64; then
|
||||
result/bin/conduit --version
|
||||
fi
|
||||
|
||||
# check validity of produced deb package, invalid debs will error on these commands
|
||||
- name: Validate produced deb package
|
||||
run: |
|
||||
# List contents
|
||||
dpkg-deb --contents ${{ matrix.target }}.deb
|
||||
dpkg-deb --contents ${{ matrix.target }}-debug.deb
|
||||
# List info
|
||||
dpkg-deb --info ${{ matrix.target }}.deb
|
||||
dpkg-deb --info ${{ matrix.target }}-debug.deb
|
||||
|
||||
- name: Upload static-${{ matrix.target }}
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
@@ -274,11 +406,65 @@ jobs:
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
|
||||
- name: Upload static-${{ matrix.target }}-debug
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: static-${{ matrix.target }}-debug
|
||||
path: static-${{ matrix.target }}-debug
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload deb ${{ matrix.target }}-debug
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: deb-${{ matrix.target }}-debug
|
||||
path: ${{ matrix.target }}-debug.deb
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
|
||||
- name: Build OCI image ${{ matrix.target }}
|
||||
run: |
|
||||
bin/nix-build-and-cache just .#oci-image-${{ matrix.target }}-all-features
|
||||
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||
ATTEMPTS=3
|
||||
SUCCESS=false
|
||||
while (( ATTEMPTS-- > 0 ))
|
||||
do
|
||||
bin/nix-build-and-cache just .#oci-image-${{ matrix.target }}-all-features
|
||||
if [[ $? == 0 ]]; then
|
||||
SUCCESS=true
|
||||
break
|
||||
else
|
||||
sleep 3
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $SUCCESS == "false" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cp -v -f result oci-image-${{ matrix.target }}.tar.gz
|
||||
|
||||
- name: Build debug OCI image ${{ matrix.target }}
|
||||
run: |
|
||||
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||
ATTEMPTS=3
|
||||
SUCCESS=false
|
||||
while (( ATTEMPTS-- > 0 ))
|
||||
do
|
||||
bin/nix-build-and-cache just .#oci-image-${{ matrix.target }}-all-features-debug
|
||||
if [[ $? == 0 ]]; then
|
||||
SUCCESS=true
|
||||
break
|
||||
else
|
||||
sleep 3
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $SUCCESS == "false" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cp -v -f result oci-image-${{ matrix.target }}-debug.tar.gz
|
||||
|
||||
- name: Upload OCI image ${{ matrix.target }}
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
@@ -287,6 +473,14 @@ jobs:
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
|
||||
- name: Upload OCI image ${{ matrix.target }}-debug
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: oci-image-${{ matrix.target }}-debug
|
||||
path: oci-image-${{ matrix.target }}-debug.tar.gz
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
|
||||
docker:
|
||||
name: Docker publish
|
||||
runs-on: ubuntu-latest
|
||||
@@ -337,8 +531,10 @@ jobs:
|
||||
|
||||
- name: Move OCI images into position
|
||||
run: |
|
||||
mv -v oci-image-x86_64-*/*.tar.gz oci-image-amd64.tar.gz
|
||||
mv -v oci-image-aarch64-*/*.tar.gz oci-image-arm64v8.tar.gz
|
||||
mv -v oci-image-x86_64-unknown-linux-musl/*.tar.gz oci-image-amd64.tar.gz
|
||||
mv -v oci-image-aarch64-unknown-linux-musl/*.tar.gz oci-image-arm64v8.tar.gz
|
||||
mv -v oci-image-x86_64-unknown-linux-musl-debug/*.tar.gz oci-image-amd64-debug.tar.gz
|
||||
mv -v oci-image-aarch64-unknown-linux-musl-debug/*.tar.gz oci-image-arm64v8-debug.tar.gz
|
||||
|
||||
- name: Load and push amd64 image
|
||||
if: ${{ (vars.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
|
||||
@@ -362,6 +558,28 @@ jobs:
|
||||
docker push ${{ env.GHCR_ARM64 }}
|
||||
docker push ${{ env.GLCR_ARM64 }}
|
||||
|
||||
- name: Load and push amd64 debug image
|
||||
if: ${{ (vars.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
|
||||
run: |
|
||||
docker load -i oci-image-amd64-debug.tar.gz
|
||||
docker tag $(docker images -q conduit:main) ${{ env.DOCKER_AMD64 }}-debug
|
||||
docker tag $(docker images -q conduit:main) ${{ env.GHCR_AMD64 }}-debug
|
||||
docker tag $(docker images -q conduit:main) ${{ env.GLCR_AMD64 }}-debug
|
||||
docker push ${{ env.DOCKER_AMD64 }}-debug
|
||||
docker push ${{ env.GHCR_AMD64 }}-debug
|
||||
docker push ${{ env.GLCR_AMD64 }}-debug
|
||||
|
||||
- name: Load and push arm64 debug image
|
||||
if: ${{ (vars.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
|
||||
run: |
|
||||
docker load -i oci-image-arm64v8-debug.tar.gz
|
||||
docker tag $(docker images -q conduit:main) ${{ env.DOCKER_ARM64 }}-debug
|
||||
docker tag $(docker images -q conduit:main) ${{ env.GHCR_ARM64 }}-debug
|
||||
docker tag $(docker images -q conduit:main) ${{ env.GLCR_ARM64 }}-debug
|
||||
docker push ${{ env.DOCKER_ARM64 }}-debug
|
||||
docker push ${{ env.GHCR_ARM64 }}-debug
|
||||
docker push ${{ env.GLCR_ARM64 }}-debug
|
||||
|
||||
- name: Create Docker combined manifests
|
||||
run: |
|
||||
# Dockerhub Container Registry
|
||||
@@ -371,9 +589,21 @@ jobs:
|
||||
docker manifest create ${{ env.GHCR_TAG }} --amend ${{ env.GHCR_ARM64 }} --amend ${{ env.GHCR_AMD64 }}
|
||||
docker manifest create ${{ env.GHCR_BRANCH }} --amend ${{ env.GHCR_ARM64 }} --amend ${{ env.GHCR_AMD64 }}
|
||||
# GitLab Container Registry
|
||||
docker manifest create ${{ env.GLCR_TAG }} --amend ${{ env.GLCR_ARM64 }} --amend ${{ env.GCCR_AMD64 }}
|
||||
docker manifest create ${{ env.GLCR_TAG }} --amend ${{ env.GLCR_ARM64 }} --amend ${{ env.GLCR_AMD64 }}
|
||||
docker manifest create ${{ env.GLCR_BRANCH }} --amend ${{ env.GLCR_ARM64 }} --amend ${{ env.GLCR_AMD64 }}
|
||||
|
||||
- name: Create Docker combined debug manifests
|
||||
run: |
|
||||
# Dockerhub Container Registry
|
||||
docker manifest create ${{ env.DOCKER_TAG }}-debug --amend ${{ env.DOCKER_ARM64 }}-debug --amend ${{ env.DOCKER_AMD64 }}-debug
|
||||
docker manifest create ${{ env.DOCKER_BRANCH }}-debug --amend ${{ env.DOCKER_ARM64 }}-debug --amend ${{ env.DOCKER_AMD64 }}-debug
|
||||
# GitHub Container Registry
|
||||
docker manifest create ${{ env.GHCR_TAG }}-debug --amend ${{ env.GHCR_ARM64 }}-debug --amend ${{ env.GHCR_AMD64 }}-debug
|
||||
docker manifest create ${{ env.GHCR_BRANCH }}-debug --amend ${{ env.GHCR_ARM64 }}-debug --amend ${{ env.GHCR_AMD64 }}-debug
|
||||
# GitLab Container Registry
|
||||
docker manifest create ${{ env.GLCR_TAG }}-debug --amend ${{ env.GLCR_ARM64 }}-debug --amend ${{ env.GLCR_AMD64 }}-debug
|
||||
docker manifest create ${{ env.GLCR_BRANCH }}-debug --amend ${{ env.GLCR_ARM64 }}-debug --amend ${{ env.GLCR_AMD64 }}-debug
|
||||
|
||||
- name: Push manifests to Docker registries
|
||||
if: ${{ (vars.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
|
||||
run: |
|
||||
@@ -383,6 +613,12 @@ jobs:
|
||||
docker manifest push ${{ env.GHCR_BRANCH }}
|
||||
docker manifest push ${{ env.GLCR_TAG }}
|
||||
docker manifest push ${{ env.GLCR_BRANCH }}
|
||||
docker manifest push ${{ env.DOCKER_TAG }}-debug
|
||||
docker manifest push ${{ env.DOCKER_BRANCH }}-debug
|
||||
docker manifest push ${{ env.GHCR_TAG }}-debug
|
||||
docker manifest push ${{ env.GHCR_BRANCH }}-debug
|
||||
docker manifest push ${{ env.GLCR_TAG }}-debug
|
||||
docker manifest push ${{ env.GLCR_BRANCH }}-debug
|
||||
|
||||
- name: Add Image Links to Job Summary
|
||||
if: ${{ (vars.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
|
||||
@@ -390,3 +626,6 @@ jobs:
|
||||
echo "- \`docker pull ${{ env.DOCKER_TAG }}\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- \`docker pull ${{ env.GHCR_TAG }}\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- \`docker pull ${{ env.GLCR_TAG }}\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- \`docker pull ${{ env.DOCKER_TAG }}-debug\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- \`docker pull ${{ env.GHCR_TAG }}-debug\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- \`docker pull ${{ env.GLCR_TAG }}-debug\`" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
43
.github/workflows/documentation.yml
vendored
43
.github/workflows/documentation.yml
vendored
@@ -47,6 +47,9 @@ jobs:
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
|
||||
steps:
|
||||
- name: Free Disk Space (Ubuntu)
|
||||
uses: jlumbroso/free-disk-space@main
|
||||
|
||||
- name: Sync repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
@@ -107,7 +110,23 @@ jobs:
|
||||
|
||||
- name: Cache CI dependencies
|
||||
run: |
|
||||
bin/nix-build-and-cache ci
|
||||
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||
ATTEMPTS=3
|
||||
SUCCESS=false
|
||||
while (( ATTEMPTS-- > 0 ))
|
||||
do
|
||||
bin/nix-build-and-cache ci
|
||||
if [[ $? == 0 ]]; then
|
||||
SUCCESS=true
|
||||
break
|
||||
else
|
||||
sleep 3
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $SUCCESS == "false" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Run lychee and markdownlint
|
||||
run: |
|
||||
@@ -116,8 +135,26 @@ jobs:
|
||||
|
||||
- name: Build documentation (book)
|
||||
run: |
|
||||
./bin/nix-build-and-cache just .#book
|
||||
cp -r --dereference result public
|
||||
# attic nix binary cache server is very, very terribly flakey. nothing i can do to fix it other than retry multiple times here
|
||||
ATTEMPTS=3
|
||||
SUCCESS=false
|
||||
while (( ATTEMPTS-- > 0 ))
|
||||
do
|
||||
bin/nix-build-and-cache just .#book
|
||||
if [[ $? == 0 ]]; then
|
||||
SUCCESS=true
|
||||
break
|
||||
else
|
||||
sleep 3
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $SUCCESS == "false" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cp -r --dereference result public
|
||||
|
||||
- name: Upload generated documentation (book) as normal artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
|
||||
@@ -1,29 +1,46 @@
|
||||
# Contributing guide
|
||||
|
||||
This page is for about contributing to conduwuit. The [development](development.md) page may be of interest for you as well.
|
||||
This page is for about contributing to conduwuit. The
|
||||
[development](development.md) page may be of interest for you as well.
|
||||
|
||||
If you would like to work on an [issue][issues] that is not assigned, preferably ask in the Matrix room first at [#conduwuit:puppygock.gay][conduwuit-matrix], and comment on it.
|
||||
If you would like to work on an [issue][issues] that is not assigned, preferably
|
||||
ask in the Matrix room first at [#conduwuit:puppygock.gay][conduwuit-matrix],
|
||||
and comment on it.
|
||||
|
||||
### Linting and Formatting
|
||||
|
||||
It is mandatory all your changes satisfy the lints (clippy, rustc, rustdoc, etc) and your code is formatted via the **nightly** `cargo fmt`. A lot of the `rustfmt.toml` features depend on nightly toolchain. It would be ideal if they weren't nightly-exclusive features, but they currently still are. CI's rustfmt uses nightly.
|
||||
It is mandatory all your changes satisfy the lints (clippy, rustc, rustdoc, etc)
|
||||
and your code is formatted via the **nightly** `cargo fmt`. A lot of the
|
||||
`rustfmt.toml` features depend on nightly toolchain. It would be ideal if they
|
||||
weren't nightly-exclusive features, but they currently still are. CI's rustfmt
|
||||
uses nightly.
|
||||
|
||||
If you need to allow a lint, please make sure it's either obvious as to why (e.g. clippy saying redundant clone but it's actually required) or it has a comment saying why. Do not write inefficient code for the sake of satisfying lints. If a lint is wrong and provides a more inefficient solution or suggestion, allow the lint and mention that in a comment.
|
||||
If you need to allow a lint, please make sure it's either obvious as to why
|
||||
(e.g. clippy saying redundant clone but it's actually required) or it has a
|
||||
comment saying why. Do not write inefficient code for the sake of satisfying
|
||||
lints. If a lint is wrong and provides a more inefficient solution or
|
||||
suggestion, allow the lint and mention that in a comment.
|
||||
|
||||
### Running CI tests locally
|
||||
|
||||
conduwuit's CI for tests, linting, formatting, audit, etc use [`engage`][engage]. engage can be installed from nixpkgs or `cargo install engage`. conduwuit's Nix flake devshell has the nixpkgs engage with `direnv`. Use `engage --help` for more usage details.
|
||||
conduwuit's CI for tests, linting, formatting, audit, etc use
|
||||
[`engage`][engage]. engage can be installed from nixpkgs or `cargo install
|
||||
engage`. conduwuit's Nix flake devshell has the nixpkgs engage with `direnv`.
|
||||
Use `engage --help` for more usage details.
|
||||
|
||||
To test, format, lint, etc that CI would do, install engage, allow the `.envrc` file using `direnv allow`, and run `engage`.
|
||||
To test, format, lint, etc that CI would do, install engage, allow the `.envrc`
|
||||
file using `direnv allow`, and run `engage`.
|
||||
|
||||
All of the tasks are defined at the [engage.toml][engage.toml] file. You can view all of them neatly by running `engage list`
|
||||
All of the tasks are defined at the [engage.toml][engage.toml] file. You can
|
||||
view all of them neatly by running `engage list`
|
||||
|
||||
If you would like to run only a specific engage task group, use `just`:
|
||||
|
||||
- `engage just <group>`
|
||||
- Example: `engage just lints`
|
||||
|
||||
If you would like to run a specific engage task in a specific group, use `just <GROUP> [TASK]`: `engage just lints cargo-fmt`
|
||||
If you would like to run a specific engage task in a specific group, use `just
|
||||
<GROUP> [TASK]`: `engage just lints cargo-fmt`
|
||||
|
||||
The following binaries are used in [`engage.toml`][engage.toml]:
|
||||
|
||||
@@ -39,46 +56,79 @@ ### Running CI tests locally
|
||||
- [`cargo-deb`][cargo-deb]
|
||||
- [`lychee`][lychee]
|
||||
- [`markdownlint-cli`][markdownlint-cli]
|
||||
- `dpkg`
|
||||
|
||||
### Matrix tests
|
||||
|
||||
CI runs [Complement][complement], but currently does not fail if results from the checked-in results differ with the new results. If your changes are done to fix Matrix tests, note that in your pull request. If more Complement tests start failing from your changes, please review the logs (they are uploaded as artifacts) and determine if they're intended or not.
|
||||
CI runs [Complement][complement], but currently does not fail if results from
|
||||
the checked-in results differ with the new results. If your changes are done to
|
||||
fix Matrix tests, note that in your pull request. If more Complement tests start
|
||||
failing from your changes, please review the logs (they are uploaded as
|
||||
artifacts) and determine if they're intended or not.
|
||||
|
||||
If you'd like to run Complement locally using Nix, see the [testing](docs/development/testing.md) page.
|
||||
If you'd like to run Complement locally using Nix, see the
|
||||
[testing](docs/development/testing.md) page.
|
||||
|
||||
[Sytest][sytest] support will come soon.
|
||||
|
||||
### Writing documentation
|
||||
|
||||
conduwuit's website uses [`mdbook`][mdbook] and deployed via CI using GitHub Pages in the [`documentation.yml`][documentation.yml] workflow file with Nix's mdbook in the devshell. All documentation is in the `docs/` directory at the top level. The compiled mdbook website is also uploaded as an artifact.
|
||||
conduwuit's website uses [`mdbook`][mdbook] and deployed via CI using GitHub
|
||||
Pages in the [`documentation.yml`][documentation.yml] workflow file with Nix's
|
||||
mdbook in the devshell. All documentation is in the `docs/` directory at the top
|
||||
level. The compiled mdbook website is also uploaded as an artifact.
|
||||
|
||||
To build the documentation using Nix, run: `bin/nix-build-and-cache just .#book`
|
||||
|
||||
The output of the mdbook generation is in `result/`. mdbooks can be opened in your browser from the individual HTML files without any web server needed.
|
||||
The output of the mdbook generation is in `result/`. mdbooks can be opened in
|
||||
your browser from the individual HTML files without any web server needed.
|
||||
|
||||
### Inclusivity and Diversity
|
||||
|
||||
All **MUST** code and write with inclusivity and diversity in mind. See the [following page by Google on writing inclusive code and documentation](https://developers.google.com/style/inclusive-documentation).
|
||||
All **MUST** code and write with inclusivity and diversity in mind. See the
|
||||
[following page by Google on writing inclusive code and
|
||||
documentation](https://developers.google.com/style/inclusive-documentation).
|
||||
|
||||
This **EXPLICITLY** forbids usage of terms like "blacklist"/"whitelist" and "master"/"slave", [forbids gender-specific words and phrases](https://developers.google.com/style/pronouns#gender-neutral-pronouns), forbids ableist language like "sanity-check", "cripple", or "insane", and forbids culture-specific language (e.g. US-only holidays or cultures).
|
||||
This **EXPLICITLY** forbids usage of terms like "blacklist"/"whitelist" and
|
||||
"master"/"slave", [forbids gender-specific words and
|
||||
phrases](https://developers.google.com/style/pronouns#gender-neutral-pronouns),
|
||||
forbids ableist language like "sanity-check", "cripple", or "insane", and
|
||||
forbids culture-specific language (e.g. US-only holidays or cultures).
|
||||
|
||||
No exceptions are allowed. Dependencies that may use these terms are allowed but [do not replicate the name in your functions or variables](https://developers.google.com/style/inclusive-documentation#write-around).
|
||||
No exceptions are allowed. Dependencies that may use these terms are allowed but
|
||||
[do not replicate the name in your functions or
|
||||
variables](https://developers.google.com/style/inclusive-documentation#write-around).
|
||||
|
||||
In addition to language, write and code with the user experience in mind. This is software that intends to be used by everyone, so make it easy and comfortable for everyone to use. 🏳️⚧️
|
||||
In addition to language, write and code with the user experience in mind. This
|
||||
is software that intends to be used by everyone, so make it easy and comfortable
|
||||
for everyone to use. 🏳️⚧️
|
||||
|
||||
### Variable, comment, function, etc standards
|
||||
|
||||
Rust's default style and standards with regards to [function names, variable names, comments](https://rust-lang.github.io/api-guidelines/naming.html), etc applies here.
|
||||
Rust's default style and standards with regards to [function names, variable
|
||||
names, comments](https://rust-lang.github.io/api-guidelines/naming.html), etc
|
||||
applies here.
|
||||
|
||||
### Creating pull requests
|
||||
|
||||
Please try to keep contributions to the GitHub. While the mirrors of conduwuit allow for pull/merge requests, there is no guarantee I will see them in a timely manner. Additionally, please mark WIP or unfinished or incomplete PRs as drafts. This prevents me from having to ping once in a while to double check the status of it, especially when the CI completed successfully and everything so it *looks* done.
|
||||
Please try to keep contributions to the GitHub. While the mirrors of conduwuit
|
||||
allow for pull/merge requests, there is no guarantee I will see them in a timely
|
||||
manner. Additionally, please mark WIP or unfinished or incomplete PRs as drafts.
|
||||
This prevents me from having to ping once in a while to double check the status
|
||||
of it, especially when the CI completed successfully and everything so it
|
||||
*looks* done.
|
||||
|
||||
If you open a pull request on one of the mirrors, it is your responsibility to inform me about its existence. In the future I may try to solve this with more repo bots in the conduwuit Matrix room. There is no mailing list or email-patch support on the sr.ht mirror, but if you'd like to email me a git patch you can do so at `strawberry@puppygock.gay`.
|
||||
If you open a pull request on one of the mirrors, it is your responsibility to
|
||||
inform me about its existence. In the future I may try to solve this with more
|
||||
repo bots in the conduwuit Matrix room. There is no mailing list or email-patch
|
||||
support on the sr.ht mirror, but if you'd like to email me a git patch you can
|
||||
do so at `strawberry@puppygock.gay`.
|
||||
|
||||
Direct all PRs/MRs to the `main` branch.
|
||||
|
||||
By sending a pull request or patch, you are agreeing that your changes are allowed to be licenced under the Apache-2.0 licence and all of your conduct is in line with the Contributor's Covenant.
|
||||
By sending a pull request or patch, you are agreeing that your changes are
|
||||
allowed to be licenced under the Apache-2.0 licence and all of your conduct is
|
||||
in line with the Contributor's Covenant.
|
||||
|
||||
[issues]: https://github.com/girlbossceo/conduwuit/issues
|
||||
[conduwuit-matrix]: https://matrix.to/#/#conduwuit:puppygock.gay
|
||||
|
||||
1124
Cargo.lock
generated
1124
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
157
Cargo.toml
157
Cargo.toml
@@ -14,20 +14,36 @@ categories = ["network-programming"]
|
||||
description = "a very cool fork of Conduit, a Matrix homeserver written in Rust"
|
||||
edition = "2021"
|
||||
homepage = "https://conduwuit.puppyirl.gay/"
|
||||
keywords = ["chat", "matrix", "server"]
|
||||
keywords = ["chat", "matrix", "server", "uwu"]
|
||||
license = "Apache-2.0"
|
||||
# See also `rust-toolchain.toml`
|
||||
readme = "README.md"
|
||||
repository = "https://github.com/girlbossceo/conduwuit"
|
||||
rust-version = "1.77.0"
|
||||
version = "0.4.5"
|
||||
rust-version = "1.80.1"
|
||||
version = "0.4.6"
|
||||
|
||||
[workspace.metadata.crane]
|
||||
name = "conduit"
|
||||
|
||||
[workspace.dependencies.arrayvec]
|
||||
version = "0.7.4"
|
||||
|
||||
[workspace.dependencies.const-str]
|
||||
version = "0.5.7"
|
||||
|
||||
[workspace.dependencies.ctor]
|
||||
version = "0.2.8"
|
||||
|
||||
[workspace.dependencies.cargo_toml]
|
||||
version = "0.20"
|
||||
default-features = false
|
||||
features = ["features"]
|
||||
|
||||
[workspace.dependencies.toml]
|
||||
version = "0.8.14"
|
||||
default-features = false
|
||||
features = ["parse"]
|
||||
|
||||
[workspace.dependencies.sanitize-filename]
|
||||
version = "0.5.0"
|
||||
|
||||
@@ -53,7 +69,7 @@ version = "0.8.5"
|
||||
|
||||
# Used for the http request / response body type for Ruma endpoints used with reqwest
|
||||
[workspace.dependencies.bytes]
|
||||
version = "1.6.1"
|
||||
version = "1.7.1"
|
||||
|
||||
[workspace.dependencies.http-body-util]
|
||||
version = "0.1.1"
|
||||
@@ -62,7 +78,7 @@ version = "0.1.1"
|
||||
version = "1.1.0"
|
||||
|
||||
[workspace.dependencies.regex]
|
||||
version = "1.10.4"
|
||||
version = "1.10.6"
|
||||
|
||||
[workspace.dependencies.axum]
|
||||
version = "0.7.5"
|
||||
@@ -83,18 +99,25 @@ default-features = false
|
||||
features = ["typed-header", "tracing"]
|
||||
|
||||
[workspace.dependencies.axum-server]
|
||||
version = "0.6.0"
|
||||
version = "0.7.1"
|
||||
default-features = false
|
||||
features = ["tls-rustls"]
|
||||
|
||||
# to listen on both HTTP and HTTPS if listening on TLS dierctly from conduwuit for complement or sytest
|
||||
[workspace.dependencies.axum-server-dual-protocol]
|
||||
version = "0.7"
|
||||
|
||||
[workspace.dependencies.axum-client-ip]
|
||||
version = "0.6.0"
|
||||
|
||||
[workspace.dependencies.tower]
|
||||
version = "0.4.13"
|
||||
version = "0.5.0"
|
||||
default-features = false
|
||||
features = ["util"]
|
||||
|
||||
[workspace.dependencies.tower-http]
|
||||
version = "0.5.2"
|
||||
default-features = false
|
||||
features = [
|
||||
"add-extension",
|
||||
"cors",
|
||||
@@ -105,8 +128,11 @@ features = [
|
||||
"catch-panic",
|
||||
]
|
||||
|
||||
[workspace.dependencies.rustls]
|
||||
version = "0.23.12"
|
||||
|
||||
[workspace.dependencies.reqwest]
|
||||
version = "0.12.4"
|
||||
version = "0.12.7"
|
||||
default-features = false
|
||||
features = [
|
||||
"rustls-tls-native-roots",
|
||||
@@ -117,10 +143,12 @@ features = [
|
||||
|
||||
[workspace.dependencies.serde]
|
||||
version = "1.0.204"
|
||||
default-features = false
|
||||
features = ["rc"]
|
||||
|
||||
[workspace.dependencies.serde_json]
|
||||
version = "1.0.120"
|
||||
version = "1.0.124"
|
||||
default-features = false
|
||||
features = ["raw_value"]
|
||||
|
||||
# Used for appservice registration files
|
||||
@@ -172,7 +200,7 @@ default-features = false
|
||||
|
||||
# used for conduit's CLI and admin room command parsing
|
||||
[workspace.dependencies.clap]
|
||||
version = "4.5.9"
|
||||
version = "4.5.15"
|
||||
default-features = false
|
||||
features = [
|
||||
"std",
|
||||
@@ -188,7 +216,8 @@ version = "0.3.30"
|
||||
default-features = false
|
||||
|
||||
[workspace.dependencies.tokio]
|
||||
version = "1.38.0"
|
||||
version = "1.39.2"
|
||||
default-features = false
|
||||
features = [
|
||||
"fs",
|
||||
"net",
|
||||
@@ -204,11 +233,12 @@ features = [
|
||||
version = "0.3.1"
|
||||
|
||||
[workspace.dependencies.libloading]
|
||||
version = "0.8.3"
|
||||
version = "0.8.5"
|
||||
|
||||
# Validating urls in config, was already a transitive dependency
|
||||
[workspace.dependencies.url]
|
||||
version = "2.5.0"
|
||||
default-features = false
|
||||
features = ["serde"]
|
||||
|
||||
# standard date and time tools
|
||||
@@ -218,7 +248,8 @@ features = ["alloc", "std"]
|
||||
default-features = false
|
||||
|
||||
[workspace.dependencies.hyper]
|
||||
version = "1.4.0"
|
||||
version = "1.4.1"
|
||||
default-features = false
|
||||
features = [
|
||||
"server",
|
||||
"http1",
|
||||
@@ -227,6 +258,7 @@ features = [
|
||||
|
||||
[workspace.dependencies.hyper-util]
|
||||
version = "0.1.6"
|
||||
default-features = false
|
||||
features = [
|
||||
"client",
|
||||
"server-auto",
|
||||
@@ -238,11 +270,13 @@ features = [
|
||||
# to support multiple variations of setting a config option
|
||||
[workspace.dependencies.either]
|
||||
version = "1.11.0"
|
||||
default-features = false
|
||||
features = ["serde"]
|
||||
|
||||
# Used for reading the configuration from conduwuit.toml & environment variables
|
||||
[workspace.dependencies.figment]
|
||||
version = "0.10.18"
|
||||
default-features = false
|
||||
features = ["env", "toml"]
|
||||
|
||||
[workspace.dependencies.hickory-resolver]
|
||||
@@ -251,7 +285,7 @@ default-features = false
|
||||
|
||||
# Used for conduit::Error type
|
||||
[workspace.dependencies.thiserror]
|
||||
version = "1.0.62"
|
||||
version = "1.0.63"
|
||||
|
||||
# Used when hashing the state
|
||||
[workspace.dependencies.ring]
|
||||
@@ -280,7 +314,7 @@ version = "0.1.2"
|
||||
[workspace.dependencies.ruma]
|
||||
git = "https://github.com/girlbossceo/ruwuma"
|
||||
#branch = "conduwuit-changes"
|
||||
rev = "c51ccb2c68d2e3557eb12b1a49036531711ec0e5"
|
||||
rev = "d7ddcd036f81edb257ab9371f9cadd46444e8a90"
|
||||
features = [
|
||||
"compat",
|
||||
"rand",
|
||||
@@ -293,6 +327,7 @@ features = [
|
||||
"server-util",
|
||||
"unstable-exhaustive-types",
|
||||
"ring-compat",
|
||||
"identifiers-validation",
|
||||
"unstable-unspecified",
|
||||
"unstable-msc2448",
|
||||
"unstable-msc2666",
|
||||
@@ -301,16 +336,14 @@ features = [
|
||||
"unstable-msc3026",
|
||||
"unstable-msc3061",
|
||||
"unstable-msc3266",
|
||||
"unstable-msc3381", # polls
|
||||
"unstable-msc3489", # beacon / live location
|
||||
"unstable-msc3575",
|
||||
"unstable-msc4121",
|
||||
"unstable-msc4125",
|
||||
"unstable-extensible-events",
|
||||
]
|
||||
|
||||
[workspace.dependencies.ruma-identifiers-validation]
|
||||
git = "https://github.com/girlbossceo/ruwuma"
|
||||
rev = "c51ccb2c68d2e3557eb12b1a49036531711ec0e5"
|
||||
|
||||
[workspace.dependencies.rust-rocksdb]
|
||||
path = "deps/rust-rocksdb"
|
||||
package = "rust-rocksdb-uwu"
|
||||
@@ -323,10 +356,6 @@ features = [
|
||||
"bzip2",
|
||||
]
|
||||
|
||||
# to listen on both HTTP and HTTPS if listening on TLS dierctly from conduwuit for complement or sytest
|
||||
[workspace.dependencies.axum-server-dual-protocol]
|
||||
version = "0.6"
|
||||
|
||||
# optional SHA256 media keys feature
|
||||
[workspace.dependencies.sha2]
|
||||
version = "0.10.8"
|
||||
@@ -373,23 +402,27 @@ version = "0.34.0"
|
||||
|
||||
# jemalloc usage
|
||||
[workspace.dependencies.tikv-jemalloc-sys]
|
||||
version = "0.5.4"
|
||||
git = "https://github.com/girlbossceo/jemallocator"
|
||||
rev = "c32af15f3b440ae5e46c3404f78b19093bbd5294"
|
||||
default-features = false
|
||||
features = ["stats", "unprefixed_malloc_on_supported_platforms"]
|
||||
features = ["unprefixed_malloc_on_supported_platforms"]
|
||||
[workspace.dependencies.tikv-jemallocator]
|
||||
version = "0.5.4"
|
||||
git = "https://github.com/girlbossceo/jemallocator"
|
||||
rev = "c32af15f3b440ae5e46c3404f78b19093bbd5294"
|
||||
default-features = false
|
||||
features = ["stats", "unprefixed_malloc_on_supported_platforms"]
|
||||
features = ["unprefixed_malloc_on_supported_platforms"]
|
||||
[workspace.dependencies.tikv-jemalloc-ctl]
|
||||
version = "0.5.4"
|
||||
git = "https://github.com/girlbossceo/jemallocator"
|
||||
rev = "c32af15f3b440ae5e46c3404f78b19093bbd5294"
|
||||
default-features = false
|
||||
features = ["use_std"]
|
||||
|
||||
[workspace.dependencies.console-subscriber]
|
||||
version = "0.3"
|
||||
version = "0.4"
|
||||
|
||||
[workspace.dependencies.nix]
|
||||
version = "0.29.0"
|
||||
default-features = false
|
||||
features = ["resource"]
|
||||
|
||||
[workspace.dependencies.sd-notify]
|
||||
@@ -405,16 +438,27 @@ features = [
|
||||
]
|
||||
|
||||
[workspace.dependencies.rustyline-async]
|
||||
version = "0.4.2"
|
||||
version = "0.4.3"
|
||||
default-features = false
|
||||
|
||||
[workspace.dependencies.termimad]
|
||||
version = "0.29.4"
|
||||
version = "0.30.0"
|
||||
default-features = false
|
||||
|
||||
[workspace.dependencies.checked_ops]
|
||||
version = "0.1"
|
||||
|
||||
[workspace.dependencies.syn]
|
||||
version = "2.0.72"
|
||||
default-features = false
|
||||
features = ["full", "extra-traits"]
|
||||
|
||||
[workspace.dependencies.quote]
|
||||
version = "1.0.36"
|
||||
|
||||
[workspace.dependencies.proc-macro2]
|
||||
version = "1.0.86"
|
||||
|
||||
|
||||
#
|
||||
# Patches
|
||||
@@ -436,17 +480,11 @@ rev = "4d78a14a5e03f539b8c6b475aefa08bb14e4de91"
|
||||
git = "https://github.com/girlbossceo/tracing"
|
||||
rev = "4d78a14a5e03f539b8c6b475aefa08bb14e4de91"
|
||||
|
||||
# fixes hyper graceful shutdowns [https://github.com/programatik29/axum-server/issues/114]
|
||||
# https://github.com/girlbossceo/axum-server/commit/8e3368d899079818934e61cc9c839abcbbcada8a
|
||||
[patch.crates-io.axum-server]
|
||||
git = "https://github.com/girlbossceo/axum-server"
|
||||
rev = "8e3368d899079818934e61cc9c839abcbbcada8a"
|
||||
|
||||
# adds a tab completion callback: https://github.com/girlbossceo/rustyline-async/commit/de26100b0db03e419a3d8e1dd26895d170d1fe50
|
||||
# adds event for CTRL+\: https://github.com/girlbossceo/rustyline-async/commit/67d8c49aeac03a5ef4e818f663eaa94dd7bf339b
|
||||
[patch.crates-io.rustyline-async]
|
||||
git = "https://github.com/girlbossceo/rustyline-async"
|
||||
rev = "de26100b0db03e419a3d8e1dd26895d170d1fe50"
|
||||
rev = "9654cc84e19241f6e19021eb8e677892656f5071"
|
||||
|
||||
#
|
||||
# Our crates
|
||||
@@ -482,6 +520,11 @@ package = "conduit_core"
|
||||
path = "src/core"
|
||||
default-features = false
|
||||
|
||||
[workspace.dependencies.conduit-macros]
|
||||
package = "conduit_macros"
|
||||
path = "src/macros"
|
||||
default-features = false
|
||||
|
||||
###############################################################################
|
||||
#
|
||||
# Release profiles
|
||||
@@ -530,7 +573,17 @@ lto = "fat"
|
||||
[profile.release-max-perf.build-override]
|
||||
inherits = "release-max-perf"
|
||||
opt-level = 0
|
||||
codegen-units = 32
|
||||
#rustflags = [
|
||||
# '-Crelocation-model=pic',
|
||||
# '-Ctarget-feature=-crt-static',
|
||||
# '-Clink-arg=-Wl,--no-gc-sections',
|
||||
#]
|
||||
|
||||
[profile.release-max-perf.package.conduit_macros]
|
||||
inherits = "release-max-perf.build-override"
|
||||
#rustflags = [
|
||||
# '-Crelocation-model=pic',
|
||||
# '-Ctarget-feature=-crt-static',
|
||||
#]
|
||||
|
||||
@@ -659,7 +712,16 @@ opt-level = 'z'
|
||||
# '-Clink-arg=-Wl,-z,nodelete',
|
||||
#]
|
||||
|
||||
# primarily used for CI
|
||||
[profile.test]
|
||||
inherits = "dev"
|
||||
codegen-units = 16
|
||||
incremental = false
|
||||
|
||||
[profile.test.package.'*']
|
||||
inherits = "dev"
|
||||
debug = 0
|
||||
codegen-units = 16
|
||||
incremental = false
|
||||
|
||||
###############################################################################
|
||||
@@ -721,19 +783,19 @@ variant_size_differences = "allow"
|
||||
[workspace.lints.clippy]
|
||||
|
||||
###################
|
||||
cargo = "warn"
|
||||
cargo = { level = "warn", priority = -1 }
|
||||
|
||||
## some sadness
|
||||
multiple_crate_versions = { level = "allow", priority = 1 }
|
||||
|
||||
###################
|
||||
complexity = "warn"
|
||||
complexity = { level = "warn", priority = -1 }
|
||||
|
||||
###################
|
||||
correctness = "warn"
|
||||
correctness = { level = "warn", priority = -1 }
|
||||
|
||||
###################
|
||||
nursery = "warn"
|
||||
nursery = { level = "warn", priority = -1 }
|
||||
|
||||
## some sadness
|
||||
missing_const_for_fn = { level = "allow", priority = 1 } # TODO
|
||||
@@ -743,7 +805,7 @@ significant_drop_in_scrutinee = { level = "allow", priority = 1 } # TODO
|
||||
significant_drop_tightening = { level = "allow", priority = 1 } # TODO
|
||||
|
||||
###################
|
||||
pedantic = "warn"
|
||||
pedantic = { level = "warn", priority = -1 }
|
||||
|
||||
## some sadness
|
||||
doc_markdown = { level = "allow", priority = 1 }
|
||||
@@ -762,12 +824,12 @@ unnecessary_wraps = { level = "allow", priority = 1 }
|
||||
unused_async = { level = "allow", priority = 1 }
|
||||
|
||||
###################
|
||||
perf = "warn"
|
||||
perf = { level = "warn", priority = -1 }
|
||||
|
||||
###################
|
||||
#restriction = "warn"
|
||||
|
||||
allow_attributes = "warn"
|
||||
#allow_attributes = "warn" # UNSTABLE
|
||||
arithmetic_side_effects = "warn"
|
||||
as_conversions = "warn"
|
||||
as_underscore = "warn"
|
||||
@@ -812,14 +874,15 @@ unseparated_literal_suffix = "warn"
|
||||
verbose_file_reads = "warn"
|
||||
|
||||
###################
|
||||
style = "warn"
|
||||
style = { level = "warn", priority = -1 }
|
||||
|
||||
## some sadness
|
||||
# trivial assertions are quite alright
|
||||
assertions_on_constants = { level = "allow", priority = 1 }
|
||||
module_inception = { level = "allow", priority = 1 }
|
||||
|
||||
###################
|
||||
suspicious = "warn"
|
||||
suspicious = { level = "warn", priority = -1 }
|
||||
|
||||
## some sadness
|
||||
let_underscore_future = { level = "allow", priority = 1 }
|
||||
|
||||
49
README.md
49
README.md
@@ -1,15 +1,15 @@
|
||||
# conduwuit
|
||||
|
||||
`main` / stable: [](https://github.com/girlbossceo/conduwuit/actions/workflows/ci.yml)
|
||||
`main` / stable: [](https://github.com/girlbossceo/conduwuit/actions/workflows/ci.yml)
|
||||
|
||||
<!-- ANCHOR: catchphrase -->
|
||||
### a very cool, featureful fork of [Conduit](https://conduit.rs/)
|
||||
<!-- ANCHOR_END: catchphrase -->
|
||||
<!-- ANCHOR: catchphrase --> ### a very cool, featureful fork of
|
||||
[Conduit](https://conduit.rs/) <!-- ANCHOR_END: catchphrase -->
|
||||
|
||||
Visit the [Conduwuit documentation](https://conduwuit.puppyirl.gay/) for more information.
|
||||
Visit the [Conduwuit documentation](https://conduwuit.puppyirl.gay/) for more
|
||||
information.
|
||||
|
||||
<!-- ANCHOR: body -->
|
||||
#### What is Matrix?
|
||||
<!-- ANCHOR: body --> #### What is Matrix?
|
||||
|
||||
[Matrix](https://matrix.org) is an open network for secure and decentralized
|
||||
communication. Users from every Matrix homeserver can chat with users from all
|
||||
@@ -18,29 +18,32 @@ #### What is Matrix?
|
||||
|
||||
#### What is the goal?
|
||||
|
||||
An efficient Matrix homeserver that's easy to set up and just works. You can install
|
||||
it on a mini-computer like the Raspberry Pi to host Matrix for your family,
|
||||
friends or company.
|
||||
An efficient Matrix homeserver that's easy to set up and just works. You can
|
||||
install it on a mini-computer like the Raspberry Pi to host Matrix for your
|
||||
family, friends or company.
|
||||
|
||||
#### Can I try it out?
|
||||
|
||||
An official conduwuit server ran by me is available at transfem.dev ([element.transfem.dev](https://element.transfem.dev) / [cinny.transfem.dev](https://cinny.transfem.dev))
|
||||
An official conduwuit server ran by me is available at transfem.dev
|
||||
([element.transfem.dev](https://element.transfem.dev) /
|
||||
[cinny.transfem.dev](https://cinny.transfem.dev))
|
||||
|
||||
transfem.dev is a public homeserver that can be used, it is not a "test only homeserver". This means there are rules, so please read the rules: [https://transfem.dev/homeserver_rules.txt](https://transfem.dev/homeserver_rules.txt)
|
||||
transfem.dev is a public homeserver that can be used, it is not a "test only
|
||||
homeserver". This means there are rules, so please read the rules:
|
||||
[https://transfem.dev/homeserver_rules.txt](https://transfem.dev/homeserver_rules.txt)
|
||||
|
||||
transfem.dev is also listed at [servers.joinmatrix.org](https://servers.joinmatrix.org/)
|
||||
transfem.dev is also listed at
|
||||
[servers.joinmatrix.org](https://servers.joinmatrix.org/)
|
||||
|
||||
#### What is the current status?
|
||||
|
||||
conduwuit is a hard fork of Conduit which is in beta, meaning you can join and participate in most
|
||||
Matrix rooms, but not all features are supported and you might run into bugs
|
||||
from time to time.
|
||||
conduwuit is a hard fork of Conduit which is in beta, meaning you can join and
|
||||
participate in most Matrix rooms, but not all features are supported and you
|
||||
might run into bugs from time to time.
|
||||
|
||||
<!-- ANCHOR_END: body -->
|
||||
|
||||
<!-- ANCHOR: footer -->
|
||||
|
||||
#### Contact
|
||||
<!-- ANCHOR: footer --> #### Contact
|
||||
|
||||
If you run into any question, feel free to
|
||||
|
||||
@@ -55,7 +58,9 @@ #### Donate
|
||||
|
||||
#### Logo
|
||||
|
||||
Original repo and Matrix room picture was from bran (<3). Current banner image and logo is directly from [this cohost post](https://cohost.org/RatBaby/post/1028290-finally-a-flag-for).
|
||||
Original repo and Matrix room picture was from bran (<3). Current banner image
|
||||
and logo is directly from [this cohost
|
||||
post](https://cohost.org/RatBaby/post/1028290-finally-a-flag-for).
|
||||
|
||||
#### Is it conduwuit or Conduwuit?
|
||||
|
||||
@@ -68,5 +73,5 @@ #### Mirrors of conduwuit
|
||||
- git.girlcock.ceo: <https://git.girlcock.ceo/strawberry/conduwuit>
|
||||
- git.gay: <https://git.gay/june/conduwuit>
|
||||
- Codeberg: <https://codeberg.org/girlbossceo/conduwuit>
|
||||
- sourcehut: <https://git.sr.ht/~girlbossceo/conduwuit>
|
||||
<!-- ANCHOR_END: footer -->
|
||||
- sourcehut: <https://git.sr.ht/~girlbossceo/conduwuit> <!-- ANCHOR_END: footer
|
||||
-->
|
||||
|
||||
@@ -52,9 +52,10 @@
|
||||
|
||||
# Performance monitoring/tracing sample rate for Sentry.io
|
||||
#
|
||||
# Note that too high values may impact performance, and can be disabled by setting it to 0.0
|
||||
# Note that too high values may impact performance, and can be disabled by setting it to 0.0 (0%)
|
||||
# This value is read as a percentage to Sentry, represented as a decimal
|
||||
#
|
||||
# Defaults to 0.15
|
||||
# Defaults to 15% of traces (0.15)
|
||||
#sentry_traces_sample_rate = 0.15
|
||||
|
||||
# Whether to attach a stacktrace to Sentry reports.
|
||||
@@ -223,9 +224,11 @@ registration_token = "change this token for something specific to your server"
|
||||
# No default.
|
||||
# forbidden_alias_names = []
|
||||
|
||||
# List of forbidden server names that we will block all client room joins, incoming federated room directory requests, incoming federated invites for, and incoming federated joins. This check is applied on the room ID, room alias, sender server name, and sender user's server name.
|
||||
# Basically "global" ACLs. For our user (client) checks, admin users are allowed.
|
||||
# No default.
|
||||
# List of forbidden server names that we will block incoming AND outgoing federation with, and block client room joins / remote user invites.
|
||||
#
|
||||
# This check is applied on the room ID, room alias, sender server name, sender user's server name, inbound federation X-Matrix origin, and outbound federation handler.
|
||||
#
|
||||
# Basically "global" ACLs. No default.
|
||||
# forbidden_remote_server_names = []
|
||||
|
||||
# List of forbidden server names that we will block all outgoing federated room directory requests for. Useful for preventing our users from wandering into bad servers or spaces.
|
||||
@@ -387,10 +390,21 @@ allow_profile_lookup_federation_requests = true
|
||||
|
||||
# Enable backward-compatibility with Conduit's media directory by creating symlinks of media. This
|
||||
# option is only necessary if you plan on using Conduit again. Otherwise setting this to false
|
||||
# reduces filesystem clutter and overhead for managing these symlinks in the directory.
|
||||
# reduces filesystem clutter and overhead for managing these symlinks in the directory. This is now
|
||||
# disabled by default. You may still return to upstream Conduit but you have to run Conduwuit at
|
||||
# least once with this set to true and allow the media_startup_check to take place before shutting
|
||||
# down to return to Conduit.
|
||||
#
|
||||
# Enabled by default.
|
||||
#media_compat_file_link = true
|
||||
# Disabled by default.
|
||||
#media_compat_file_link = false
|
||||
|
||||
# Prunes missing media from the database as part of the media startup checks. This means if you
|
||||
# delete files from the media directory the corresponding entries will be removed from the
|
||||
# database. This is disabled by default because if the media directory is accidentally moved or
|
||||
# inaccessible the metadata entries in the database will be lost with sadness.
|
||||
#
|
||||
# Disabled by default.
|
||||
#prune_missing_media = false
|
||||
|
||||
# Checks consistency of the media directory at startup:
|
||||
# 1. When `media_compat_file_link` is enbled, this check will upgrade media when switching back
|
||||
@@ -401,7 +415,7 @@ allow_profile_lookup_federation_requests = true
|
||||
# setting this to false may reduce startup time.
|
||||
#
|
||||
# Enabled by default.
|
||||
#media_statup_check = true
|
||||
#media_startup_check = true
|
||||
|
||||
# OpenID token expiration/TTL in seconds
|
||||
#
|
||||
@@ -513,6 +527,31 @@ allow_profile_lookup_federation_requests = true
|
||||
# Defaults to false as this uses more CPU when compressing.
|
||||
#rocksdb_bottommost_compression = false
|
||||
|
||||
# Level of statistics collection. Some admin commands to display database statistics may require
|
||||
# this option to be set. Database performance may be impacted by higher settings.
|
||||
#
|
||||
# Option is a number ranging from 0 to 6:
|
||||
# 0 = No statistics.
|
||||
# 1 = No statistics in release mode (default).
|
||||
# 2 to 3 = Statistics with no performance impact.
|
||||
# 3 to 5 = Statistics with possible performance impact.
|
||||
# 6 = All statistics.
|
||||
#
|
||||
# Defaults to 1 (No statistics, except in debug-mode)
|
||||
#rocksdb_stats_level = 1
|
||||
|
||||
# Database repair mode (for RocksDB SST corruption)
|
||||
#
|
||||
# Use this option when the server reports corruption while running or panics. If the server refuses
|
||||
# to start use the recovery mode options first. Corruption errors containing the acronym 'SST' which
|
||||
# occur after startup will likely require this option.
|
||||
#
|
||||
# - Backing up your database directory is recommended prior to running the repair.
|
||||
# - Disabling repair mode and restarting the server is recommended after running the repair.
|
||||
#
|
||||
# Defaults to false
|
||||
#rocksdb_repair = false
|
||||
|
||||
# Database recovery mode (for RocksDB WAL corruption)
|
||||
#
|
||||
# Use this option when the server reports corruption and refuses to start. Set mode 2 (PointInTime)
|
||||
|
||||
1
debian/postinst
vendored
1
debian/postinst
vendored
@@ -16,7 +16,6 @@ case "$1" in
|
||||
--home "$CONDUWUIT_DATABASE_PATH" \
|
||||
--disabled-login \
|
||||
--shell "/usr/sbin/nologin" \
|
||||
--verbose \
|
||||
conduwuit
|
||||
fi
|
||||
|
||||
|
||||
4
deps/rust-rocksdb/Cargo.toml
vendored
4
deps/rust-rocksdb/Cargo.toml
vendored
@@ -26,8 +26,8 @@ serde1 = ["rust-rocksdb/serde1"]
|
||||
malloc-usable-size = ["rust-rocksdb/malloc-usable-size"]
|
||||
|
||||
[dependencies.rust-rocksdb]
|
||||
git = "https://github.com/zaidoon1/rust-rocksdb"
|
||||
rev = "4056a3b0f823013fec49f6d0b3e5698856e6476a"
|
||||
git = "https://github.com/girlbossceo/rust-rocksdb-zaidoon1"
|
||||
rev = "5383ca8173299066b516406e3a2cf945ead891cb"
|
||||
#branch = "master"
|
||||
default-features = false
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ # Summary
|
||||
- [Docker](deploying/docker.md)
|
||||
- [Arch Linux](deploying/arch-linux.md)
|
||||
- [Debian](deploying/debian.md)
|
||||
- [FreeBSD](deploying/freebsd.md)
|
||||
- [TURN](turn.md)
|
||||
- [Appservices](appservices.md)
|
||||
- [Maintenance](maintenance.md)
|
||||
|
||||
@@ -2,13 +2,15 @@ # Setting up Appservices
|
||||
|
||||
## Getting help
|
||||
|
||||
If you run into any problems while setting up an Appservice: ask us in [#conduwuit:puppygock.gay](https://matrix.to/#/#conduwuit:puppygock.gay) or [open an issue on GitHub](https://github.com/girlbossceo/conduwuit/issues/new).
|
||||
If you run into any problems while setting up an Appservice: ask us in
|
||||
[#conduwuit:puppygock.gay](https://matrix.to/#/#conduwuit:puppygock.gay) or
|
||||
[open an issue on GitHub](https://github.com/girlbossceo/conduwuit/issues/new).
|
||||
|
||||
## Set up the appservice - general instructions
|
||||
|
||||
Follow whatever instructions are given by the appservice. This usually includes
|
||||
downloading, changing its config (setting domain, homeserver url, port etc.)
|
||||
and later starting it.
|
||||
downloading, changing its config (setting domain, homeserver url, port etc.) and
|
||||
later starting it.
|
||||
|
||||
At some point the appservice guide should ask you to add a registration yaml
|
||||
file to the homeserver. In Synapse you would do this by adding the path to the
|
||||
|
||||
@@ -1,76 +1,92 @@
|
||||
# conduwuit Community Code of Conduct
|
||||
|
||||
Welcome to the conduwuit community! We’re excited to have you here. conduwuit is a hard-fork of the Conduit homeserver,
|
||||
aimed at making Matrix more accessible and inclusive for everyone.
|
||||
Welcome to the conduwuit community! We’re excited to have you here. conduwuit is
|
||||
a hard-fork of the Conduit homeserver, aimed at making Matrix more accessible
|
||||
and inclusive for everyone.
|
||||
|
||||
This space is dedicated to fostering a positive, supportive, and inclusive environment for everyone. This Code of
|
||||
Conduct applies to all conduwuit spaces, including any further community rooms that reference this CoC. Here are our
|
||||
This space is dedicated to fostering a positive, supportive, and inclusive
|
||||
environment for everyone. This Code of Conduct applies to all conduwuit spaces,
|
||||
including any further community rooms that reference this CoC. Here are our
|
||||
guidelines to help maintain the welcoming atmosphere that sets conduwuit apart.
|
||||
|
||||
For the foundational rules, please refer to the [Matrix.org Code of Conduct](https://matrix.org/legal/code-of-conduct/)
|
||||
and the [Contributor's Covenant](https://github.com/girlbossceo/conduwuit/blob/main/CODE_OF_CONDUCT.md). Below are
|
||||
additional guidelines specific to the conduwuit community.
|
||||
For the general foundational rules, please refer to the [Contributor's
|
||||
Covenant](https://github.com/girlbossceo/conduwuit/blob/main/CODE_OF_CONDUCT.md).
|
||||
Below are additional guidelines specific to the conduwuit community.
|
||||
|
||||
## Our Values and Guidelines
|
||||
|
||||
1. **Respect and Inclusivity**: We are committed to maintaining a community where everyone feels safe and respected.
|
||||
Discrimination, harassment, or hate speech of any kind will not be tolerated. Recognise that each community member
|
||||
experiences the world differently based on their past experiences, background, and identity. Share your own
|
||||
experiences and be open to learning about others' diverse perspectives.
|
||||
1. **Respect and Inclusivity**: We are committed to maintaining a community
|
||||
where everyone feels safe and respected. Discrimination, harassment, or hate
|
||||
speech of any kind will not be tolerated. Recognise that each community member
|
||||
experiences the world differently based on their past experiences, background,
|
||||
and identity. Share your own experiences and be open to learning about others'
|
||||
diverse perspectives.
|
||||
|
||||
2. **Positivity and Constructiveness**: Engage in constructive discussions and support each other. If you feel angry,
|
||||
negative, or aggressive, take a break until you can participate in a positive and constructive manner. Process
|
||||
intense feelings with a friend or in a private setting before engaging in community conversations to help maintain
|
||||
a supportive and focused environment.
|
||||
2. **Positivity and Constructiveness**: Engage in constructive discussions and
|
||||
support each other. If you feel angry, negative, or aggressive, take a break
|
||||
until you can participate in a positive and constructive manner. Process intense
|
||||
feelings with a friend or in a private setting before engaging in community
|
||||
conversations to help maintain a supportive and focused environment.
|
||||
|
||||
3. **Clarity and Understanding**: Our community includes neurodivergent individuals and those who may not appreciate
|
||||
sarcasm or subtlety. Communicate clearly and kindly, avoiding sarcasm and ensuring your messages are easily
|
||||
understood by all. Additionally, avoid putting the burden of education on marginalized groups by doing your own
|
||||
research before asking for explanations.
|
||||
3. **Clarity and Understanding**: Our community includes neurodivergent
|
||||
individuals and those who may not appreciate sarcasm or subtlety. Communicate
|
||||
clearly and kindly, avoiding sarcasm and ensuring your messages are easily
|
||||
understood by all. Additionally, avoid putting the burden of education on
|
||||
marginalized groups by doing your own research before asking for explanations.
|
||||
|
||||
4. **Be Open to Inclusivity**: Actively engage in conversations about making our community more inclusive. Report
|
||||
discriminatory behavior to the moderators and be open to constructive feedback that aims to improve our community.
|
||||
Understand that discussing discrimination and negative experiences can be emotionally taxing, so focus on the
|
||||
message rather than critiquing the tone used.
|
||||
4. **Be Open to Inclusivity**: Actively engage in conversations about making our
|
||||
community more inclusive. Report discriminatory behavior to the moderators
|
||||
and be open to constructive feedback that aims to improve our community.
|
||||
Understand that discussing discrimination and negative experiences can be
|
||||
emotionally taxing, so focus on the message rather than critiquing the tone
|
||||
used.
|
||||
|
||||
5. **Commit to Inclusivity**: Building an inclusive community requires time, energy, and resources. Recognise that
|
||||
addressing discrimination and bias is an ongoing process that necessitates commitment and action from all community
|
||||
members.
|
||||
5. **Commit to Inclusivity**: Building an inclusive community requires time,
|
||||
energy, and resources. Recognise that addressing discrimination and bias is
|
||||
an ongoing process that necessitates commitment and action from all community
|
||||
members.
|
||||
|
||||
## Matrix Community
|
||||
|
||||
This Code of Conduct applies to the entire [conduwuit Matrix Space](https://matrix.to/#/#conduwuit-space:puppygock.gay)
|
||||
and its rooms, including:
|
||||
This Code of Conduct applies to the entire [conduwuit Matrix
|
||||
Space](https://matrix.to/#/#conduwuit-space:puppygock.gay) and its rooms,
|
||||
including:
|
||||
|
||||
### [#conduwuit:puppygock.gay](https://matrix.to/#/#conduwuit:puppygock.gay)
|
||||
|
||||
This room is for support and discussions about conduwuit. Ask questions, share insights, and help each other out.
|
||||
This room is for support and discussions about conduwuit. Ask questions, share
|
||||
insights, and help each other out.
|
||||
|
||||
### [#conduwuit-offtopic:girlboss.ceo](https://matrix.to/#/#conduwuit-offtopic:girlboss.ceo)
|
||||
|
||||
For off-topic community conversations about any subject. While this room allows for a wide range of topics, the same
|
||||
CoC applies. Keep discussions respectful and inclusive, and avoid divisive subjects like country/world politics.
|
||||
General topics, such as world events, are welcome as long as they follow the CoC.
|
||||
For off-topic community conversations about any subject. While this room allows
|
||||
for a wide range of topics, the same CoC applies. Keep discussions respectful
|
||||
and inclusive, and avoid divisive subjects like country/world politics. General
|
||||
topics, such as world events, are welcome as long as they follow the CoC.
|
||||
|
||||
### [#conduwuit-dev:puppygock.gay](https://matrix.to/#/#conduwuit-dev:puppygock.gay)
|
||||
|
||||
This room is dedicated to discussing active development of conduwuit. Posting requires an elevated power level, which
|
||||
can be requested in one of the other rooms. Use this space to collaborate and innovate.
|
||||
This room is dedicated to discussing active development of conduwuit. Posting
|
||||
requires an elevated power level, which can be requested in one of the other
|
||||
rooms. Use this space to collaborate and innovate.
|
||||
|
||||
## Enforcement
|
||||
|
||||
We have a zero-tolerance policy for violations of this Code of Conduct. If someone’s behavior makes you uncomfortable,
|
||||
please report it to the moderators. Actions we may take include:
|
||||
We have a zero-tolerance policy for violations of this Code of Conduct. If
|
||||
someone’s behavior makes you uncomfortable, please report it to the moderators.
|
||||
Actions we may take include:
|
||||
|
||||
1. **Warning**: A warning given directly in the room or via a private message from the moderators, identifying
|
||||
the violation and requesting corrective action.
|
||||
2. **Temporary Mute**: Temporary restriction from participating in discussions for a specified period to allow for
|
||||
reflection and cooling off.
|
||||
3. **Kick or Ban**: Egregious behavior may result in an immediate kick or ban to protect other community members.
|
||||
Bans are considered permanent and will only be reversed in exceptional circumstances after proven good behavior.
|
||||
1. **Warning**: A warning given directly in the room or via a private message
|
||||
from the moderators, identifying the violation and requesting corrective
|
||||
action.
|
||||
2. **Temporary Mute**: Temporary restriction from participating in discussions
|
||||
for a specified period to allow for reflection and cooling off.
|
||||
3. **Kick or Ban**: Egregious behavior may result in an immediate kick or ban to
|
||||
protect other community members. Bans are considered permanent and will only
|
||||
be reversed in exceptional circumstances after proven good behavior.
|
||||
|
||||
Please highlight issues directly in rooms when possible, but if you don't feel comfortable doing that, then please send
|
||||
a DM to one of the moderators directly.
|
||||
Please highlight issues directly in rooms when possible, but if you don't feel
|
||||
comfortable doing that, then please send a DM to one of the moderators directly.
|
||||
|
||||
Together, let’s build a community where everyone feels valued and respected.
|
||||
|
||||
|
||||
@@ -4,15 +4,45 @@ # Configuration
|
||||
|
||||
## Basics
|
||||
|
||||
Conduwuit uses a config file for the majority of the settings. Please refer to the
|
||||
[example config file](./configuration/examples.md#example-configuration) for all of those settings.
|
||||
The config file to use can either be specified on the command line when running conduwuit by specifying the
|
||||
`-c`, `--config` flag. Alternatively, you can use the environment variable `CONDUWUIT_CONFIG` to specify the config
|
||||
file to used.
|
||||
conduwuit uses a config file for the majority of the settings, but also supports
|
||||
setting individual config options via commandline.
|
||||
|
||||
Please refer to the [example config
|
||||
file](./configuration/examples.md#example-configuration) for all of those
|
||||
settings.
|
||||
|
||||
The config file to use can be specified on the commandline when running
|
||||
conduwuit by specifying the `-c`, `--config` flag. Alternatively, you can use
|
||||
the environment variable `CONDUWUIT_CONFIG` to specify the config file to used.
|
||||
Conduit's environment variables are supported for backwards compatibility.
|
||||
|
||||
## Option commandline flag
|
||||
|
||||
conduwuit supports setting individual config options in TOML format from the
|
||||
`-O` / `--option` flag. For example, you can set your server name via `-O
|
||||
server_name=\"example.com\"`.
|
||||
|
||||
Note that the config is parsed as TOML, and shells like bash will remove quotes.
|
||||
So unfortunately it is required to escape quotes if the config option takes a
|
||||
string. This does not apply to options that take booleans or numbers:
|
||||
- `--option allow_registration=true` works ✅
|
||||
- `-O max_request_size=99999999` works ✅
|
||||
- `-O server_name=example.com` does not work ❌
|
||||
- `--option log=\"debug\"` works ✅
|
||||
- `--option server_name='"example.com'"` works ✅
|
||||
|
||||
|
||||
## Environment variables
|
||||
|
||||
All of the settings that are found in the config file can be specified by using environment variables.
|
||||
The environment variable names should be all caps and prefixed with `CONDUWUIT_`.
|
||||
For example, if the setting you are changing is `max_request_size`, then the environment variable to set is
|
||||
`CONDUWUIT_MAX_REQUEST_SIZE`.
|
||||
All of the settings that are found in the config file can be specified by using
|
||||
environment variables. The environment variable names should be all caps and
|
||||
prefixed with `CONDUWUIT_`.
|
||||
|
||||
For example, if the setting you are changing is `max_request_size`, then the
|
||||
environment variable to set is `CONDUWUIT_MAX_REQUEST_SIZE`.
|
||||
|
||||
To modify config options not in the `[global]` context such as
|
||||
`[global.well_known]`, use the `__` suffix split: `CONDUWUIT_WELL_KNOWN__SERVER`
|
||||
|
||||
Conduit's environment variables are supported for backwards compatibility (e.g.
|
||||
`CONDUIT_SERVER_NAME`).
|
||||
|
||||
@@ -2,8 +2,14 @@ # conduwuit for Arch Linux
|
||||
|
||||
Currently conduwuit is only on the Arch User Repository (AUR).
|
||||
|
||||
The conduwuit AUR packages are community maintained and are not maintained by conduwuit development team, but the AUR package maintainers are in the Matrix room. Please attempt to verify your AUR package's PKGBUILD file looks fine before asking for support.
|
||||
The conduwuit AUR packages are community maintained and are not maintained by
|
||||
conduwuit development team, but the AUR package maintainers are in the Matrix
|
||||
room. Please attempt to verify your AUR package's PKGBUILD file looks fine
|
||||
before asking for support.
|
||||
|
||||
- [conduwuit](https://aur.archlinux.org/packages/conduwuit) - latest tagged conduwuit
|
||||
- [conduwuit-git](https://aur.archlinux.org/packages/conduwuit-git) - latest git conduwuit from `main` branch
|
||||
- [conduwuit-bin](https://aur.archlinux.org/packages/conduwuit-bin) - latest tagged conduwuit static binary
|
||||
- [conduwuit](https://aur.archlinux.org/packages/conduwuit) - latest tagged
|
||||
conduwuit
|
||||
- [conduwuit-git](https://aur.archlinux.org/packages/conduwuit-git) - latest git
|
||||
conduwuit from `main` branch
|
||||
- [conduwuit-bin](https://aur.archlinux.org/packages/conduwuit-bin) - latest
|
||||
tagged conduwuit static binary
|
||||
|
||||
@@ -2,32 +2,39 @@ # conduwuit for Docker
|
||||
|
||||
## Docker
|
||||
|
||||
To run conduwuit with Docker you can either build the image yourself or pull it from a registry.
|
||||
To run conduwuit with Docker you can either build the image yourself or pull it
|
||||
from a registry.
|
||||
|
||||
### Use a registry
|
||||
|
||||
OCI images for conduwuit are available in the registries listed below.
|
||||
|
||||
| Registry | Image | Size | Notes |
|
||||
| --------------- | --------------------------------------------------------------- | ----------------------------- | ---------------------- |
|
||||
| GitHub Registry | [ghcr.io/girlbossceo/conduwuit:latest][gh] | ![Image Size][shield-latest] | Stable tagged image. |
|
||||
| GitLab Registry | [registry.gitlab.com/conduwuit/conduwuit:latest][gl] | ![Image Size][shield-latest] | Stable tagged image. |
|
||||
| Docker Hub | [docker.io/girlbossceo/conduwuit:latest][dh] | ![Image Size][shield-latest] | Stable tagged image. |
|
||||
| GitHub Registry | [ghcr.io/girlbossceo/conduwuit:main][gh] | ![Image Size][shield-main] | Stable main branch. |
|
||||
| GitLab Registry | [registry.gitlab.com/conduwuit/conduwuit:main][gl] | ![Image Size][shield-main] | Stable main branch. |
|
||||
| Docker Hub | [docker.io/girlbossceo/conduwuit:main][dh] | ![Image Size][shield-main] | Stable main branch. |
|
||||
| Registry | Image
|
||||
| Size | Notes | | --------------- |
|
||||
--------------------------------------------------------------- |
|
||||
----------------------------- | ---------------------- | | GitHub Registry |
|
||||
[ghcr.io/girlbossceo/conduwuit:latest][gh] | ![Image Size][shield-latest] |
|
||||
Stable tagged image. | | GitLab Registry |
|
||||
[registry.gitlab.com/conduwuit/conduwuit:latest][gl] | ![Image
|
||||
Size][shield-latest] | Stable tagged image. | | Docker Hub |
|
||||
[docker.io/girlbossceo/conduwuit:latest][dh] | ![Image
|
||||
Size][shield-latest] | Stable tagged image. | | GitHub Registry |
|
||||
[ghcr.io/girlbossceo/conduwuit:main][gh] | ![Image Size][shield-main] |
|
||||
Stable main branch. | | GitLab Registry |
|
||||
[registry.gitlab.com/conduwuit/conduwuit:main][gl] | ![Image
|
||||
Size][shield-main] | Stable main branch. | | Docker Hub |
|
||||
[docker.io/girlbossceo/conduwuit:main][dh] | ![Image
|
||||
Size][shield-main] | Stable main branch. |
|
||||
|
||||
[dh]: https://hub.docker.com/repository/docker/girlbossceo/conduwuit
|
||||
[dh]: https://hub.docker.com/r/girlbossceo/conduwuit
|
||||
[gh]: https://github.com/girlbossceo/conduwuit/pkgs/container/conduwuit
|
||||
[gl]: https://gitlab.com/conduwuit/conduwuit/container_registry/6351657
|
||||
[gl]: https://gitlab.com/conduwuit/conduwuit/container_registry/6369729
|
||||
[shield-latest]: https://img.shields.io/docker/image-size/girlbossceo/conduwuit/latest
|
||||
[shield-main]: https://img.shields.io/docker/image-size/girlbossceo/conduwuit/main
|
||||
|
||||
Use
|
||||
|
||||
```bash
|
||||
docker image pull <link>
|
||||
```
|
||||
```bash docker image pull <link> ```
|
||||
|
||||
to pull it to your machine.
|
||||
|
||||
@@ -35,61 +42,77 @@ ### Run
|
||||
|
||||
When you have the image you can simply run it with
|
||||
|
||||
```bash
|
||||
docker run -d -p 8448:6167 \
|
||||
-v db:/var/lib/conduwuit/ \
|
||||
-e CONDUWUIT_SERVER_NAME="your.server.name" \
|
||||
-e CONDUWUIT_DATABASE_BACKEND="rocksdb" \
|
||||
-e CONDUWUIT_ALLOW_REGISTRATION=false \
|
||||
--name conduit <link>
|
||||
```bash
|
||||
docker run -d -p 8448:6167 \
|
||||
-v db:/var/lib/conduwuit/ \
|
||||
-e CONDUWUIT_SERVER_NAME="your.server.name" \
|
||||
-e CONDUWUIT_DATABASE_BACKEND="rocksdb" \
|
||||
-e CONDUWUIT_ALLOW_REGISTRATION=false \
|
||||
--name conduit <link>
|
||||
```
|
||||
|
||||
or you can use [docker compose](#docker-compose).
|
||||
|
||||
The `-d` flag lets the container run in detached mode. You may supply an optional `conduwuit.toml` config file, the example config can be found [here](../configuration/examples.md).
|
||||
You can pass in different env vars to change config values on the fly. You can even configure conduwuit completely by using env vars. For an overview of possible
|
||||
values, please take a look at the [`docker-compose.yml`](docker-compose.yml) file.
|
||||
The `-d` flag lets the container run in detached mode. You may supply an
|
||||
optional `conduwuit.toml` config file, the example config can be found
|
||||
[here](../configuration/examples.md). You can pass in different env vars to
|
||||
change config values on the fly. You can even configure conduwuit completely by
|
||||
using env vars. For an overview of possible values, please take a look at the
|
||||
[`docker-compose.yml`](docker-compose.yml) file.
|
||||
|
||||
If you just want to test conduwuit for a short time, you can use the `--rm` flag, which will clean up everything related to your container after you stop it.
|
||||
If you just want to test conduwuit for a short time, you can use the `--rm`
|
||||
flag, which will clean up everything related to your container after you stop
|
||||
it.
|
||||
|
||||
### Docker-compose
|
||||
|
||||
If the `docker run` command is not for you or your setup, you can also use one of the provided `docker-compose` files.
|
||||
If the `docker run` command is not for you or your setup, you can also use one
|
||||
of the provided `docker-compose` files.
|
||||
|
||||
Depending on your proxy setup, you can use one of the following files;
|
||||
|
||||
- If you already have a `traefik` instance set up, use [`docker-compose.for-traefik.yml`](docker-compose.for-traefik.yml)
|
||||
- If you don't have a `traefik` instance set up and would like to use it, use [`docker-compose.with-traefik.yml`](docker-compose.with-traefik.yml)
|
||||
- If you want a setup that works out of the box with `caddy-docker-proxy`, use [`docker-compose.with-caddy.yml`](docker-compose.with-caddy.yml) and replace all `example.com` placeholders with your own domain
|
||||
- If you already have a `traefik` instance set up, use
|
||||
[`docker-compose.for-traefik.yml`](docker-compose.for-traefik.yml)
|
||||
- If you don't have a `traefik` instance set up and would like to use it, use
|
||||
[`docker-compose.with-traefik.yml`](docker-compose.with-traefik.yml)
|
||||
- If you want a setup that works out of the box with `caddy-docker-proxy`, use
|
||||
[`docker-compose.with-caddy.yml`](docker-compose.with-caddy.yml) and replace all
|
||||
`example.com` placeholders with your own domain
|
||||
- For any other reverse proxy, use [`docker-compose.yml`](docker-compose.yml)
|
||||
|
||||
When picking the traefik-related compose file, rename it so it matches `docker-compose.yml`, and
|
||||
rename the override file to `docker-compose.override.yml`. Edit the latter with the values you want
|
||||
for your server.
|
||||
When picking the traefik-related compose file, rename it so it matches
|
||||
`docker-compose.yml`, and rename the override file to
|
||||
`docker-compose.override.yml`. Edit the latter with the values you want for your
|
||||
server.
|
||||
|
||||
When picking the `caddy-docker-proxy` compose file, it's important to first create the `caddy` network before spinning up the containers:
|
||||
When picking the `caddy-docker-proxy` compose file, it's important to first
|
||||
create the `caddy` network before spinning up the containers:
|
||||
|
||||
```bash
|
||||
docker network create caddy
|
||||
```
|
||||
```bash docker network create caddy ```
|
||||
|
||||
After that, you can rename it so it matches `docker-compose.yml` and spin up the containers!
|
||||
After that, you can rename it so it matches `docker-compose.yml` and spin up the
|
||||
containers!
|
||||
|
||||
Additional info about deploying conduwuit can be found [here](generic.md).
|
||||
|
||||
### Build
|
||||
|
||||
To build the conduwuit image with docker-compose, you first need to open and modify the `docker-compose.yml` file. There you need to comment the `image:` option and uncomment the `build:` option. Then call docker compose with:
|
||||
To build the conduwuit image with docker-compose, you first need to open and
|
||||
modify the `docker-compose.yml` file. There you need to comment the `image:`
|
||||
option and uncomment the `build:` option. Then call docker compose with:
|
||||
|
||||
```bash
|
||||
```bash
|
||||
docker compose up
|
||||
```
|
||||
|
||||
This will also start the container right afterwards, so if want it to run in detached mode, you also should use the `-d` flag.
|
||||
This will also start the container right afterwards, so if want it to run in
|
||||
detached mode, you also should use the `-d` flag.
|
||||
|
||||
### Run
|
||||
|
||||
If you already have built the image or want to use one from the registries, you can just start the container and everything else in the compose file in detached mode with:
|
||||
If you already have built the image or want to use one from the registries, you
|
||||
can just start the container and everything else in the compose file in detached
|
||||
mode with:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
@@ -99,18 +122,21 @@ ### Run
|
||||
|
||||
### Use Traefik as Proxy
|
||||
|
||||
As a container user, you probably know about Traefik. It is a easy to use reverse proxy for making
|
||||
containerized app and services available through the web. With the two provided files,
|
||||
As a container user, you probably know about Traefik. It is a easy to use
|
||||
reverse proxy for making containerized app and services available through the
|
||||
web. With the two provided files,
|
||||
[`docker-compose.for-traefik.yml`](docker-compose.for-traefik.yml) (or
|
||||
[`docker-compose.with-traefik.yml`](docker-compose.with-traefik.yml)) and
|
||||
[`docker-compose.override.yml`](docker-compose.override.yml), it is equally easy to deploy
|
||||
and use conduwuit, with a little caveat. If you already took a look at the files, then you should have
|
||||
seen the `well-known` service, and that is the little caveat. Traefik is simply a proxy and
|
||||
loadbalancer and is not able to serve any kind of content, but for conduwuit to federate, we need to
|
||||
either expose ports `443` and `8448` or serve two endpoints `.well-known/matrix/client` and
|
||||
`.well-known/matrix/server`.
|
||||
[`docker-compose.override.yml`](docker-compose.override.yml), it is equally easy
|
||||
to deploy and use conduwuit, with a little caveat. If you already took a look at
|
||||
the files, then you should have seen the `well-known` service, and that is the
|
||||
little caveat. Traefik is simply a proxy and loadbalancer and is not able to
|
||||
serve any kind of content, but for conduwuit to federate, we need to either
|
||||
expose ports `443` and `8448` or serve two endpoints `.well-known/matrix/client`
|
||||
and `.well-known/matrix/server`.
|
||||
|
||||
With the service `well-known` we use a single `nginx` container that will serve those two files.
|
||||
With the service `well-known` we use a single `nginx` container that will serve
|
||||
those two files.
|
||||
|
||||
## Voice communication
|
||||
|
||||
|
||||
11
docs/deploying/freebsd.md
Normal file
11
docs/deploying/freebsd.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# conduwuit for FreeBSD
|
||||
|
||||
conduwuit at the moment does not provide FreeBSD builds. Building conduwuit on
|
||||
FreeBSD requires a specific environment variable to use the system prebuilt
|
||||
RocksDB library instead of rust-rocksdb / rust-librocksdb-sys which does *not*
|
||||
work and will cause a build error or coredump.
|
||||
|
||||
Use the following environment variable: `ROCKSDB_LIB_DIR=/usr/local/lib`
|
||||
|
||||
Such example commandline with it can be: `ROCKSDB_LIB_DIR=/usr/local/lib cargo
|
||||
build --release`
|
||||
@@ -2,127 +2,140 @@ # Generic deployment documentation
|
||||
|
||||
> ## Getting help
|
||||
>
|
||||
> If you run into any problems while setting up conduwuit, ask us
|
||||
> in `#conduwuit:puppygock.gay` or [open an issue on GitHub](https://github.com/girlbossceo/conduwuit/issues/new).
|
||||
> If you run into any problems while setting up conduwuit, ask us in
|
||||
> `#conduwuit:puppygock.gay` or [open an issue on
|
||||
> GitHub](https://github.com/girlbossceo/conduwuit/issues/new).
|
||||
|
||||
## Installing conduwuit
|
||||
|
||||
You may simply download the binary that fits your machine. Run `uname -m` to see what you need.
|
||||
You may simply download the binary that fits your machine. Run `uname -m` to see
|
||||
what you need.
|
||||
|
||||
Prebuilt binaries can be downloaded from the latest tagged release [here](https://github.com/girlbossceo/conduwuit/releases/latest).
|
||||
Prebuilt fully static musl binaries can be downloaded from the latest tagged
|
||||
release [here](https://github.com/girlbossceo/conduwuit/releases/latest) or
|
||||
`main` CI branch workflow artifact output. These also include Debian packages.
|
||||
These binaries have jemalloc and io_uring statically linked and included with
|
||||
them.
|
||||
|
||||
The latest tagged release also includes the Debian packages.
|
||||
|
||||
Alternatively, you may compile the binary yourself. We recommend using [Lix](https://lix.systems) to build conduwuit as this has the most guaranteed
|
||||
Alternatively, you may compile the binary yourself. We recommend using
|
||||
[Lix](https://lix.systems) to build conduwuit as this has the most guaranteed
|
||||
reproducibiltiy and easiest to get a build environment and output going.
|
||||
|
||||
Otherwise, follow standard Rust project build guides (installing git and cloning the repo, getting the Rust toolchain via rustup, installing LLVM toolchain + libclang, installing liburing for io_uring and RocksDB, etc).
|
||||
Otherwise, follow standard Rust project build guides (installing git and cloning
|
||||
the repo, getting the Rust toolchain via rustup, installing LLVM toolchain +
|
||||
libclang for RocksDB, installing liburing for io_uring and RocksDB, etc).
|
||||
|
||||
## Adding a conduwuit user
|
||||
|
||||
While conduwuit can run as any user it is better to use dedicated users for different services. This also allows
|
||||
you to make sure that the file permissions are correctly set up.
|
||||
While conduwuit can run as any user it is better to use dedicated users for
|
||||
different services. This also allows you to make sure that the file permissions
|
||||
are correctly set up.
|
||||
|
||||
In Debian or Fedora/RHEL, you can use this command to create a conduwuit user:
|
||||
|
||||
```bash
|
||||
sudo adduser --system conduwuit --group --disabled-login --no-create-home
|
||||
sudo adduser --system conduwuit --group --disabled-login --no-create-home
|
||||
```
|
||||
|
||||
For distros without `adduser`:
|
||||
|
||||
```bash
|
||||
sudo useradd -r --shell /usr/bin/nologin --no-create-home conduwuit
|
||||
```
|
||||
```bash sudo useradd -r --shell /usr/bin/nologin --no-create-home conduwuit ```
|
||||
|
||||
## Forwarding ports in the firewall or the router
|
||||
|
||||
conduwuit uses the ports 443 and 8448 both of which need to be open in the firewall.
|
||||
conduwuit uses the ports 443 and 8448 both of which need to be open in the
|
||||
firewall.
|
||||
|
||||
If conduwuit runs behind a router or in a container and has a different public IP address than the host system these public ports need to be forwarded directly or indirectly to the port mentioned in the config.
|
||||
If conduwuit runs behind a router or in a container and has a different public
|
||||
IP address than the host system these public ports need to be forwarded directly
|
||||
or indirectly to the port mentioned in the config.
|
||||
|
||||
## Setting up a systemd service
|
||||
|
||||
The systemd unit for conduwuit can be found [here](../configuration/examples.md#example-systemd-unit-file). You may need to change the `ExecStart=` path to where you placed the conduwuit binary.
|
||||
The systemd unit for conduwuit can be found
|
||||
[here](../configuration/examples.md#example-systemd-unit-file). You may need to
|
||||
change the `ExecStart=` path to where you placed the conduwuit binary.
|
||||
|
||||
## Creating the conduwuit configuration file
|
||||
|
||||
Now we need to create the conduwuit's config file in `/etc/conduwuit/conduwuit.toml`. The example config can be found at [conduwuit-example.toml](../configuration/examples.md).**Please take a moment to read it. You need to change at least the server name.**
|
||||
Now we need to create the conduwuit's config file in
|
||||
`/etc/conduwuit/conduwuit.toml`. The example config can be found at
|
||||
[conduwuit-example.toml](../configuration/examples.md).**Please take a moment to
|
||||
read it. You need to change at least the server name.**
|
||||
|
||||
RocksDB is the only supported database backend.
|
||||
|
||||
## Setting the correct file permissions
|
||||
|
||||
If you are using a dedicated user for conduwuit, you will need to allow it to read the config. To do that you can run this:
|
||||
If you are using a dedicated user for conduwuit, you will need to allow it to
|
||||
read the config. To do that you can run this:
|
||||
|
||||
```bash
|
||||
sudo chown -R root:root /etc/conduwuit
|
||||
sudo chmod -R 755 /etc/conduwuit
|
||||
sudo chown -R root:root /etc/conduwuit sudo chmod -R 755 /etc/conduwuit
|
||||
```
|
||||
|
||||
If you use the default database path you also need to run this:
|
||||
|
||||
```bash
|
||||
sudo mkdir -p /var/lib/conduwuit/
|
||||
sudo chown -R conduwuit:conduwuit /var/lib/conduwuit/
|
||||
sudo chmod 700 /var/lib/conduwuit/
|
||||
```bash
|
||||
sudo mkdir -p /var/lib/conduwuit/ sudo chown -R conduwuit:conduwuit
|
||||
/var/lib/conduwuit/ sudo chmod 700 /var/lib/conduwuit/
|
||||
```
|
||||
|
||||
## Setting up the Reverse Proxy
|
||||
|
||||
Refer to the documentation or various guides online of your chosen reverse proxy software. A [Caddy](https://caddyserver.com/) example will be provided as this is the recommended reverse proxy for new users and is very trivial to use (handles TLS, reverse proxy headers, etc transparently with proper defaults).
|
||||
Refer to the documentation or various guides online of your chosen reverse proxy
|
||||
software. A [Caddy](https://caddyserver.com/) example will be provided as this
|
||||
is the recommended reverse proxy for new users and is very trivial to use
|
||||
(handles TLS, reverse proxy headers, etc transparently with proper defaults).
|
||||
|
||||
Lighttpd is not supported as it seems to mess with the `X-Matrix` Authorization header, making federation non-functional. If using Apache, you need to use `nocanon` to prevent this.
|
||||
Lighttpd is not supported as it seems to mess with the `X-Matrix` Authorization
|
||||
header, making federation non-functional. If using Apache, you need to use
|
||||
`nocanon` to prevent this.
|
||||
|
||||
### Caddy
|
||||
|
||||
Create `/etc/caddy/conf.d/conduwuit_caddyfile` and enter this (substitute for your server name).
|
||||
Create `/etc/caddy/conf.d/conduwuit_caddyfile` and enter this (substitute for
|
||||
your server name).
|
||||
|
||||
```caddy
|
||||
your.server.name, your.server.name:8448 {
|
||||
# TCP
|
||||
reverse_proxy 127.0.0.1:6167
|
||||
|
||||
# UNIX socket
|
||||
#reverse_proxy unix//run/conduwuit/conduwuit.sock
|
||||
your.server.name, your.server.name:8448 { # TCP reverse_proxy
|
||||
127.0.0.1:6167
|
||||
# UNIX socket
|
||||
#reverse_proxy unix//run/conduwuit/conduwuit.sock
|
||||
}
|
||||
```
|
||||
|
||||
That's it! Just start and enable the service and you're set.
|
||||
|
||||
```bash
|
||||
sudo systemctl enable --now caddy
|
||||
```
|
||||
```bash sudo systemctl enable --now caddy ```
|
||||
|
||||
## You're done
|
||||
|
||||
Now you can start conduwuit with:
|
||||
|
||||
```bash
|
||||
sudo systemctl start conduwuit
|
||||
```
|
||||
```bash sudo systemctl start conduwuit ```
|
||||
|
||||
Set it to start automatically when your system boots with:
|
||||
|
||||
```bash
|
||||
sudo systemctl enable conduwuit
|
||||
```
|
||||
```bash sudo systemctl enable conduwuit ```
|
||||
|
||||
## How do I know it works?
|
||||
|
||||
You can open [a Matrix client](https://matrix.org/ecosystem/clients), enter your homeserver and try to register.
|
||||
You can open [a Matrix client](https://matrix.org/ecosystem/clients), enter your
|
||||
homeserver and try to register.
|
||||
|
||||
You can also use these commands as a quick health check (replace `your.server.name`).
|
||||
You can also use these commands as a quick health check (replace
|
||||
`your.server.name`).
|
||||
|
||||
```bash
|
||||
$ curl https://your.server.name/_conduwuit/server_version
|
||||
```bash $ curl https://your.server.name/_conduwuit/server_version
|
||||
|
||||
# If using port 8448
|
||||
$ curl https://your.server.name:8448/_conduwuit/server_version
|
||||
```
|
||||
# If using port 8448 $ curl
|
||||
https://your.server.name:8448/_conduwuit/server_version ```
|
||||
|
||||
- To check if your server can talk with other homeservers, you can use the [Matrix Federation Tester](https://federationtester.matrix.org/).
|
||||
If you can register but cannot join federated rooms check your config again and also check if the port 8448 is open and forwarded correctly.
|
||||
- To check if your server can talk with other homeservers, you can use the
|
||||
[Matrix Federation Tester](https://federationtester.matrix.org/). If you can
|
||||
register but cannot join federated rooms check your config again and also check
|
||||
if the port 8448 is open and forwarded correctly.
|
||||
|
||||
# What's next?
|
||||
|
||||
@@ -132,4 +145,5 @@ ## Audio/Video calls
|
||||
|
||||
## Appservices
|
||||
|
||||
If you want to set up an appservice, take a look at the [Appservice Guide](../appservices.md).
|
||||
If you want to set up an appservice, take a look at the [Appservice
|
||||
Guide](../appservices.md).
|
||||
|
||||
@@ -9,31 +9,29 @@ # conduwuit for NixOS
|
||||
A binary cache for conduwuit that the CI/CD publishes to is available at the
|
||||
following places (both are the same just different names):
|
||||
|
||||
```
|
||||
https://attic.kennel.juneis.dog/conduit
|
||||
``` https://attic.kennel.juneis.dog/conduit
|
||||
conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk=
|
||||
|
||||
https://attic.kennel.juneis.dog/conduwuit
|
||||
conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE=
|
||||
```
|
||||
conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE= ```
|
||||
|
||||
The binary caches have been recreated recently due to attic issues. The old public keys were:
|
||||
The binary caches have been recreated recently due to attic issues. The old
|
||||
public keys were:
|
||||
|
||||
```
|
||||
conduit:Isq8FGyEC6FOXH6nD+BOeAA+bKp6X6UIbupSlGEPuOg=
|
||||
``` conduit:Isq8FGyEC6FOXH6nD+BOeAA+bKp6X6UIbupSlGEPuOg=
|
||||
|
||||
conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=
|
||||
```
|
||||
conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw= ```
|
||||
|
||||
If specifying a URL in your flake, please use the GitHub remote: `github:girlbossceo/conduwuit`
|
||||
If specifying a URL in your flake, please use the GitHub remote:
|
||||
`github:girlbossceo/conduwuit`
|
||||
|
||||
The `flake.nix` and `default.nix` do not (currently) provide a NixOS module, so
|
||||
(for now) [`services.matrix-conduit`][module] from Nixpkgs should be used to
|
||||
configure conduwuit.
|
||||
|
||||
If you want to run the latest code, you should get conduwuit from the `flake.nix`
|
||||
or `default.nix` and set [`services.matrix-conduit.package`][package]
|
||||
appropriately.
|
||||
If you want to run the latest code, you should get conduwuit from the
|
||||
`flake.nix` or `default.nix` and set
|
||||
[`services.matrix-conduit.package`][package] appropriately.
|
||||
|
||||
[lix]: https://lix.systems/
|
||||
[module]: https://search.nixos.org/options?channel=unstable&query=services.matrix-conduit
|
||||
|
||||
@@ -4,19 +4,50 @@ # Development
|
||||
it, you can safely ignore this section. If you plan on contributing, see the
|
||||
[contributor's guide](contributing.md).
|
||||
|
||||
## List of forked dependencies During conduwuit development, we have had to fork
|
||||
some dependencies to support our use-cases in some areas. This ranges from
|
||||
things said upstream project won't accept for any reason, faster-paced
|
||||
development (unresponsive or slow upstream), conduwuit-specific usecases, or
|
||||
lack of time to upstream some things.
|
||||
|
||||
- [ruma/ruma][1]: <https://github.com/girlbossceo/ruwuma> - various performance
|
||||
improvements, more features, faster-paced development, client/server interop
|
||||
hacks upstream won't accept, etc
|
||||
- [facebook/rocksdb][2]: <https://github.com/girlbossceo/rocksdb> - liburing
|
||||
build fixes, GCC build fix, and logging callback C API for Rust tracing
|
||||
integration
|
||||
- [tikv/jemallocator][3]: <https://github.com/girlbossceo/jemallocator> - musl
|
||||
builds seem to be broken on upstream
|
||||
- [zyansheep/rustyline-async][4]:
|
||||
<https://github.com/girlbossceo/rustyline-async> - tab completion callback and
|
||||
`CTRL+\` signal quit event for CLI
|
||||
- [rust-rocksdb/rust-rocksdb][5]:
|
||||
<https://github.com/girlbossceo/rust-rocksdb-zaidoon1> - [`@zaidoon1`'s][8] fork
|
||||
has quicker updates, more up to date dependencies. Our changes fix musl build
|
||||
issues, Rust part of the logging callback C API, removes unnecessary `gtest`
|
||||
include, and uses our RocksDB and jemallocator
|
||||
- [tokio-rs/tracing][6]: <https://github.com/girlbossceo/tracing> - Implements
|
||||
`Clone` for `EnvFilter` to support dynamically changing tracing envfilter's
|
||||
alongside other logging/metrics things
|
||||
|
||||
## Debugging with `tokio-console`
|
||||
|
||||
[`tokio-console`][1] can be a useful tool for debugging and profiling. To make
|
||||
a `tokio-console`-enabled build of conduwuit, enable the `tokio_console` feature,
|
||||
disable the default `release_max_log_level` feature, and set the
|
||||
`--cfg tokio_unstable` flag to enable experimental tokio APIs. A build might
|
||||
look like this:
|
||||
[`tokio-console`][7] can be a useful tool for debugging and profiling. To make a
|
||||
`tokio-console`-enabled build of conduwuit, enable the `tokio_console` feature,
|
||||
disable the default `release_max_log_level` feature, and set the `--cfg
|
||||
tokio_unstable` flag to enable experimental tokio APIs. A build might look like
|
||||
this:
|
||||
|
||||
```bash
|
||||
RUSTFLAGS="--cfg tokio_unstable" cargo build \
|
||||
--release \
|
||||
--no-default-features \
|
||||
--features=systemd,element_hacks,gzip_compression,brotli_compression,zstd_compression,tokio_console
|
||||
```bash RUSTFLAGS="--cfg tokio_unstable" cargo build \ --release \
|
||||
--no-default-features \
|
||||
--features=systemd,element_hacks,gzip_compression,brotli_compression,zstd_compression,tokio_console
|
||||
```
|
||||
|
||||
[1]: https://docs.rs/tokio-console/latest/tokio_console/
|
||||
[1]: https://github.com/ruma/ruma/
|
||||
[2]: https://github.com/facebook/rocksdb/
|
||||
[3]: https://github.com/tikv/jemallocator/
|
||||
[4]: https://github.com/zyansheep/rustyline-async/
|
||||
[5]: https://github.com/rust-rocksdb/rust-rocksdb/
|
||||
[6]: https://github.com/tokio-rs/tracing/
|
||||
[7]: https://docs.rs/tokio-console/latest/tokio_console/
|
||||
[8]: https://github.com/zaidoon1/
|
||||
|
||||
@@ -2,89 +2,190 @@ # Hot Reloading ("Live" Development)
|
||||
|
||||
### Summary
|
||||
|
||||
When developing in debug-builds with the nightly toolchain, conduwuit is modular using dynamic libraries and various parts of the application are hot-reloadable while the server is running: http api handlers, admin commands, services, database, etc. These are all split up into individual workspace crates as seen in the `src/` directory. Changes to sourcecode in a crate rebuild that crate and subsequent crates depending on it. Reloading then occurs for the changed crates.
|
||||
When developing in debug-builds with the nightly toolchain, conduwuit is modular
|
||||
using dynamic libraries and various parts of the application are hot-reloadable
|
||||
while the server is running: http api handlers, admin commands, services,
|
||||
database, etc. These are all split up into individual workspace crates as seen
|
||||
in the `src/` directory. Changes to sourcecode in a crate rebuild that crate and
|
||||
subsequent crates depending on it. Reloading then occurs for the changed crates.
|
||||
|
||||
Release builds still produce static binaries which are unaffected. Rust's soundness guarantees are in full force. Thus you cannot hot-reload release binaries.
|
||||
Release builds still produce static binaries which are unaffected. Rust's
|
||||
soundness guarantees are in full force. Thus you cannot hot-reload release
|
||||
binaries.
|
||||
|
||||
### Requirements
|
||||
|
||||
Currently, this development setup only works on x86_64 and aarch64 Linux glibc. [musl explicitly does not support hot reloadable libraries, and does not implement `dlclose`][2]. macOS does not fully support our usage of `RTLD_GLOBAL` possibly due to some thread-local issues. [This Rust issue][3] may be of relevance, specifically [this comment][4]. It may be possible to get it working on only very modern macOS versions such as at least Sonoma, as currently loading dylibs is supported, but not unloading them in our setup, and the cited comment mentions an Apple WWDC confirming there have been TLS changes to somewhat make this possible.
|
||||
Currently, this development setup only works on x86_64 and aarch64 Linux glibc.
|
||||
[musl explicitly does not support hot reloadable libraries, and does not
|
||||
implement `dlclose`][2]. macOS does not fully support our usage of `RTLD_GLOBAL`
|
||||
possibly due to some thread-local issues. [This Rust issue][3] may be of
|
||||
relevance, specifically [this comment][4]. It may be possible to get it working
|
||||
on only very modern macOS versions such as at least Sonoma, as currently loading
|
||||
dylibs is supported, but not unloading them in our setup, and the cited comment
|
||||
mentions an Apple WWDC confirming there have been TLS changes to somewhat make
|
||||
this possible.
|
||||
|
||||
As mentioned above this requires the nightly toolchain. This is due to reliance on various Cargo.toml features that are only available on nightly, most specifically `RUSTFLAGS` in Cargo.toml. Some of the implementation could also be simpler based on other various nightly features. We hope lots of nightly features start making it out of nightly sooner as there have been dozens of very helpful features that have been stuck in nightly ("unstable") for at least 5+ years that would make this simpler. We encourage greater community consensus to move these features into stability.
|
||||
As mentioned above this requires the nightly toolchain. This is due to reliance
|
||||
on various Cargo.toml features that are only available on nightly, most
|
||||
specifically `RUSTFLAGS` in Cargo.toml. Some of the implementation could also be
|
||||
simpler based on other various nightly features. We hope lots of nightly
|
||||
features start making it out of nightly sooner as there have been dozens of very
|
||||
helpful features that have been stuck in nightly ("unstable") for at least 5+
|
||||
years that would make this simpler. We encourage greater community consensus to
|
||||
move these features into stability.
|
||||
|
||||
This currently only works on x86_64/aarch64 Linux with a glibc C library. musl C library, macOS, and likely other host architectures are not supported (if other architectures work, feel free to let us know and/or make a PR updating this). This should work on GNU ld and lld (rust-lld) and gcc/clang, however if you happen to have linker issues it's recommended to try using `mold` or `gold` linkers, and please let us know in the [conduwuit Matrix room][7] the linker error and what linker solved this issue so we can figure out a solution. Ideally there should be minimal friction to using this, and in the future a build script (`build.rs`) may be suitable to making this easier to use if the capabilities allow us.
|
||||
This currently only works on x86_64/aarch64 Linux with a glibc C library. musl C
|
||||
library, macOS, and likely other host architectures are not supported (if other
|
||||
architectures work, feel free to let us know and/or make a PR updating this).
|
||||
This should work on GNU ld and lld (rust-lld) and gcc/clang, however if you
|
||||
happen to have linker issues it's recommended to try using `mold` or `gold`
|
||||
linkers, and please let us know in the [conduwuit Matrix room][7] the linker
|
||||
error and what linker solved this issue so we can figure out a solution. Ideally
|
||||
there should be minimal friction to using this, and in the future a build script
|
||||
(`build.rs`) may be suitable to making this easier to use if the capabilities
|
||||
allow us.
|
||||
|
||||
### Usage
|
||||
|
||||
As of 19 May 2024, the instructions for using this are:
|
||||
|
||||
0. Have patience. Don't hesitate to join the [conduwuit Matrix room][7] to receive help using this. As indicated by the various rustflags used and some of the interesting issues linked at the bottom, this is definitely not something the Rust ecosystem or toolchain is used to doing.
|
||||
0. Have patience. Don't hesitate to join the [conduwuit Matrix room][7] to
|
||||
receive help using this. As indicated by the various rustflags used and some
|
||||
of the interesting issues linked at the bottom, this is definitely not something
|
||||
the Rust ecosystem or toolchain is used to doing.
|
||||
|
||||
1. Install the nightly toolchain using rustup. You may need to use `rustup override set nightly` in your local conduwuit directory, or use `cargo +nightly` for all actions.
|
||||
1. Install the nightly toolchain using rustup. You may need to use `rustup
|
||||
override set nightly` in your local conduwuit directory, or use `cargo
|
||||
+nightly` for all actions.
|
||||
|
||||
2. Uncomment `cargo-features` at the top level / root Cargo.toml
|
||||
|
||||
3. Scroll down to the `# Developer profile` section and uncomment ALL the rustflags for each dev profile and their respective packages.
|
||||
3. Scroll down to the `# Developer profile` section and uncomment ALL the
|
||||
rustflags for each dev profile and their respective packages.
|
||||
|
||||
4. In each workspace crate's Cargo.toml (everything under `src/*` AND `deps/rust-rocksdb/Cargo.toml`), uncomment the `dylib` crate type under `[lib]`.
|
||||
4. In each workspace crate's Cargo.toml (everything under `src/*` AND
|
||||
`deps/rust-rocksdb/Cargo.toml`), uncomment the `dylib` crate type under
|
||||
`[lib]`.
|
||||
|
||||
5. Due to [this rpath issue][5], you must export the `LD_LIBRARY_PATH` environment variable to your nightly Rust toolchain library directory. If using rustup (hopefully), use this: `export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/`
|
||||
5. Due to [this rpath issue][5], you must export the `LD_LIBRARY_PATH`
|
||||
environment variable to your nightly Rust toolchain library directory. If
|
||||
using rustup (hopefully), use this: `export
|
||||
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/`
|
||||
|
||||
6. Start the server. You can use `cargo +nightly run` for this along with the standard.
|
||||
6. Start the server. You can use `cargo +nightly run` for this along with the
|
||||
standard.
|
||||
|
||||
7. Make some changes where you need to.
|
||||
|
||||
8. In a separate terminal window in the same directory (or using a terminal multiplexer like tmux), run the *build* Cargo command `cargo +nightly build`. Cargo should only rebuild what was changed / what's necessary, so it should not be rebuilding all the crates.
|
||||
8. In a separate terminal window in the same directory (or using a terminal
|
||||
multiplexer like tmux), run the *build* Cargo command `cargo +nightly build`.
|
||||
Cargo should only rebuild what was changed / what's necessary, so it should
|
||||
not be rebuilding all the crates.
|
||||
|
||||
9. In your conduwuit server terminal, hit/send `CTRL+C` signal. This will tell conduwuit to find which libraries need to be reloaded, and reloads them as necessary.
|
||||
9. In your conduwuit server terminal, hit/send `CTRL+C` signal. This will tell
|
||||
conduwuit to find which libraries need to be reloaded, and reloads them as
|
||||
necessary.
|
||||
|
||||
10. If there were no errors, it will tell you it successfully reloaded `#` modules, and your changes should now be visible. Repeat 7 - 9 as needed.
|
||||
10. If there were no errors, it will tell you it successfully reloaded `#`
|
||||
modules, and your changes should now be visible. Repeat 7 - 9 as needed.
|
||||
|
||||
To shutdown conduwuit in this setup, hit/send `CTRL+\`. Normal builds still shutdown with `CTRL+C` as usual.
|
||||
To shutdown conduwuit in this setup, hit/send `CTRL+\`. Normal builds still
|
||||
shutdown with `CTRL+C` as usual.
|
||||
|
||||
Steps 1 - 5 are the initial first-time steps for using this. To remove the hot reload setup, revert/comment all the Cargo.toml changes.
|
||||
Steps 1 - 5 are the initial first-time steps for using this. To remove the hot
|
||||
reload setup, revert/comment all the Cargo.toml changes.
|
||||
|
||||
As mentioned in the requirements section, if you happen to have some linker issues, try using the `-fuse-ld=` rustflag and specify mold or gold in all the `rustflags` definitions in the top level Cargo.toml, and please let us know in the [conduwuit Matrix room][7] the problem. mold can be installed typically through your distro, and gold is provided by the binutils package.
|
||||
As mentioned in the requirements section, if you happen to have some linker
|
||||
issues, try using the `-fuse-ld=` rustflag and specify mold or gold in all the
|
||||
`rustflags` definitions in the top level Cargo.toml, and please let us know in
|
||||
the [conduwuit Matrix room][7] the problem. mold can be installed typically
|
||||
through your distro, and gold is provided by the binutils package.
|
||||
|
||||
It's possible a helper script can be made to do all of this, or most preferably a specially made build script (build.rs). `cargo watch` support will be implemented soon which will eliminate the need to manually run `cargo build` all together.
|
||||
It's possible a helper script can be made to do all of this, or most preferably
|
||||
a specially made build script (build.rs). `cargo watch` support will be
|
||||
implemented soon which will eliminate the need to manually run `cargo build` all
|
||||
together.
|
||||
|
||||
### Addendum
|
||||
|
||||
Conduit was inherited as a single crate without modularity or reloading in its design. Reasonable partitioning and abstraction allowed a split into several crates, though many circular dependencies had to be corrected. The resulting crates now form a directed graph as depicted in figures below. The interfacing between these crates is still extremely broad which is not mitigable.
|
||||
Conduit was inherited as a single crate without modularity or reloading in its
|
||||
design. Reasonable partitioning and abstraction allowed a split into several
|
||||
crates, though many circular dependencies had to be corrected. The resulting
|
||||
crates now form a directed graph as depicted in figures below. The interfacing
|
||||
between these crates is still extremely broad which is not mitigable.
|
||||
|
||||
Initially [hot_lib_reload][6] was investigated but found appropriate for a project designed with modularity through limited interfaces, not a large and complex existing codebase. Instead a bespoke solution built directly on [libloading][8] satisfied our constraints. This required relatively minimal modifications and zero maintenance burden compared to what would be required otherwise. The technical difference lies with relocation processing: we leverage global bindings (`RTLD_GLOBAL`) in a very intentional way. Most libraries and off-the-shelf module systems (such as [hot_lib_reload][6]) restrict themselves to local bindings (`RTLD_LOCAL`). This allows them to release software to multiple platforms with much greater consistency, but at the cost of burdening applications to explicitly manage these bindings. In our case with an optional feature for developers, we shrug any such requirement to enjoy the cost/benefit on platforms where global relocations are properly cooperative.
|
||||
Initially [hot_lib_reload][6] was investigated but found appropriate for a
|
||||
project designed with modularity through limited interfaces, not a large and
|
||||
complex existing codebase. Instead a bespoke solution built directly on
|
||||
[libloading][8] satisfied our constraints. This required relatively minimal
|
||||
modifications and zero maintenance burden compared to what would be required
|
||||
otherwise. The technical difference lies with relocation processing: we leverage
|
||||
global bindings (`RTLD_GLOBAL`) in a very intentional way. Most libraries and
|
||||
off-the-shelf module systems (such as [hot_lib_reload][6]) restrict themselves
|
||||
to local bindings (`RTLD_LOCAL`). This allows them to release software to
|
||||
multiple platforms with much greater consistency, but at the cost of burdening
|
||||
applications to explicitly manage these bindings. In our case with an optional
|
||||
feature for developers, we shrug any such requirement to enjoy the cost/benefit
|
||||
on platforms where global relocations are properly cooperative.
|
||||
|
||||
To make use of `RTLD_GLOBAL` the application has to be oriented as a directed acyclic graph. The primary rule is simple and illustrated in the figure below: **no crate is allowed to call a function or use a variable from a crate below it.**
|
||||
To make use of `RTLD_GLOBAL` the application has to be oriented as a directed
|
||||
acyclic graph. The primary rule is simple and illustrated in the figure below:
|
||||
**no crate is allowed to call a function or use a variable from a crate below
|
||||
it.**
|
||||
|
||||

|
||||

|
||||
|
||||
When a symbol is referenced between crates they become bound: **crates cannot be unloaded until their calling crates are first unloaded.** Thus we start the reloading process from the crate which has no callers. There is a small problem though: the first crate is called by the base executable itself! This is solved by using an `RTLD_LOCAL` binding for just one link between the main executable and the first crate, freeing the executable from all modules as no global binding ever occurs between them.
|
||||
When a symbol is referenced between crates they become bound: **crates cannot be
|
||||
unloaded until their calling crates are first unloaded.** Thus we start the
|
||||
reloading process from the crate which has no callers. There is a small problem
|
||||
though: the first crate is called by the base executable itself! This is solved
|
||||
by using an `RTLD_LOCAL` binding for just one link between the main executable
|
||||
and the first crate, freeing the executable from all modules as no global
|
||||
binding ever occurs between them.
|
||||
|
||||

|
||||

|
||||
|
||||
Proper resource management is essential for reliable reloading to occur. This is a very basic ask in RAII-idiomatic Rust and the exposure to reloading hazards is remarkably low, generally stemming from poor patterns and practices. Unfortunately static analysis doesn't enforce reload-safety programmatically (though it could one day), for now hazards can be avoided by knowing a few basic do's and dont's:
|
||||
Proper resource management is essential for reliable reloading to occur. This is
|
||||
a very basic ask in RAII-idiomatic Rust and the exposure to reloading hazards is
|
||||
remarkably low, generally stemming from poor patterns and practices.
|
||||
Unfortunately static analysis doesn't enforce reload-safety programmatically
|
||||
(though it could one day), for now hazards can be avoided by knowing a few basic
|
||||
do's and dont's:
|
||||
|
||||
1. Understand that code is memory. Just like one is forbidden from referencing free'd memory, one must not transfer control to free'd code. Exposure to this is primarily from two things:
|
||||
1. Understand that code is memory. Just like one is forbidden from referencing
|
||||
free'd memory, one must not transfer control to free'd code. Exposure to this
|
||||
is primarily from two things:
|
||||
|
||||
- Callbacks, which this project makes very little use of.
|
||||
- Async tasks, which are addressed below.
|
||||
- Callbacks, which this project makes very little use of.
|
||||
- Async tasks, which are addressed below.
|
||||
|
||||
2. Tie all resources to a scope or object lifetime with greatest possible symmetry (locality). For our purposes this applies to code resources, which means async blocks and tokio tasks.
|
||||
2. Tie all resources to a scope or object lifetime with greatest possible
|
||||
symmetry (locality). For our purposes this applies to code resources, which
|
||||
means async blocks and tokio tasks.
|
||||
|
||||
- **Never spawn a task without receiving and storing its JoinHandle**.
|
||||
- **Always wait on join handles** before leaving a scope or in another cleanup function called by an owning scope.
|
||||
- **Never spawn a task without receiving and storing its JoinHandle**.
|
||||
- **Always wait on join handles** before leaving a scope or in another cleanup
|
||||
function called by an owning scope.
|
||||
|
||||
3. Know any minor specific quirks documented in code or here:
|
||||
|
||||
- Don't use `tokio::spawn`, instead use our `Handle` in `core/server.rs`, which is reachable in most of the codebase via `services()` or other state. This is due to some bugs or assumptions made in tokio, as it happens in `unsafe {}` blocks, which are mitigated by circumventing some thread-local variables. Using runtime handles is good practice in any case.
|
||||
- Don't use `tokio::spawn`, instead use our `Handle` in `core/server.rs`, which
|
||||
is reachable in most of the codebase via `services()` or other state. This is
|
||||
due to some bugs or assumptions made in tokio, as it happens in `unsafe {}`
|
||||
blocks, which are mitigated by circumventing some thread-local variables. Using
|
||||
runtime handles is good practice in any case.
|
||||
|
||||
The initial implementation PR is available [here][1].
|
||||
|
||||
### Interesting related issues/bugs
|
||||
|
||||
- [DT_RUNPATH produced in binary with rpath = true is wrong (cargo)][5]
|
||||
- [Disabling MIR Optimization in Rust Compilation (cargo)](https://internals.rust-lang.org/t/disabling-mir-optimization-in-rust-compilation/19066/5)
|
||||
- [Workspace-level metadata (cargo-deb)](https://github.com/kornelski/cargo-deb/issues/68)
|
||||
- [Disabling MIR Optimization in Rust Compilation
|
||||
(cargo)](https://internals.rust-lang.org/t/disabling-mir-optimization-in-rust-compilation/19066/5)
|
||||
- [Workspace-level metadata
|
||||
(cargo-deb)](https://github.com/kornelski/cargo-deb/issues/68)
|
||||
|
||||
[1]: https://github.com/girlbossceo/conduwuit/pull/387
|
||||
[2]: https://wiki.musl-libc.org/functional-differences-from-glibc.html#Unloading-libraries
|
||||
|
||||
@@ -5,15 +5,18 @@ ## Complement
|
||||
Have a look at [Complement's repository][complement] for an explanation of what
|
||||
it is.
|
||||
|
||||
To test against Complement, with [Lix][lix] and direnv installed and set up, you can:
|
||||
To test against Complement, with [Lix][lix] and direnv installed and set up, you
|
||||
can:
|
||||
|
||||
* Run `./bin/complement "$COMPLEMENT_SRC" ./path/to/logs.jsonl ./path/to/results.jsonl`
|
||||
to build a Complement image, run the tests, and output the logs and results
|
||||
to the specified paths. This will also output the OCI image at `result`
|
||||
* Run `./bin/complement "$COMPLEMENT_SRC" ./path/to/logs.jsonl
|
||||
./path/to/results.jsonl` to build a Complement image, run the tests, and output
|
||||
the logs and results to the specified paths. This will also output the OCI image
|
||||
at `result`
|
||||
* Run `nix build .#complement` from the root of the repository to just build a
|
||||
Complement OCI image outputted to `result` (it's a `.tar.gz` file)
|
||||
* Or download the latest Complement OCI image from the CI workflow artifacts output
|
||||
from the commit/revision you want to test (e.g. from main) [here][ci-workflows]
|
||||
Complement OCI image outputted to `result` (it's a `.tar.gz` file)
|
||||
* Or download the latest Complement OCI image from the CI workflow artifacts
|
||||
output from the commit/revision you want to test (e.g. from main)
|
||||
[here][ci-workflows]
|
||||
|
||||
[lix]: https://lix.systems/
|
||||
[ci-workflows]: https://github.com/girlbossceo/conduwuit/actions/workflows/ci.yml?query=event%3Apush+is%3Asuccess+actor%3Agirlbossceo
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
#### **Note: This list may not up to date. There are rapidly more and more improvements, fixes, changes, etc being made that it is becoming more difficult to maintain this list. I recommend that you give conduwuit a try and see the differences for yourself. If you have any concerns, feel free to join the conduwuit Matrix room and ask any pre-usage questions.**
|
||||
#### **Note: This list may not up to date. There are rapidly more and more
|
||||
improvements, fixes, changes, etc being made that it is becoming more difficult
|
||||
to maintain this list. I recommend that you give conduwuit a try and see the
|
||||
differences for yourself. If you have any concerns, feel free to join the
|
||||
conduwuit Matrix room and ask any pre-usage questions.**
|
||||
|
||||
### list of features, bug fixes, etc that conduwuit does that Conduit does not
|
||||
|
||||
@@ -6,192 +10,371 @@ ### list of features, bug fixes, etc that conduwuit does that Conduit does not
|
||||
|
||||
## Performance
|
||||
|
||||
- Concurrency support for individual homeserver key fetching for faster remote room joins and room joins that will error less frequently
|
||||
- Send `Cache-Control` response header with `immutable` and 1 year cache length for all media requests (download and thumbnail) to instruct clients to cache media, and reduce server load from media requests that could be otherwise cached
|
||||
- Add feature flags and config options to enable/build with zstd, brotli, and/or gzip HTTP body compression (response and request)
|
||||
- Eliminate all usage of the thread-blocking `getaddrinfo(3)` call upon DNS queries, significantly improving federation latency/ping and cache DNS results (NXDOMAINs, successful queries, etc) using hickory-dns / hickory-resolver
|
||||
- Concurrency support for individual homeserver key fetching for faster remote
|
||||
room joins and room joins that will error less frequently
|
||||
- Send `Cache-Control` response header with `immutable` and 1 year cache length
|
||||
for all media requests (download and thumbnail) to instruct clients to cache
|
||||
media, and reduce server load from media requests that could be otherwise cached
|
||||
- Add feature flags and config options to enable/build with zstd, brotli, and/or
|
||||
gzip HTTP body compression (response and request)
|
||||
- Eliminate all usage of the thread-blocking `getaddrinfo(3)` call upon DNS
|
||||
queries, significantly improving federation latency/ping and cache DNS results
|
||||
(NXDOMAINs, successful queries, etc) using hickory-dns / hickory-resolver
|
||||
- Enable HTTP/2 support on all requests
|
||||
- Vastly improve RocksDB default settings to use new features that help with performance significantly, uses settings tailored to SSDs, various ways to tweak RocksDB, and a conduwuit setting to tell RocksDB to use settings that are tailored to HDDs or slow spinning rust storage or buggy filesystems.
|
||||
- Vastly improve RocksDB default settings to use new features that help with
|
||||
performance significantly, uses settings tailored to SSDs, various ways to tweak
|
||||
RocksDB, and a conduwuit setting to tell RocksDB to use settings that are
|
||||
tailored to HDDs or slow spinning rust storage or buggy filesystems.
|
||||
- Implement database flush and cleanup conduwuit operations when using RocksDB
|
||||
- Implement RocksDB write buffer corking and coalescing in database write-heavy areas
|
||||
- Perform connection pooling and keepalives where necessary to significantly improve federation performance and latency
|
||||
- Various config options to tweak connection pooling, request timeouts, connection timeouts, DNS timeouts and settings, etc with good defaults which also help huge with performance via reusing connections and retrying where needed
|
||||
- Implement RocksDB write buffer corking and coalescing in database write-heavy
|
||||
areas
|
||||
- Perform connection pooling and keepalives where necessary to significantly
|
||||
improve federation performance and latency
|
||||
- Various config options to tweak connection pooling, request timeouts,
|
||||
connection timeouts, DNS timeouts and settings, etc with good defaults which
|
||||
also help huge with performance via reusing connections and retrying where
|
||||
needed
|
||||
- Properly get and use the amount of parallelism / tokio workers
|
||||
- Implement building conduwuit with jemalloc (which extends to the RocksDB jemalloc feature for maximum gains) or hardened_malloc light variant, and io_uring support, and produce CI builds with jemalloc and io_uring by default for performance (Nix doesn't seem to build [hardened_malloc-rs](https://github.com/girlbossceo/hardened_malloc-rs) properly)
|
||||
- Add support for caching DNS results with hickory-dns / hickory-resolver in conduwuit (not a replacement for a proper resolver cache, but still far better than nothing), also properly falls back on TCP for UDP errors or if a SRV response is too large
|
||||
- Add config option for using DNS over TCP, and config option for controlling A/AAAA record lookup strategy (e.g. don't query AAAA records if you don't have IPv6 connectivity)
|
||||
- Overall significant database, Client-Server, and federation performance and latency improvements (check out the ping room leaderboards if you don't believe me :>)
|
||||
- Add config options for RocksDB compression and bottommost compression, including choosing the algorithm and compression level
|
||||
- Use [loole](https://github.com/mahdi-shojaee/loole) MPSC channels instead of tokio MPSC channels for huge performance boosts in sending channels (mainly relevant for federation) and presence channels
|
||||
- Use `tracing`/`log`'s `release_max_level_info` feature to improve performance, build speeds, binary size, and CPU usage in release builds by avoid compiling debug/trace log level macros that users will generally never use (can be disabled with a build-time feature flag)
|
||||
- Remove some unnecessary checks on EDU handling for incoming transactions, effectively speeding them up
|
||||
- Simplify, dedupe, etc huge chunks of the codebase, including some that were unnecessary overhead, binary bloats, or preventing compiler/linker optimisations
|
||||
- Implement zero-copy RocksDB database accessors, substantially improving performance caused by unnecessary memory allocations
|
||||
- Implement building conduwuit with jemalloc (which extends to the RocksDB
|
||||
jemalloc feature for maximum gains) or hardened_malloc light variant, and
|
||||
io_uring support, and produce CI builds with jemalloc and io_uring by default
|
||||
for performance (Nix doesn't seem to build
|
||||
[hardened_malloc-rs](https://github.com/girlbossceo/hardened_malloc-rs)
|
||||
properly)
|
||||
- Add support for caching DNS results with hickory-dns / hickory-resolver in
|
||||
conduwuit (not a replacement for a proper resolver cache, but still far better
|
||||
than nothing), also properly falls back on TCP for UDP errors or if a SRV
|
||||
response is too large
|
||||
- Add config option for using DNS over TCP, and config option for controlling
|
||||
A/AAAA record lookup strategy (e.g. don't query AAAA records if you don't have
|
||||
IPv6 connectivity)
|
||||
- Overall significant database, Client-Server, and federation performance and
|
||||
latency improvements (check out the ping room leaderboards if you don't believe
|
||||
me :>)
|
||||
- Add config options for RocksDB compression and bottommost compression,
|
||||
including choosing the algorithm and compression level
|
||||
- Use [loole](https://github.com/mahdi-shojaee/loole) MPSC channels instead of
|
||||
tokio MPSC channels for huge performance boosts in sending channels (mainly
|
||||
relevant for federation) and presence channels
|
||||
- Use `tracing`/`log`'s `release_max_level_info` feature to improve performance,
|
||||
build speeds, binary size, and CPU usage in release builds by avoid compiling
|
||||
debug/trace log level macros that users will generally never use (can be
|
||||
disabled with a build-time feature flag)
|
||||
- Remove some unnecessary checks on EDU handling for incoming transactions,
|
||||
effectively speeding them up
|
||||
- Simplify, dedupe, etc huge chunks of the codebase, including some that were
|
||||
unnecessary overhead, binary bloats, or preventing compiler/linker optimisations
|
||||
- Implement zero-copy RocksDB database accessors, substantially improving
|
||||
performance caused by unnecessary memory allocations
|
||||
|
||||
## General Fixes/Features
|
||||
|
||||
- Add legacy Element client hack fixing password changes and deactivations on legacy Element Android/iOS due to usage of an unspecced `user` field for UIAA
|
||||
- Raise and improve all the various request timeouts making some things like room joins and client bugs error less or none at all than they should, and make them all user configurable
|
||||
- Add legacy Element client hack fixing password changes and deactivations on
|
||||
legacy Element Android/iOS due to usage of an unspecced `user` field for UIAA
|
||||
- Raise and improve all the various request timeouts making some things like
|
||||
room joins and client bugs error less or none at all than they should, and make
|
||||
them all user configurable
|
||||
- Add missing `reason` field to user ban events (`/ban`)
|
||||
- Safer and cleaner shutdowns across incoming/outgoing requests (graceful shutdown) and the database
|
||||
- Stop sending `make_join` requests on room joins if 15 servers respond with `M_UNSUPPORTED_ROOM_VERSION` or `M_INVALID_ROOM_VERSION`
|
||||
- Stop sending `make_join` requests if 50 servers cannot provide `make_join` for us
|
||||
- Respect *most* client parameters for `/media/` requests (`allow_redirect` still needs work)
|
||||
- Return joined member count of rooms for push rules/conditions instead of a hardcoded value of 10
|
||||
- Make `CONDUIT_CONFIG` optional, relevant for container users that configure only by environment variables and no longer need to set `CONDUIT_CONFIG` to an empty string.
|
||||
- Allow HEAD and PATCH (MSC4138) HTTP requests in CORS for clients (despite not being explicity mentioned in Matrix spec, HTTP spec says all HEAD requests need to behave the same as GET requests, Synapse supports HEAD requests)
|
||||
- Safer and cleaner shutdowns across incoming/outgoing requests (graceful
|
||||
shutdown) and the database
|
||||
- Stop sending `make_join` requests on room joins if 15 servers respond with
|
||||
`M_UNSUPPORTED_ROOM_VERSION` or `M_INVALID_ROOM_VERSION`
|
||||
- Stop sending `make_join` requests if 50 servers cannot provide `make_join` for
|
||||
us
|
||||
- Respect *most* client parameters for `/media/` requests (`allow_redirect`
|
||||
still needs work)
|
||||
- Return joined member count of rooms for push rules/conditions instead of a
|
||||
hardcoded value of 10
|
||||
- Make `CONDUIT_CONFIG` optional, relevant for container users that configure
|
||||
only by environment variables and no longer need to set `CONDUIT_CONFIG` to an
|
||||
empty string.
|
||||
- Allow HEAD and PATCH (MSC4138) HTTP requests in CORS for clients (despite not
|
||||
being explicity mentioned in Matrix spec, HTTP spec says all HEAD requests need
|
||||
to behave the same as GET requests, Synapse supports HEAD requests)
|
||||
- Fix using conduwuit with flake-compat on NixOS
|
||||
- Resolve and remove some "features" from upstream that result in concurrency hazards, exponential backoff issues, or arbitrary performance limiters
|
||||
- Find more servers for outbound federation `/hierarchy` requests instead of just the room ID server name
|
||||
- Support for suggesting servers to join through at `/_matrix/client/v3/directory/room/{roomAlias}`
|
||||
- Support for suggesting servers to join through us at `/_matrix/federation/v1/query/directory`
|
||||
- Resolve and remove some "features" from upstream that result in concurrency
|
||||
hazards, exponential backoff issues, or arbitrary performance limiters
|
||||
- Find more servers for outbound federation `/hierarchy` requests instead of
|
||||
just the room ID server name
|
||||
- Support for suggesting servers to join through at
|
||||
`/_matrix/client/v3/directory/room/{roomAlias}`
|
||||
- Support for suggesting servers to join through us at
|
||||
`/_matrix/federation/v1/query/directory`
|
||||
- Misc edge-case search fixes (e.g. potentially missing some events)
|
||||
- Misc `/sync` fixes (e.g. returning unnecessary data or incorrect/invalid responses)
|
||||
- Add `replaces_state` and `prev_sender` in `unsigned` for state event changes which primarily makes Element's "See history" button on a state event functional
|
||||
- Fix Conduit not allowing incoming federation requests for various world readable rooms
|
||||
- Misc `/sync` fixes (e.g. returning unnecessary data or incorrect/invalid
|
||||
responses)
|
||||
- Add `replaces_state` and `prev_sender` in `unsigned` for state event changes
|
||||
which primarily makes Element's "See history" button on a state event functional
|
||||
- Fix Conduit not allowing incoming federation requests for various world
|
||||
readable rooms
|
||||
- Fix Conduit not respecting the client-requested file name on media requests
|
||||
- Prevent sending junk / non-membership events to `/send_join` and `/send_leave` endpoints
|
||||
- Only allow the requested membership type on `/send_join` and `/send_leave` endpoints (e.g. don't allow leave memberships on join endpoints)
|
||||
- Prevent sending junk / non-membership events to `/send_join` and `/send_leave`
|
||||
endpoints
|
||||
- Only allow the requested membership type on `/send_join` and `/send_leave`
|
||||
endpoints (e.g. don't allow leave memberships on join endpoints)
|
||||
- Prevent state key impersonation on `/send_join` and `/send_leave` endpoints
|
||||
- Validate `X-Matrix` origin and request body `"origin"` field on incoming transactions
|
||||
- Add `GET /_matrix/client/v1/register/m.login.registration_token/validity` endpoint
|
||||
- Explicitly define support for sliding sync at `/_matrix/client/versions` (`org.matrix.msc3575`)
|
||||
- Validate `X-Matrix` origin and request body `"origin"` field on incoming
|
||||
transactions
|
||||
- Add `GET /_matrix/client/v1/register/m.login.registration_token/validity`
|
||||
endpoint
|
||||
- Explicitly define support for sliding sync at `/_matrix/client/versions`
|
||||
(`org.matrix.msc3575`)
|
||||
- Fix seeing empty status messages on user presences
|
||||
|
||||
## Moderation
|
||||
|
||||
- (Also see [Admin Room](#admin-room) for all the admin commands pertaining to moderation, there's a lot!)
|
||||
- (Also see [Admin Room](#admin-room) for all the admin commands pertaining to
|
||||
moderation, there's a lot!)
|
||||
- Add support for room banning/blocking by ID using admin command
|
||||
- Add support for serving `support` well-known from `[global.well_known]` (MSC1929) (`/.well-known/matrix/support`)
|
||||
- Config option to forbid publishing rooms to the room directory (`lockdown_public_room_directory`) except for admins
|
||||
- Admin commands to delete room aliases and unpublish rooms from our room directory
|
||||
- For all [`/report`](https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidreporteventid) requests: check if the reported event ID belongs to the reported room ID, raise report reasoning character limit to 750, fix broken formatting, make a small delayed random response per spec suggestion on privacy, and check if the sender user is in the reported room.
|
||||
- Add support for serving `support` well-known from `[global.well_known]`
|
||||
(MSC1929) (`/.well-known/matrix/support`)
|
||||
- Config option to forbid publishing rooms to the room directory
|
||||
(`lockdown_public_room_directory`) except for admins
|
||||
- Admin commands to delete room aliases and unpublish rooms from our room
|
||||
directory
|
||||
- For all
|
||||
[`/report`](https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidreporteventid)
|
||||
requests: check if the reported event ID belongs to the reported room ID, raise
|
||||
report reasoning character limit to 750, fix broken formatting, make a small
|
||||
delayed random response per spec suggestion on privacy, and check if the sender
|
||||
user is in the reported room.
|
||||
- Support blocking servers from downloading remote media from, returning a 404
|
||||
- Don't allow `m.call.invite` events to be sent in public rooms (prevents calling the entire room)
|
||||
- On new public room creations, only allow moderators to send `m.call.invite`, `org.matrix.msc3401.call`, and `org.matrix.msc3401.call.member` events to prevent unprivileged users from calling the entire room
|
||||
- Add support for a "global ACLs" feature (`forbidden_remote_server_names`) that blocks inbound remote room invites, room joins by room ID on server name, room joins by room alias on server name, incoming federated joins, and incoming federated room directory requests. This is very helpful for blocking servers that are purely toxic/bad and serve no value in allowing our users to suffer from things like room invite spam or such. Please note that this is not a substitute for room ACLs.
|
||||
- Add support for a config option to forbid our local users from sending federated room directory requests for (`forbidden_remote_room_directory_server_names`). Similar to above, useful for blocking servers that help prevent our users from wandering into bad areas of Matrix via room directories of those malicious servers.
|
||||
- Add config option for auto remediating/deactivating local non-admin users who attempt to join bad/forbidden rooms (`auto_deactivate_banned_room_attempts`)
|
||||
- Deactivating users will remove their profile picture, blurhash, display name, and leave all rooms by default just like Synapse and for additional privacy
|
||||
- Don't allow `m.call.invite` events to be sent in public rooms (prevents
|
||||
calling the entire room)
|
||||
- On new public room creations, only allow moderators to send `m.call.invite`,
|
||||
`org.matrix.msc3401.call`, and `org.matrix.msc3401.call.member` events to
|
||||
prevent unprivileged users from calling the entire room
|
||||
- Add support for a "global ACLs" feature (`forbidden_remote_server_names`) that
|
||||
blocks inbound remote room invites, room joins by room ID on server name, room
|
||||
joins by room alias on server name, incoming federated joins, and incoming
|
||||
federated room directory requests. This is very helpful for blocking servers
|
||||
that are purely toxic/bad and serve no value in allowing our users to suffer
|
||||
from things like room invite spam or such. Please note that this is not a
|
||||
substitute for room ACLs.
|
||||
- Add support for a config option to forbid our local users from sending
|
||||
federated room directory requests for
|
||||
(`forbidden_remote_room_directory_server_names`). Similar to above, useful for
|
||||
blocking servers that help prevent our users from wandering into bad areas of
|
||||
Matrix via room directories of those malicious servers.
|
||||
- Add config option for auto remediating/deactivating local non-admin users who
|
||||
attempt to join bad/forbidden rooms (`auto_deactivate_banned_room_attempts`)
|
||||
- Deactivating users will remove their profile picture, blurhash, display name,
|
||||
and leave all rooms by default just like Synapse and for additional privacy
|
||||
- Reject some EDUs from ACL'd users such as read receipts and typing indicators
|
||||
|
||||
## Privacy/Security
|
||||
|
||||
- Add config option for device name federation with a privacy-friendly default (disabled)
|
||||
- Add config option for requiring authentication to the `/publicRooms` endpoint (room directory) with a default enabled for privacy
|
||||
- Add config option for federating `/publicRooms` endpoint (room directory) to other servers with a default disabled for privacy
|
||||
- Uses proper `argon2` crate by RustCrypto instead of questionable `rust-argon2` crate
|
||||
- Add config option for device name federation with a privacy-friendly default
|
||||
(disabled)
|
||||
- Add config option for requiring authentication to the `/publicRooms` endpoint
|
||||
(room directory) with a default enabled for privacy
|
||||
- Add config option for federating `/publicRooms` endpoint (room directory) to
|
||||
other servers with a default disabled for privacy
|
||||
- Uses proper `argon2` crate by RustCrypto instead of questionable `rust-argon2`
|
||||
crate
|
||||
- Generate passwords with 25 characters instead of 15
|
||||
- Config option `ip_range_denylist` to support refusing to send requests (typically federation) to specific IP ranges, typically RFC 1918, non-routable, testnet, etc addresses like Synapse for security (note: this is not a guaranteed protection, and you should be using a firewall with zones if you want guaranteed protection as doing this on the application level is prone to bypasses).
|
||||
- Config option to block non-admin users from sending room invites or receiving remote room invites. Admin users are still allowed.
|
||||
- Config option `ip_range_denylist` to support refusing to send requests
|
||||
(typically federation) to specific IP ranges, typically RFC 1918, non-routable,
|
||||
testnet, etc addresses like Synapse for security (note: this is not a guaranteed
|
||||
protection, and you should be using a firewall with zones if you want guaranteed
|
||||
protection as doing this on the application level is prone to bypasses).
|
||||
- Config option to block non-admin users from sending room invites or receiving
|
||||
remote room invites. Admin users are still allowed.
|
||||
- Config option to disable incoming and/or outgoing remote read receipts
|
||||
- Config option to disable incoming and/or outgoing remote typing indicators
|
||||
- Config option to disable incoming, outgoing, and/or local presence and for timing out remote users
|
||||
- Sanitise file names for the `Content-Disposition` header for all media requests (thumbnails, downloads, uploads)
|
||||
- Media repository on handling `Content-Disposition` and `Content-Type` is fully spec compliant and secured
|
||||
- Send secure default HTTP headers such as a strong restrictive CSP (see MSC4149), deny iframes, disable `X-XSS-Protection`, disable interest cohort in `Permission-Policy`, etc to mitigate any potential attack surface such as from untrusted media
|
||||
- Config option to disable incoming, outgoing, and/or local presence and for
|
||||
timing out remote users
|
||||
- Sanitise file names for the `Content-Disposition` header for all media
|
||||
requests (thumbnails, downloads, uploads)
|
||||
- Media repository on handling `Content-Disposition` and `Content-Type` is fully
|
||||
spec compliant and secured
|
||||
- Send secure default HTTP headers such as a strong restrictive CSP (see
|
||||
MSC4149), deny iframes, disable `X-XSS-Protection`, disable interest cohort in
|
||||
`Permission-Policy`, etc to mitigate any potential attack surface such as from
|
||||
untrusted media
|
||||
|
||||
## Administration/Logging
|
||||
|
||||
- Commandline argument to specify the path to a config file instead of relying on `CONDUIT_CONFIG`
|
||||
- Commandline argument to specify the path to a config file instead of relying
|
||||
on `CONDUIT_CONFIG`
|
||||
- Revamped admin room infrastructure and commands
|
||||
- Substantially clean up, improve, and fix logging (less noisy dead server logging, registration attempts, more useful troubleshooting logging, proper error propagation, etc)
|
||||
- Configurable RocksDB logging (`LOG` files) with proper defaults (rotate, max size, verbosity, etc) to stop LOG files from accumulating so much
|
||||
- Explicit startup error if your configuration allows open registration without a token or such like Synapse with a way to bypass it if needed
|
||||
- Replace the lightning bolt emoji option with support for setting any arbitrary text (e.g. another emoji) to suffix to all new user registrations, with a conduwuit default of "🏳️⚧️"
|
||||
- Substantially clean up, improve, and fix logging (less noisy dead server
|
||||
logging, registration attempts, more useful troubleshooting logging, proper
|
||||
error propagation, etc)
|
||||
- Configurable RocksDB logging (`LOG` files) with proper defaults (rotate, max
|
||||
size, verbosity, etc) to stop LOG files from accumulating so much
|
||||
- Explicit startup error if your configuration allows open registration without
|
||||
a token or such like Synapse with a way to bypass it if needed
|
||||
- Replace the lightning bolt emoji option with support for setting any arbitrary
|
||||
text (e.g. another emoji) to suffix to all new user registrations, with a
|
||||
conduwuit default of "🏳️⚧️"
|
||||
- Implement config option to auto join rooms upon registration
|
||||
- Warn on unknown config options specified
|
||||
- Add `/_conduwuit/server_version` route to return the version of conduwuit without relying on the federation API `/_matrix/federation/v1/version`
|
||||
- Add `/_conduwuit/local_user_count` route to return the amount of registered active local users on your homeserver *if federation is enabled*
|
||||
- Add configurable RocksDB recovery modes to aid in recovering corrupted RocksDB databases
|
||||
- Support config options via `CONDUWUIT_` prefix and accessing non-global struct config options with the `__` split (e.g. `CONDUWUIT_WELL_KNOWN__SERVER`)
|
||||
- Add `/_conduwuit/server_version` route to return the version of conduwuit
|
||||
without relying on the federation API `/_matrix/federation/v1/version`
|
||||
- Add `/_conduwuit/local_user_count` route to return the amount of registered
|
||||
active local users on your homeserver *if federation is enabled*
|
||||
- Add configurable RocksDB recovery modes to aid in recovering corrupted RocksDB
|
||||
databases
|
||||
- Support config options via `CONDUWUIT_` prefix and accessing non-global struct
|
||||
config options with the `__` split (e.g. `CONDUWUIT_WELL_KNOWN__SERVER`)
|
||||
- Add support for listening on multiple TCP ports and multiple addresses
|
||||
- **Opt-in** Sentry.io telemetry and metrics, mainly used for crash reporting
|
||||
- Log the client IP on various requests such as registrations, banned room join attempts, logins, deactivations, federation transactions, etc
|
||||
- Log the client IP on various requests such as registrations, banned room join
|
||||
attempts, logins, deactivations, federation transactions, etc
|
||||
- Fix Conduit dropping some remote server federation response errors
|
||||
|
||||
## Maintenance/Stability
|
||||
|
||||
- GitLab CI ported to GitHub Actions
|
||||
- Add support for the Matrix spec compliance test suite [Complement](https://github.com/matrix-org/complement/) via the Nix flake and various other fixes for it
|
||||
- Implement running and diff'ing Complement results in CI and error if any mismatch occurs to prevent large cases of conduwuit regressions
|
||||
- Repo is (officially) mirrored to GitHub, GitLab, git.gay, git.girlcock.ceo, sourcehut, and Codeberg (see README.md for their links)
|
||||
- Docker container images published to GitLab Container Registry, GitHub Container Registry, and Dockerhub
|
||||
- Extensively revamp the example config to be extremely helpful and useful to both new users and power users
|
||||
- Fixed every single clippy (default lints) and rustc warnings, including some that were performance related or potential safety issues / unsoundness
|
||||
- Add support for the Matrix spec compliance test suite
|
||||
[Complement](https://github.com/matrix-org/complement/) via the Nix flake and
|
||||
various other fixes for it
|
||||
- Implement running and diff'ing Complement results in CI and error if any
|
||||
mismatch occurs to prevent large cases of conduwuit regressions
|
||||
- Repo is (officially) mirrored to GitHub, GitLab, git.gay, git.girlcock.ceo,
|
||||
sourcehut, and Codeberg (see README.md for their links)
|
||||
- Docker container images published to GitLab Container Registry, GitHub
|
||||
Container Registry, and Dockerhub
|
||||
- Extensively revamp the example config to be extremely helpful and useful to
|
||||
both new users and power users
|
||||
- Fixed every single clippy (default lints) and rustc warnings, including some
|
||||
that were performance related or potential safety issues / unsoundness
|
||||
- Add a **lot** of other clippy and rustc lints and a rustfmt.toml file
|
||||
- Repo uses [Renovate](https://docs.renovatebot.com/), [Trivy](https://github.com/aquasecurity/trivy-action), and keeps ALL dependencies as up to date as possible
|
||||
- Purge unmaintained/irrelevant/broken database backends (heed, sled, persy) and other unnecessary code or overhead
|
||||
- Repo uses [Renovate](https://docs.renovatebot.com/),
|
||||
[Trivy](https://github.com/aquasecurity/trivy-action), and keeps ALL
|
||||
dependencies as up to date as possible
|
||||
- Purge unmaintained/irrelevant/broken database backends (heed, sled, persy) and
|
||||
other unnecessary code or overhead
|
||||
- webp support for images
|
||||
- Add cargo audit support to CI
|
||||
- Add documentation lints via lychee and markdownlint-cli to CI
|
||||
- CI tests for all sorts of feature matrixes (jemalloc, non-defaullt, all features, etc)
|
||||
- Add static and dynamic linking smoke tests in CI to prevent any potential linking regressions for Complement, static binaries, Nix devshells, etc
|
||||
- Add timestamp by commit date when building OCI images for keeping image build reproducibility and still have a meaningful "last modified date" for OCI image
|
||||
- CI tests for all sorts of feature matrixes (jemalloc, non-defaullt, all
|
||||
features, etc)
|
||||
- Add static and dynamic linking smoke tests in CI to prevent any potential
|
||||
linking regressions for Complement, static binaries, Nix devshells, etc
|
||||
- Add timestamp by commit date when building OCI images for keeping image build
|
||||
reproducibility and still have a meaningful "last modified date" for OCI image
|
||||
- Add timestamp by commit date via `SOURCE_DATE_EPOCH` for Debian packages
|
||||
- Startup check if conduwuit running in a container and is listening on 127.0.0.1 (generally containers are using NAT networking and 0.0.0.0 is the intended listening address)
|
||||
- Add a panic catcher layer to return panic messages in HTTP responses if a panic occurs
|
||||
- Add full compatibility support for SHA256 media file names instead of base64 file names to overcome filesystem file name length limitations (OS error file name too long) while still retaining upstream database compatibility
|
||||
- Remove SQLite support due to being very poor performance, difficult to maintain against RocksDB, and is a blocker to significantly improved database code
|
||||
- Startup check if conduwuit running in a container and is listening on
|
||||
127.0.0.1 (generally containers are using NAT networking and 0.0.0.0 is the
|
||||
intended listening address)
|
||||
- Add a panic catcher layer to return panic messages in HTTP responses if a
|
||||
panic occurs
|
||||
- Add full compatibility support for SHA256 media file names instead of base64
|
||||
file names to overcome filesystem file name length limitations (OS error file
|
||||
name too long) while still retaining upstream database compatibility
|
||||
- Remove SQLite support due to being very poor performance, difficult to
|
||||
maintain against RocksDB, and is a blocker to significantly improved database
|
||||
code
|
||||
|
||||
## Admin Room
|
||||
|
||||
- Add support for a console CLI interface that can issue admin commands and output them in your terminal
|
||||
- Add support for an admin-user-only commandline admin room interface that can be issued in any room with the `\\!admin` or `\!admin` prefix and returns the response as yourself in the same room
|
||||
- Add admin commands for uptime, server startup, server shutdown, and server restart
|
||||
- Fix admin room handler to not panic/crash if the admin room command response fails (e.g. too large message)
|
||||
- Add command to dynamically change conduwuit's tracing log level filter on the fly
|
||||
- Add support for a console CLI interface that can issue admin commands and
|
||||
output them in your terminal
|
||||
- Add support for an admin-user-only commandline admin room interface that can
|
||||
be issued in any room with the `\\!admin` or `\!admin` prefix and returns the
|
||||
response as yourself in the same room
|
||||
- Add admin commands for uptime, server startup, server shutdown, and server
|
||||
restart
|
||||
- Fix admin room handler to not panic/crash if the admin room command response
|
||||
fails (e.g. too large message)
|
||||
- Add command to dynamically change conduwuit's tracing log level filter on the
|
||||
fly
|
||||
- Add admin command to fetch a server's `/.well-known/matrix/support` file
|
||||
- Add debug admin command to force update user device lists (could potentially resolve some E2EE flukes)
|
||||
- Implement **RocksDB online backups**, listing RocksDB backups, and listing database file counts all via admin commands
|
||||
- Add various database visibility commands such as being able to query the getters and iterators used in conduwuit, a very helpful online debugging utility
|
||||
- Add debug admin command to force update user device lists (could potentially
|
||||
resolve some E2EE flukes)
|
||||
- Implement **RocksDB online backups**, listing RocksDB backups, and listing
|
||||
database file counts all via admin commands
|
||||
- Add various database visibility commands such as being able to query the
|
||||
getters and iterators used in conduwuit, a very helpful online debugging utility
|
||||
- Forbid the admin room from being made public or world readable history
|
||||
- Add `!admin` as a way to call the admin bot
|
||||
- Extend clear cache admin command to support clearing more caches such as DNS and TLS name overrides
|
||||
- Admin debug command to send a federation request/ping to a server's `/_matrix/federation/v1/version` endpoint and measures the latency it took
|
||||
- Extend clear cache admin command to support clearing more caches such as DNS
|
||||
and TLS name overrides
|
||||
- Admin debug command to send a federation request/ping to a server's
|
||||
`/_matrix/federation/v1/version` endpoint and measures the latency it took
|
||||
- Add admin command to bulk delete media via a codeblock list of MXC URLs.
|
||||
- Add admin command to delete both the thumbnail and media MXC URLs from an event ID (e.g. from an abuse report)
|
||||
- Add admin command to delete both the thumbnail and media MXC URLs from an
|
||||
event ID (e.g. from an abuse report)
|
||||
- Add admin command to list all the rooms a local user is joined in
|
||||
- Add admin command to list joined members in a room
|
||||
- Add admin command to view the room topic of a room
|
||||
- Add admin command to delete all remote media in the past X minutes as a form of deleting media that you don't want on your server that a remote user posted in a room, a `--force` flag to ignore errors, and support for reading `last modified time` instead of `creation time` for filesystems that don't support file created metadata
|
||||
- Add admin command to delete all remote media in the past X minutes as a form
|
||||
of deleting media that you don't want on your server that a remote user posted
|
||||
in a room, a `--force` flag to ignore errors, and support for reading `last
|
||||
modified time` instead of `creation time` for filesystems that don't support
|
||||
file created metadata
|
||||
- Add admin command to return a room's full/complete state
|
||||
- Admin debug command to fetch a PDU from a remote server and inserts it into our database/timeline as backfill
|
||||
- Add admin command to delete media via a specific MXC. This deletes the MXC from our database, and the file locally.
|
||||
- Add admin commands for banning (blocking) room IDs from our local users joining (admins are always allowed) and evicts all our local users from that room, in addition to bulk room banning support, and blocks room invites (remote and local) to the banned room, as a moderation feature
|
||||
- Admin debug command to fetch a PDU from a remote server and inserts it into
|
||||
our database/timeline as backfill
|
||||
- Add admin command to delete media via a specific MXC. This deletes the MXC
|
||||
from our database, and the file locally.
|
||||
- Add admin commands for banning (blocking) room IDs from our local users
|
||||
joining (admins are always allowed) and evicts all our local users from that
|
||||
room, in addition to bulk room banning support, and blocks room invites (remote
|
||||
and local) to the banned room, as a moderation feature
|
||||
- Add admin commands to output jemalloc memory stats and memory usage
|
||||
- Add admin command to get rooms a *remote* user shares with us
|
||||
- Add debug admin commands to get the earliest and latest PDU in a room
|
||||
- Add debug admin command to echo a message
|
||||
- Add admin command to insert rooms tags for a user, most useful for inserting the `m.server_notice` tag on your admin room to make it "persistent" in the "System Alerts" section of Element
|
||||
- Add experimental admin debug command for Dendrite's `AdminDownloadState` (`/admin/downloadState/{serverName}/{roomID}`) admin API endpoint to download and use a remote server's room state in the room
|
||||
- Disable URL previews by default in the admin room due to various command outputs having "URLs" in them that clients may needlessly render/request
|
||||
- Extend memory usage admin server command to support showing memory allocator stats such as jemalloc's
|
||||
- Add admin debug command to see memory allocator's full extended debug statistics such as jemalloc's
|
||||
- Add admin command to insert rooms tags for a user, most useful for inserting
|
||||
the `m.server_notice` tag on your admin room to make it "persistent" in the
|
||||
"System Alerts" section of Element
|
||||
- Add experimental admin debug command for Dendrite's `AdminDownloadState`
|
||||
(`/admin/downloadState/{serverName}/{roomID}`) admin API endpoint to download
|
||||
and use a remote server's room state in the room
|
||||
- Disable URL previews by default in the admin room due to various command
|
||||
outputs having "URLs" in them that clients may needlessly render/request
|
||||
- Extend memory usage admin server command to support showing memory allocator
|
||||
stats such as jemalloc's
|
||||
- Add admin debug command to see memory allocator's full extended debug
|
||||
statistics such as jemalloc's
|
||||
|
||||
## Misc
|
||||
|
||||
- Add guest support for accessing TURN servers via `turn_allow_guests` like Synapse
|
||||
- Support for creating rooms with custom room IDs like Maunium Synapse (`room_id` request body field to `/createRoom`)
|
||||
- Query parameter `?format=event|content` for returning either the room state event's content (default) for the full room state event on `/_matrix/client/v3/rooms/{roomId}/state/{eventType}[/{stateKey}]` requests (see <https://github.com/matrix-org/matrix-spec/issues/1047>)
|
||||
- Add guest support for accessing TURN servers via `turn_allow_guests` like
|
||||
Synapse
|
||||
- Support for creating rooms with custom room IDs like Maunium Synapse
|
||||
(`room_id` request body field to `/createRoom`)
|
||||
- Query parameter `?format=event|content` for returning either the room state
|
||||
event's content (default) for the full room state event on
|
||||
`/_matrix/client/v3/rooms/{roomId}/state/{eventType}[/{stateKey}]` requests (see
|
||||
<https://github.com/matrix-org/matrix-spec/issues/1047>)
|
||||
- Send a User-Agent on all of our requests
|
||||
- Send `avatar_url` on invite room membership events/changes
|
||||
- Support sending [`well_known` response to client login responses](https://spec.matrix.org/v1.10/client-server-api/#post_matrixclientv3login) if using config option `[well_known.client]`
|
||||
- Implement `include_state` search criteria support for `/search` requests (response now can include room states)
|
||||
- Declare various missing Matrix versions and features at `/_matrix/client/versions`
|
||||
- Implement legacy Matrix `/v1/` media endpoints that some clients and servers may still call
|
||||
- Config option to change Conduit's behaviour of homeserver key fetching (`query_trusted_key_servers_first`). This option sets whether conduwuit will query trusted notary key servers first before the individual homeserver(s), or vice versa which may help in joining certain rooms.
|
||||
- Support sending [`well_known` response to client login
|
||||
responses](https://spec.matrix.org/v1.10/client-server-api/#post_matrixclientv3login)
|
||||
if using config option `[well_known.client]`
|
||||
- Implement `include_state` search criteria support for `/search` requests
|
||||
(response now can include room states)
|
||||
- Declare various missing Matrix versions and features at
|
||||
`/_matrix/client/versions`
|
||||
- Implement legacy Matrix `/v1/` media endpoints that some clients and servers
|
||||
may still call
|
||||
- Config option to change Conduit's behaviour of homeserver key fetching
|
||||
(`query_trusted_key_servers_first`). This option sets whether conduwuit will
|
||||
query trusted notary key servers first before the individual homeserver(s), or
|
||||
vice versa which may help in joining certain rooms.
|
||||
- Implement unstable MSC2666 support for querying mutual rooms with a user
|
||||
- Implement unstable MSC3266 room summary API support
|
||||
- Implement unstable MSC4125 support for specifying servers to join via on federated invites
|
||||
- Implement unstable MSC4125 support for specifying servers to join via on
|
||||
federated invites
|
||||
- Make conduwuit build and be functional under Nix + macOS
|
||||
- Log out all sessions after unsetting the emergency password
|
||||
- Assume well-knowns are broken if they exceed past 12288 characters.
|
||||
- Add support for listening on both HTTP and HTTPS if using direct TLS with conduwuit for usecases such as Complement
|
||||
- Add support for listening on both HTTP and HTTPS if using direct TLS with
|
||||
conduwuit for usecases such as Complement
|
||||
- Add config option for disabling RocksDB Direct IO if needed
|
||||
- Add various documentation on maintaining conduwuit, using RocksDB online backups, some troubleshooting, using admin commands, moderation documentation, etc
|
||||
- (Developers): Add support for [hot reloadable/"live" modular development](development/hot_reload.md)
|
||||
- Add various documentation on maintaining conduwuit, using RocksDB online
|
||||
backups, some troubleshooting, using admin commands, moderation documentation,
|
||||
etc
|
||||
- (Developers): Add support for [hot reloadable/"live" modular
|
||||
development](development/hot_reload.md)
|
||||
- (Developers): Add support for tokio-console
|
||||
- (Developers): Add support for tracing flame graphs
|
||||
- No cryptocurrency donations allowed, conduwuit is fully maintained by independent queer maintainers, and with a strong priority on inclusitivity and comfort for protected groups 🏳️⚧️
|
||||
- [Add a community Code of Conduct for all conduwuit community spaces, primarily the Matrix space](https://conduwuit.puppyirl.gay/conduwuit_coc.html)
|
||||
- No cryptocurrency donations allowed, conduwuit is fully maintained by
|
||||
independent queer maintainers, and with a strong priority on inclusitivity and
|
||||
comfort for protected groups 🏳️⚧️
|
||||
- [Add a community Code of Conduct for all conduwuit community spaces, primarily
|
||||
the Matrix space](https://conduwuit.puppyirl.gay/conduwuit_coc.html)
|
||||
|
||||
@@ -12,7 +12,8 @@ #### How can I deploy my own?
|
||||
|
||||
- [Deployment options](deploying.md)
|
||||
|
||||
If you want to connect an appservice to conduwuit, take a look at the [appservices documentation](appservices.md).
|
||||
If you want to connect an appservice to conduwuit, take a look at the
|
||||
[appservices documentation](appservices.md).
|
||||
|
||||
#### How can I contribute?
|
||||
|
||||
|
||||
@@ -2,7 +2,11 @@ # Maintaining your conduwuit setup
|
||||
|
||||
## Moderation
|
||||
|
||||
conduwuit has moderation through admin room commands. "binary commands" (medium priority) and an admin API (low priority) is planned. Some moderation-related config options are available in the example config such as "global ACLs" and blocking media requests to certain servers. See the example config for the moderation config options under the "Moderation / Privacy / Security" section.
|
||||
conduwuit has moderation through admin room commands. "binary commands" (medium
|
||||
priority) and an admin API (low priority) is planned. Some moderation-related
|
||||
config options are available in the example config such as "global ACLs" and
|
||||
blocking media requests to certain servers. See the example config for the
|
||||
moderation config options under the "Moderation / Privacy / Security" section.
|
||||
|
||||
conduwuit has moderation admin commands for:
|
||||
|
||||
@@ -11,56 +15,83 @@ ## Moderation
|
||||
- managing room banning/blocking and user removal (`!admin rooms moderation`)
|
||||
- managing user accounts (`!admin users`)
|
||||
- fetching `/.well-known/matrix/support` from servers (`!admin federation`)
|
||||
- blocking incoming federation for certain rooms (not the same as room banning) (`!admin federation`)
|
||||
- blocking incoming federation for certain rooms (not the same as room banning)
|
||||
(`!admin federation`)
|
||||
- deleting media (see [the media section](#media))
|
||||
|
||||
Any commands with `-list` in them will require a codeblock in the message with each object being newline delimited. An example of doing this is:
|
||||
Any commands with `-list` in them will require a codeblock in the message with
|
||||
each object being newline delimited. An example of doing this is:
|
||||
|
||||
````
|
||||
!admin rooms moderation ban-list-of-rooms
|
||||
```
|
||||
!roomid1:server.name
|
||||
!roomid2:server.name
|
||||
!roomid3:server.name
|
||||
```
|
||||
````
|
||||
```` !admin rooms moderation ban-list-of-rooms ``` !roomid1:server.name
|
||||
!roomid2:server.name !roomid3:server.name ``` ````
|
||||
|
||||
## Database
|
||||
|
||||
If using RocksDB, there's very little you need to do. Compaction is ran automatically based on various defined thresholds tuned for conduwuit to be high performance with the least I/O amplifcation or overhead. Manually running compaction is not recommended, or compaction via a timer. RocksDB is built with io_uring support via liburing for async read I/O.
|
||||
If using RocksDB, there's very little you need to do. Compaction is ran
|
||||
automatically based on various defined thresholds tuned for conduwuit to be high
|
||||
performance with the least I/O amplifcation or overhead. Manually running
|
||||
compaction is not recommended, or compaction via a timer. RocksDB is built with
|
||||
io_uring support via liburing for async read I/O.
|
||||
|
||||
Some RocksDB settings can be adjusted such as the compression method chosen. See the RocksDB section in the [example config](configuration/examples.md). btrfs users may benefit from disabling compression on RocksDB if CoW is in use.
|
||||
Some RocksDB settings can be adjusted such as the compression method chosen. See
|
||||
the RocksDB section in the [example config](configuration/examples.md). btrfs
|
||||
users may benefit from disabling compression on RocksDB if CoW is in use.
|
||||
|
||||
RocksDB troubleshooting can be found [in the RocksDB section of troubleshooting](troubleshooting.md).
|
||||
RocksDB troubleshooting can be found [in the RocksDB section of
|
||||
troubleshooting](troubleshooting.md).
|
||||
|
||||
## Backups
|
||||
|
||||
Currently only RocksDB supports online backups. If you'd like to backup your database online without any downtime, see the `!admin server` command for the backup commands and the `database_backup_path` config options in the example config. Please note that the format of the database backup is not the exact same. This is unfortunately a bad design choice by Facebook as we are using the database backup engine API from RocksDB, however the data is still there and can still be joined together.
|
||||
Currently only RocksDB supports online backups. If you'd like to backup your
|
||||
database online without any downtime, see the `!admin server` command for the
|
||||
backup commands and the `database_backup_path` config options in the example
|
||||
config. Please note that the format of the database backup is not the exact
|
||||
same. This is unfortunately a bad design choice by Facebook as we are using the
|
||||
database backup engine API from RocksDB, however the data is still there and can
|
||||
still be joined together.
|
||||
|
||||
To restore a backup from an online RocksDB backup:
|
||||
|
||||
- shutdown conduwuit
|
||||
- create a new directory for merging together the data
|
||||
- in the online backup created, copy all `.sst` files in `$DATABASE_BACKUP_PATH/shared_checksum` to your new directory
|
||||
- trim all the strings so instead of `######_sxxxxxxxxx.sst`, it reads `######.sst`. A way of doing this with sed and bash is `for file in *.sst; do mv "$file" "$(echo "$file" | sed 's/_s.*/.sst/')"; done`
|
||||
- copy all the files in `$DATABASE_BACKUP_PATH/1` (or the latest backup number if you have multiple) to your new directory
|
||||
- set your `database_path` config option to your new directory, or replace your old one with the new one you crafted
|
||||
- in the online backup created, copy all `.sst` files in
|
||||
`$DATABASE_BACKUP_PATH/shared_checksum` to your new directory
|
||||
- trim all the strings so instead of `######_sxxxxxxxxx.sst`, it reads
|
||||
`######.sst`. A way of doing this with sed and bash is `for file in *.sst; do mv
|
||||
"$file" "$(echo "$file" | sed 's/_s.*/.sst/')"; done`
|
||||
- copy all the files in `$DATABASE_BACKUP_PATH/1` (or the latest backup number
|
||||
if you have multiple) to your new directory
|
||||
- set your `database_path` config option to your new directory, or replace your
|
||||
old one with the new one you crafted
|
||||
- start up conduwuit again and it should open as normal
|
||||
|
||||
If you'd like to do an offline backup, shutdown conduwuit and copy your `database_path` directory elsewhere. This can be restored with no modifications needed.
|
||||
If you'd like to do an offline backup, shutdown conduwuit and copy your
|
||||
`database_path` directory elsewhere. This can be restored with no modifications
|
||||
needed.
|
||||
|
||||
Backing up media is also just copying the `media/` directory from your database directory.
|
||||
Backing up media is also just copying the `media/` directory from your database
|
||||
directory.
|
||||
|
||||
## Media
|
||||
|
||||
Media still needs various work, however conduwuit implements media deletion via:
|
||||
|
||||
- MXC URI or Event ID (unencrypted and attempts to find the MXC URI in the event)
|
||||
- MXC URI or Event ID (unencrypted and attempts to find the MXC URI in the
|
||||
event)
|
||||
- Delete list of MXC URIs
|
||||
- Delete remote media in the past `N` seconds/minutes via filesystem metadata on the file created time (`btime`) or file modified time (`mtime`)
|
||||
- Delete remote media in the past `N` seconds/minutes via filesystem metadata on
|
||||
the file created time (`btime`) or file modified time (`mtime`)
|
||||
|
||||
See the `!admin media` command for further information. All media in conduwuit is stored at `$DATABASE_DIR/media`. This will be configurable soon.
|
||||
See the `!admin media` command for further information. All media in conduwuit
|
||||
is stored at `$DATABASE_DIR/media`. This will be configurable soon.
|
||||
|
||||
If you are finding yourself needing extensive granular control over media, we recommend looking into [Matrix Media Repo](https://github.com/t2bot/matrix-media-repo). conduwuit intends to implement various utilities for media, but MMR is dedicated to extensive media management.
|
||||
If you are finding yourself needing extensive granular control over media, we
|
||||
recommend looking into [Matrix Media
|
||||
Repo](https://github.com/t2bot/matrix-media-repo). conduwuit intends to
|
||||
implement various utilities for media, but MMR is dedicated to extensive media
|
||||
management.
|
||||
|
||||
Built-in S3 support is also planned, but for now using a "S3 filesystem" on `media/` works. conduwuit also sends a `Cache-Control` header of 1 year and immutable for all media requests (download and thumbnail) to reduce unnecessary media requests from browsers, reduce bandwidth usage, and reduce load.
|
||||
Built-in S3 support is also planned, but for now using a "S3 filesystem" on
|
||||
`media/` works. conduwuit also sends a `Cache-Control` header of 1 year and
|
||||
immutable for all media requests (download and thumbnail) to reduce unnecessary
|
||||
media requests from browsers, reduce bandwidth usage, and reduce load.
|
||||
|
||||
@@ -2,23 +2,55 @@ # Troubleshooting conduwuit
|
||||
|
||||
> ## Docker users ⚠️
|
||||
>
|
||||
> Docker is extremely UX unfriendly. Because of this, a ton of issues or support is actually Docker support, not conduwuit support. We also cannot document the ever-growing list of Docker issues here.
|
||||
> Docker is extremely UX unfriendly. Because of this, a ton of issues or support
|
||||
> is actually Docker support, not conduwuit support. We also cannot document the
|
||||
> ever-growing list of Docker issues here.
|
||||
>
|
||||
> If you intend on asking for support and you are using Docker, **PLEASE** triple validate your issues are **NOT** because you have a misconfiguration in your Docker setup.
|
||||
> If you intend on asking for support and you are using Docker, **PLEASE**
|
||||
> triple validate your issues are **NOT** because you have a misconfiguration in
|
||||
> your Docker setup.
|
||||
>
|
||||
> If there are things like Compose file issues or Dockerhub image issues, those can still be mentioned as long as they're something we can fix.
|
||||
> If there are things like Compose file issues or Dockerhub image issues, those
|
||||
> can still be mentioned as long as they're something we can fix.
|
||||
|
||||
## General potential issues
|
||||
|
||||
#### Potential DNS issues when using Docker
|
||||
|
||||
Docker has issues with its default DNS setup that may cause DNS to not be
|
||||
properly functional when running conduwuit, resulting in federation issues. The
|
||||
symptoms of this have shown in excessively long room joins (30+ minutes) from
|
||||
very long DNS timeouts, log entries of "mismatching responding nameservers",
|
||||
and/or partial or non-functional inbound/outbound federation.
|
||||
|
||||
This is **not** a conduwuit issue, and is purely a Docker issue. It is not
|
||||
sustainable for heavy DNS activity which is normal for Matrix federation. The
|
||||
workarounds for this are:
|
||||
- Use DNS over TCP via the config option `query_over_tcp_only = true`
|
||||
- Don't use Docker's default DNS setup and instead allow the container to use
|
||||
and communicate with your host's DNS servers (host's `/etc/resolv.conf`)
|
||||
|
||||
## Rocksdb / database issues
|
||||
|
||||
#### Direct IO
|
||||
|
||||
Some filesystems may not like RocksDB using [Direct IO](https://github.com/facebook/rocksdb/wiki/Direct-IO). Direct IO is for non-buffered I/O which improves conduwuit performance, but at least FUSE is a filesystem potentially known to not like this. See the [example config](configuration/examples.md) for disabling it if needed. Issues from Direct IO on unsupported filesystems are usually shown as startup errors.
|
||||
Some filesystems may not like RocksDB using [Direct
|
||||
IO](https://github.com/facebook/rocksdb/wiki/Direct-IO). Direct IO is for
|
||||
non-buffered I/O which improves conduwuit performance, but at least FUSE is a
|
||||
filesystem potentially known to not like this. See the [example
|
||||
config](configuration/examples.md) for disabling it if needed. Issues from
|
||||
Direct IO on unsupported filesystems are usually shown as startup errors.
|
||||
|
||||
#### Database corruption
|
||||
|
||||
If your database is corrupted *and* is failing to start (e.g. checksum mismatch), it may be recoverable but careful steps must be taken, and there is no guarantee it may be recoverable.
|
||||
If your database is corrupted *and* is failing to start (e.g. checksum
|
||||
mismatch), it may be recoverable but careful steps must be taken, and there is
|
||||
no guarantee it may be recoverable.
|
||||
|
||||
The first thing that can be done is launching conduwuit with the `rocksdb_repair` config option set to true. This will tell RocksDB to attempt to repair itself at launch. If this does not work, disable the option and continue reading.
|
||||
The first thing that can be done is launching conduwuit with the
|
||||
`rocksdb_repair` config option set to true. This will tell RocksDB to attempt to
|
||||
repair itself at launch. If this does not work, disable the option and continue
|
||||
reading.
|
||||
|
||||
RocksDB has the following recovery modes:
|
||||
|
||||
@@ -27,35 +59,59 @@ #### Database corruption
|
||||
- `PointInTime`
|
||||
- `SkipAnyCorruptedRecord`
|
||||
|
||||
By default, conduwuit uses `TolerateCorruptedTailRecords` as generally these may be due to bad federation and we can re-fetch the correct data over federation. The RocksDB default is `PointInTime` which will attempt to restore a "snapshot" of the data when it was last known to be good. This data can be either a few seconds old, or multiple minutes prior. `PointInTime` may not be suitable for default usage due to clients and servers possibly not being able to handle sudden "backwards time travels", and `AbsoluteConsistency` may be too strict.
|
||||
By default, conduwuit uses `TolerateCorruptedTailRecords` as generally these may
|
||||
be due to bad federation and we can re-fetch the correct data over federation.
|
||||
The RocksDB default is `PointInTime` which will attempt to restore a "snapshot"
|
||||
of the data when it was last known to be good. This data can be either a few
|
||||
seconds old, or multiple minutes prior. `PointInTime` may not be suitable for
|
||||
default usage due to clients and servers possibly not being able to handle
|
||||
sudden "backwards time travels", and `AbsoluteConsistency` may be too strict.
|
||||
|
||||
`AbsoluteConsistency` will fail to start the database if any sign of corruption is detected. `SkipAnyCorruptedRecord` will skip all forms of corruption unless it forbids the database from opening (e.g. too severe). Usage of `SkipAnyCorruptedRecord` voids any support as this may cause more damage and/or leave your database in a permanently inconsistent state, but it may do something if `PointInTime` does not work as a last ditch effort.
|
||||
`AbsoluteConsistency` will fail to start the database if any sign of corruption
|
||||
is detected. `SkipAnyCorruptedRecord` will skip all forms of corruption unless
|
||||
it forbids the database from opening (e.g. too severe). Usage of
|
||||
`SkipAnyCorruptedRecord` voids any support as this may cause more damage and/or
|
||||
leave your database in a permanently inconsistent state, but it may do something
|
||||
if `PointInTime` does not work as a last ditch effort.
|
||||
|
||||
With this in mind:
|
||||
|
||||
- First start conduwuit with the `PointInTime` recovery method. See the [example config](configuration/examples.md) for how to do this using `rocksdb_recovery_mode`
|
||||
- If your database successfully opens, clients are recommended to clear their client cache to account for the rollback
|
||||
- Leave your conduwuit running in `PointInTime` for at least 30-60 minutes so as much possible corruption is restored
|
||||
- If all goes will, you should be able to restore back to using `TolerateCorruptedTailRecords` and you have successfully recovered your database
|
||||
|
||||
## Media
|
||||
- First start conduwuit with the `PointInTime` recovery method. See the [example
|
||||
config](configuration/examples.md) for how to do this using
|
||||
`rocksdb_recovery_mode`
|
||||
- If your database successfully opens, clients are recommended to clear their
|
||||
client cache to account for the rollback
|
||||
- Leave your conduwuit running in `PointInTime` for at least 30-60 minutes so as
|
||||
much possible corruption is restored
|
||||
- If all goes will, you should be able to restore back to using
|
||||
`TolerateCorruptedTailRecords` and you have successfully recovered your database
|
||||
|
||||
## Debugging
|
||||
|
||||
Note that users should not really be debugging things. If you find yourself debugging and find the issue, please let us know and/or how we can fix it. Various debug commands can be found in `!admin debug`.
|
||||
Note that users should not really be debugging things. If you find yourself
|
||||
debugging and find the issue, please let us know and/or how we can fix it.
|
||||
Various debug commands can be found in `!admin debug`.
|
||||
|
||||
#### Debug/Trace log level
|
||||
|
||||
conduwuit builds without debug or trace log levels by default for at least performance reasons. This may change in the future and/or binaries providing such configurations may be provided. If you need to access debug/trace log levels, you will need to build without the `release_max_log_level` feature.
|
||||
conduwuit builds without debug or trace log levels by default for at least
|
||||
performance reasons. This may change in the future and/or binaries providing
|
||||
such configurations may be provided. If you need to access debug/trace log
|
||||
levels, you will need to build without the `release_max_log_level` feature.
|
||||
|
||||
#### Changing log level dynamically
|
||||
|
||||
conduwuit supports changing the tracing log environment filter on-the-fly using the admin command `!admin debug change-log-level`. This accepts a string **without quotes** the same format as the `log` config option.
|
||||
conduwuit supports changing the tracing log environment filter on-the-fly using
|
||||
the admin command `!admin debug change-log-level`. This accepts a string
|
||||
**without quotes** the same format as the `log` config option.
|
||||
|
||||
#### Pinging servers
|
||||
|
||||
conduwuit can ping other servers using `!admin debug ping`. This takes a server name and goes through the server discovery process and queries `/_matrix/federation/v1/version`. Errors are outputted.
|
||||
conduwuit can ping other servers using `!admin debug ping`. This takes a server
|
||||
name and goes through the server discovery process and queries
|
||||
`/_matrix/federation/v1/version`. Errors are outputted.
|
||||
|
||||
#### Allocator memory stats
|
||||
|
||||
When using jemalloc with jemallocator's `stats` feature, you can see conduwuit's jemalloc memory stats by using `!admin debug memory-stats`
|
||||
When using jemalloc with jemallocator's `stats` feature, you can see conduwuit's
|
||||
jemalloc memory stats by using `!admin debug memory-stats`
|
||||
|
||||
26
docs/turn.md
26
docs/turn.md
@@ -1,6 +1,8 @@
|
||||
# Setting up TURN/STURN
|
||||
|
||||
In order to make or receive calls, a TURN server is required. conduwuit suggests using [Coturn](https://github.com/coturn/coturn) for this purpose, which is also available as a Docker image.
|
||||
In order to make or receive calls, a TURN server is required. conduwuit suggests
|
||||
using [Coturn](https://github.com/coturn/coturn) for this purpose, which is also
|
||||
available as a Docker image.
|
||||
|
||||
### Configuration
|
||||
|
||||
@@ -12,20 +14,25 @@ ### Configuration
|
||||
realm=<your server domain>
|
||||
```
|
||||
|
||||
A common way to generate a suitable alphanumeric secret key is by using `pwgen -s 64 1`.
|
||||
A common way to generate a suitable alphanumeric secret key is by using `pwgen
|
||||
-s 64 1`.
|
||||
|
||||
These same values need to be set in conduwuit. See the [example config](configuration/examples.md) in the TURN section for configuring these and restart conduwuit after.
|
||||
These same values need to be set in conduwuit. See the [example
|
||||
config](configuration/examples.md) in the TURN section for configuring these and
|
||||
restart conduwuit after.
|
||||
|
||||
### Run
|
||||
|
||||
Run the [Coturn](https://hub.docker.com/r/coturn/coturn) image using
|
||||
|
||||
```bash
|
||||
docker run -d --network=host -v $(pwd)/coturn.conf:/etc/coturn/turnserver.conf coturn/coturn
|
||||
docker run -d --network=host -v
|
||||
$(pwd)/coturn.conf:/etc/coturn/turnserver.conf coturn/coturn
|
||||
```
|
||||
|
||||
or docker-compose. For the latter, paste the following section into a file called `docker-compose.yml`
|
||||
and run `docker compose up -d` in the same directory.
|
||||
or docker-compose. For the latter, paste the following section into a file
|
||||
called `docker-compose.yml` and run `docker compose up -d` in the same
|
||||
directory.
|
||||
|
||||
```yml
|
||||
version: 3
|
||||
@@ -39,6 +46,9 @@ ### Run
|
||||
- ./coturn.conf:/etc/coturn/turnserver.conf
|
||||
```
|
||||
|
||||
To understand why the host networking mode is used and explore alternative configuration options, please visit [Coturn's Docker documentation](https://github.com/coturn/coturn/blob/master/docker/coturn/README.md).
|
||||
To understand why the host networking mode is used and explore alternative
|
||||
configuration options, please visit [Coturn's Docker
|
||||
documentation](https://github.com/coturn/coturn/blob/master/docker/coturn/README.md).
|
||||
|
||||
For security recommendations see Synapse's [Coturn documentation](https://element-hq.github.io/synapse/latest/turn-howto.html).
|
||||
For security recommendations see Synapse's [Coturn
|
||||
documentation](https://element-hq.github.io/synapse/latest/turn-howto.html).
|
||||
|
||||
21
engage.toml
21
engage.toml
@@ -60,6 +60,11 @@ name = "markdownlint"
|
||||
group = "versions"
|
||||
script = "markdownlint --version"
|
||||
|
||||
[[task]]
|
||||
name = "dpkg"
|
||||
group = "versions"
|
||||
script = "dpkg --version"
|
||||
|
||||
[[task]]
|
||||
name = "cargo-audit"
|
||||
group = "security"
|
||||
@@ -68,7 +73,9 @@ script = "cargo audit -D warnings -D unmaintained -D unsound -D yanked"
|
||||
[[task]]
|
||||
name = "cargo-fmt"
|
||||
group = "lints"
|
||||
script = "cargo fmt --check -- --color=always"
|
||||
script = """
|
||||
cargo fmt --check -- --color=always
|
||||
"""
|
||||
|
||||
[[task]]
|
||||
name = "cargo-doc"
|
||||
@@ -79,6 +86,7 @@ env DIRENV_DEVSHELL=all-features \
|
||||
direnv exec . \
|
||||
cargo doc \
|
||||
--workspace \
|
||||
--profile test \
|
||||
--all-features \
|
||||
--no-deps \
|
||||
--document-private-items \
|
||||
@@ -91,6 +99,7 @@ group = "lints"
|
||||
script = """
|
||||
cargo clippy \
|
||||
--workspace \
|
||||
--profile test \
|
||||
--all-targets \
|
||||
--color=always \
|
||||
-- \
|
||||
@@ -105,6 +114,7 @@ env DIRENV_DEVSHELL=all-features \
|
||||
direnv exec . \
|
||||
cargo clippy \
|
||||
--workspace \
|
||||
--profile test \
|
||||
--all-targets \
|
||||
--all-features \
|
||||
--color=always \
|
||||
@@ -118,6 +128,7 @@ group = "lints"
|
||||
script = """
|
||||
cargo clippy \
|
||||
--workspace \
|
||||
--profile test \
|
||||
--features jemalloc \
|
||||
--all-targets \
|
||||
--color=always \
|
||||
@@ -156,6 +167,7 @@ env DIRENV_DEVSHELL=all-features \
|
||||
direnv exec . \
|
||||
cargo test \
|
||||
--workspace \
|
||||
--profile test \
|
||||
--all-targets \
|
||||
--all-features \
|
||||
--color=always \
|
||||
@@ -169,6 +181,7 @@ group = "tests"
|
||||
script = """
|
||||
cargo test \
|
||||
--workspace \
|
||||
--profile test \
|
||||
--all-targets \
|
||||
--color=always \
|
||||
-- \
|
||||
@@ -185,9 +198,11 @@ name = "nix-default"
|
||||
group = "tests"
|
||||
script = """
|
||||
env DIRENV_DEVSHELL=dynamic \
|
||||
CARGO_PROFILE="test" \
|
||||
direnv exec . \
|
||||
bin/nix-build-and-cache just .#default
|
||||
bin/nix-build-and-cache just .#default-test
|
||||
env DIRENV_DEVSHELL=dynamic \
|
||||
CARGO_PROFILE="test" \
|
||||
direnv exec . \
|
||||
nix run -L .#default -- --help
|
||||
nix run -L .#default-test -- --help && nix run -L .#default-test -- --version
|
||||
"""
|
||||
|
||||
205
flake.lock
generated
205
flake.lock
generated
@@ -9,11 +9,11 @@
|
||||
"nixpkgs-stable": "nixpkgs-stable"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1720542474,
|
||||
"narHash": "sha256-aKjJ/4l2I9+wNGTaOGRsuS3M1+IoTibqgEMPDikXm04=",
|
||||
"lastModified": 1724226964,
|
||||
"narHash": "sha256-cltFh4su2vcFidxKp7LuEgX3ZGLfPy0DCdrQZ/QTe68=",
|
||||
"owner": "zhaofengli",
|
||||
"repo": "attic",
|
||||
"rev": "6139576a3ce6bb992e0f6c3022528ec233e45f00",
|
||||
"rev": "6d9aeaef0a067d664cb11bb7704f7ec373d47fb2",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -27,15 +27,15 @@
|
||||
"inputs": {
|
||||
"devenv": "devenv",
|
||||
"flake-compat": "flake-compat_3",
|
||||
"nixpkgs": "nixpkgs_3",
|
||||
"pre-commit-hooks": "pre-commit-hooks"
|
||||
"git-hooks": "git-hooks",
|
||||
"nixpkgs": "nixpkgs_3"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1719923519,
|
||||
"narHash": "sha256-7Rhljj2fsklFRsu+eq7N683Z9qukmreMEj5C1GqCrSA=",
|
||||
"lastModified": 1724232775,
|
||||
"narHash": "sha256-6u2DycIEgrgNYlLxyGqdFVmBNiKIitnQKJ1pbRP5oko=",
|
||||
"owner": "cachix",
|
||||
"repo": "cachix",
|
||||
"rev": "4e9e71f78b9500fa6210cf1eaa4d75bdbab777c3",
|
||||
"rev": "03b6cb3f953097bff378fb8b9ea094bd091a4ec7",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -81,11 +81,11 @@
|
||||
"complement": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1720637557,
|
||||
"narHash": "sha256-oZz6nCmFmdJZpC+K1iOG2KkzTI6rlAmndxANPDVU7X0=",
|
||||
"lastModified": 1722323564,
|
||||
"narHash": "sha256-6w6/N8walz4Ayc9zu7iySqJRmGFukhkaICLn4dweAcA=",
|
||||
"owner": "matrix-org",
|
||||
"repo": "complement",
|
||||
"rev": "0d14432e010482ea9e13a6f7c47c1533c0c9d62f",
|
||||
"rev": "6e4426a9e63233f9821a4d2382bfed145244183f",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -103,11 +103,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1717025063,
|
||||
"narHash": "sha256-dIubLa56W9sNNz0e8jGxrX3CAkPXsq7snuFA/Ie6dn8=",
|
||||
"lastModified": 1722960479,
|
||||
"narHash": "sha256-NhCkJJQhD5GUib8zN9JrmYGMwt4lCRp6ZVNzIiYCl0Y=",
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"rev": "480dff0be03dac0e51a8dfc26e882b0d123a450e",
|
||||
"rev": "4c6c77920b8d44cd6660c1621dea6b3fc4b4c4f4",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -123,11 +123,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1720546058,
|
||||
"narHash": "sha256-iU2yVaPIZm5vMGdlT0+57vdB/aPq/V5oZFBRwYw+HBM=",
|
||||
"lastModified": 1724006180,
|
||||
"narHash": "sha256-PVxPj0Ga2fMYMtcT9ARCthF+4U71YkOT7ZjgD/vf1Aw=",
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"rev": "2d83156f23c43598cf44e152c33a59d3892f8b29",
|
||||
"rev": "7ce92819802bc583b7e82ebc08013a530f22209f",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -151,15 +151,15 @@
|
||||
],
|
||||
"pre-commit-hooks": [
|
||||
"cachix",
|
||||
"pre-commit-hooks"
|
||||
"git-hooks"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1719759336,
|
||||
"narHash": "sha256-3a34VL/QnHprl5gMy9xlx6d8J+iNp+W88Ex8smkgH9M=",
|
||||
"lastModified": 1723156315,
|
||||
"narHash": "sha256-0JrfahRMJ37Rf1i0iOOn+8Z4CLvbcGNwa2ChOAVrp/8=",
|
||||
"owner": "cachix",
|
||||
"repo": "devenv",
|
||||
"rev": "bb32aa986f2f695385e54428d0eaf7d05b31466e",
|
||||
"rev": "ff5eb4f2accbcda963af67f1a1159e3f6c7f5f91",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -209,11 +209,11 @@
|
||||
"rust-analyzer-src": "rust-analyzer-src"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1720852044,
|
||||
"narHash": "sha256-3NBYz8VuXuKU+8ONd9NFafCNjPEGHIZQ2Mdoam1a4mY=",
|
||||
"lastModified": 1724221791,
|
||||
"narHash": "sha256-mKX67QPnUybOopVph/LhOV1G/H4EvPxDIfSmbufrVdA=",
|
||||
"owner": "nix-community",
|
||||
"repo": "fenix",
|
||||
"rev": "5087b12a595ee73131a944d922f24d81dae05725",
|
||||
"rev": "e88b38a5a3834e039d413a88f8150a75ef6453ef",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -226,11 +226,11 @@
|
||||
"flake-compat": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1673956053,
|
||||
"narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=",
|
||||
"lastModified": 1696426674,
|
||||
"narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=",
|
||||
"owner": "edolstra",
|
||||
"repo": "flake-compat",
|
||||
"rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9",
|
||||
"rev": "0f9255e01c2351cc7d116c072cb317785dd33b33",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -272,22 +272,6 @@
|
||||
}
|
||||
},
|
||||
"flake-compat_4": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1696426674,
|
||||
"narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=",
|
||||
"owner": "edolstra",
|
||||
"repo": "flake-compat",
|
||||
"rev": "0f9255e01c2351cc7d116c072cb317785dd33b33",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "edolstra",
|
||||
"repo": "flake-compat",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"flake-compat_5": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1696426674,
|
||||
@@ -305,12 +289,15 @@
|
||||
}
|
||||
},
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1667395993,
|
||||
"narHash": "sha256-nuEHfE/LcWyuSWnS8t12N1wc105Qtau+/OdUAjtQ0rA=",
|
||||
"lastModified": 1710146030,
|
||||
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "5aed5285a952e0b949eb3ba02c12fa4fcfef535f",
|
||||
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -321,7 +308,7 @@
|
||||
},
|
||||
"flake-utils_2": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
"systems": "systems_2"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1689068808,
|
||||
@@ -339,7 +326,7 @@
|
||||
},
|
||||
"flake-utils_3": {
|
||||
"inputs": {
|
||||
"systems": "systems_2"
|
||||
"systems": "systems_3"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1710146030,
|
||||
@@ -356,11 +343,38 @@
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"git-hooks": {
|
||||
"inputs": {
|
||||
"flake-compat": [
|
||||
"cachix",
|
||||
"flake-compat"
|
||||
],
|
||||
"gitignore": "gitignore",
|
||||
"nixpkgs": [
|
||||
"cachix",
|
||||
"nixpkgs"
|
||||
],
|
||||
"nixpkgs-stable": "nixpkgs-stable_2"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1723202784,
|
||||
"narHash": "sha256-qbhjc/NEGaDbyy0ucycubq4N3//gDFFH3DOmp1D3u1Q=",
|
||||
"owner": "cachix",
|
||||
"repo": "git-hooks.nix",
|
||||
"rev": "c7012d0c18567c889b948781bc74a501e92275d1",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "cachix",
|
||||
"repo": "git-hooks.nix",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"gitignore": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"cachix",
|
||||
"pre-commit-hooks",
|
||||
"git-hooks",
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
@@ -381,11 +395,11 @@
|
||||
"liburing": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1720798442,
|
||||
"narHash": "sha256-gtPppAoksMLW4GuruQ36nf4EAqIA1Bs6V9Xcx8dBxrQ=",
|
||||
"lastModified": 1724199144,
|
||||
"narHash": "sha256-MVjnwO6EbKzzSrU51dSseLarZ1fRp+6SagAf/nE/XZU=",
|
||||
"owner": "axboe",
|
||||
"repo": "liburing",
|
||||
"rev": "1d674f83b7d0f07553ac44d99a401b05853d9dbe",
|
||||
"rev": "2d4e799017d64cd2f8304503eef9064931bb3fbd",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -494,11 +508,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1711401922,
|
||||
"narHash": "sha256-QoQqXoj8ClGo0sqD/qWKFWezgEwUL0SUh37/vY2jNhc=",
|
||||
"lastModified": 1723827930,
|
||||
"narHash": "sha256-EU+W5F6y2CVNxGrGIMpY7nSVYq72WRChYxF4zpjx0y4=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "07262b18b97000d16a4bdb003418bd2fb067a932",
|
||||
"rev": "d4a7a4d0e066278bfb0d77bd2a7adde1c0ec9e3d",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -542,11 +556,11 @@
|
||||
},
|
||||
"nixpkgs-stable": {
|
||||
"locked": {
|
||||
"lastModified": 1711460390,
|
||||
"narHash": "sha256-akSgjDZL6pVHEfSE6sz1DNSXuYX6hq+P/1Z5IoYWs7E=",
|
||||
"lastModified": 1720535198,
|
||||
"narHash": "sha256-zwVvxrdIzralnSbcpghA92tWu2DV2lwv89xZc8MTrbg=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "44733514b72e732bd49f5511bd0203dea9b9a434",
|
||||
"rev": "205fd4226592cc83fd4c0885a3e4c9c400efabb5",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -558,16 +572,16 @@
|
||||
},
|
||||
"nixpkgs-stable_2": {
|
||||
"locked": {
|
||||
"lastModified": 1718811006,
|
||||
"narHash": "sha256-0Y8IrGhRmBmT7HHXlxxepg2t8j1X90++qRN3lukGaIk=",
|
||||
"lastModified": 1720386169,
|
||||
"narHash": "sha256-NGKVY4PjzwAa4upkGtAMz1npHGoRzWotlSnVlqI40mo=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "03d771e513ce90147b65fe922d87d3a0356fc125",
|
||||
"rev": "194846768975b7ad2c4988bdb82572c00222c0d7",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-23.11",
|
||||
"ref": "nixos-24.05",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
@@ -590,11 +604,11 @@
|
||||
},
|
||||
"nixpkgs_3": {
|
||||
"locked": {
|
||||
"lastModified": 1719848872,
|
||||
"narHash": "sha256-H3+EC5cYuq+gQW8y0lSrrDZfH71LB4DAf+TDFyvwCNA=",
|
||||
"lastModified": 1722813957,
|
||||
"narHash": "sha256-IAoYyYnED7P8zrBFMnmp7ydaJfwTnwcnqxUElC1I26Y=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "00d80d13810dbfea8ab4ed1009b09100cca86ba8",
|
||||
"rev": "cb9a96f23c491c081b38eab96d22fa958043c9fa",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -606,11 +620,11 @@
|
||||
},
|
||||
"nixpkgs_4": {
|
||||
"locked": {
|
||||
"lastModified": 1720768451,
|
||||
"narHash": "sha256-EYekUHJE2gxeo2pM/zM9Wlqw1Uw2XTJXOSAO79ksc4Y=",
|
||||
"lastModified": 1724271409,
|
||||
"narHash": "sha256-z4nw9HxkaXEn+5OT8ljLVL2oataHvAzUQ1LEi8Fp+SY=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "7e7c39ea35c5cdd002cd4588b03a3fb9ece6fad9",
|
||||
"rev": "36a9aeaaa17a2d4348498275f9fe530cd4f9e519",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -646,43 +660,19 @@
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"pre-commit-hooks": {
|
||||
"inputs": {
|
||||
"flake-compat": "flake-compat_4",
|
||||
"gitignore": "gitignore",
|
||||
"nixpkgs": [
|
||||
"cachix",
|
||||
"nixpkgs"
|
||||
],
|
||||
"nixpkgs-stable": "nixpkgs-stable_2"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1719259945,
|
||||
"narHash": "sha256-F1h+XIsGKT9TkGO3omxDLEb/9jOOsI6NnzsXFsZhry4=",
|
||||
"owner": "cachix",
|
||||
"repo": "pre-commit-hooks.nix",
|
||||
"rev": "0ff4381bbb8f7a52ca4a851660fc7a437a4c6e07",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "cachix",
|
||||
"repo": "pre-commit-hooks.nix",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"rocksdb": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1720900786,
|
||||
"narHash": "sha256-Vta9Um/RRuWwZ46BjXftV06iWLm/j/9MX39emXUvSAY=",
|
||||
"lastModified": 1724285323,
|
||||
"narHash": "sha256-k60kreKQ0v+bQ16yBd2SfLYpuNjMw2qoRmZL/S3k6CU=",
|
||||
"owner": "girlbossceo",
|
||||
"repo": "rocksdb",
|
||||
"rev": "911f4243e69c2e320a7a209bf1f5f3ff5f825495",
|
||||
"rev": "5a67ad7ce46328578ee5587fb0c23faa03d14e67",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "girlbossceo",
|
||||
"ref": "v9.4.0",
|
||||
"ref": "v9.5.2",
|
||||
"repo": "rocksdb",
|
||||
"type": "github"
|
||||
}
|
||||
@@ -694,7 +684,7 @@
|
||||
"complement": "complement",
|
||||
"crane": "crane_2",
|
||||
"fenix": "fenix",
|
||||
"flake-compat": "flake-compat_5",
|
||||
"flake-compat": "flake-compat_4",
|
||||
"flake-utils": "flake-utils_3",
|
||||
"liburing": "liburing",
|
||||
"nix-filter": "nix-filter",
|
||||
@@ -705,11 +695,11 @@
|
||||
"rust-analyzer-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1720717809,
|
||||
"narHash": "sha256-6I+fm+nTLF/iaj7ffiFGlSY7POmubwUaPA/Wq0Bm53M=",
|
||||
"lastModified": 1724153119,
|
||||
"narHash": "sha256-WxpvDJDttkINkXmUA/W5o11lwLPYhATAgu0QUAacZ2g=",
|
||||
"owner": "rust-lang",
|
||||
"repo": "rust-analyzer",
|
||||
"rev": "ffbc5ad993d5cd2f3b8bcf9a511165470944ab91",
|
||||
"rev": "3723e5910c14f0ffbd13de474b8a8fcc74db04ce",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -748,6 +738,21 @@
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"systems_3": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
|
||||
123
flake.nix
123
flake.nix
@@ -9,14 +9,17 @@
|
||||
flake-utils.url = "github:numtide/flake-utils?ref=main";
|
||||
nix-filter.url = "github:numtide/nix-filter?ref=main";
|
||||
nixpkgs.url = "github:NixOS/nixpkgs?ref=nixos-unstable";
|
||||
rocksdb = { url = "github:girlbossceo/rocksdb?ref=v9.4.0"; flake = false; };
|
||||
rocksdb = { url = "github:girlbossceo/rocksdb?ref=v9.5.2"; flake = false; };
|
||||
liburing = { url = "github:axboe/liburing?ref=master"; flake = false; };
|
||||
};
|
||||
|
||||
outputs = inputs:
|
||||
inputs.flake-utils.lib.eachDefaultSystem (system:
|
||||
let
|
||||
pkgsHost = inputs.nixpkgs.legacyPackages.${system};
|
||||
pkgsHost = import inputs.nixpkgs{
|
||||
inherit system;
|
||||
config.permittedInsecurePackages = [ "olm-3.2.16" ];
|
||||
};
|
||||
pkgsHostStatic = pkgsHost.pkgsStatic;
|
||||
|
||||
# The Rust toolchain to use
|
||||
@@ -24,14 +27,14 @@
|
||||
file = ./rust-toolchain.toml;
|
||||
|
||||
# See also `rust-toolchain.toml`
|
||||
sha256 = "sha256-+syqAd2kX8KVa8/U2gz3blIQTTsYYt3U63xBWaGOSc8";
|
||||
sha256 = "sha256-3jVIIf5XPnUU1CRaTyAiO0XHVbJl12MSx3eucTXCjtE=";
|
||||
};
|
||||
|
||||
mkScope = pkgs: pkgs.lib.makeScope pkgs.newScope (self: {
|
||||
inherit pkgs;
|
||||
book = self.callPackage ./nix/pkgs/book {};
|
||||
complement = self.callPackage ./nix/pkgs/complement {};
|
||||
craneLib = ((inputs.crane.mkLib pkgs).overrideToolchain toolchain);
|
||||
craneLib = ((inputs.crane.mkLib pkgs).overrideToolchain (_: toolchain));
|
||||
inherit inputs;
|
||||
main = self.callPackage ./nix/pkgs/main {};
|
||||
oci-image = self.callPackage ./nix/pkgs/oci-image {};
|
||||
@@ -119,6 +122,9 @@
|
||||
# Needed for producing Debian packages
|
||||
cargo-deb
|
||||
|
||||
# Needed for CI to check validity of produced Debian packages (dpkg-deb)
|
||||
dpkg
|
||||
|
||||
# Needed for Complement
|
||||
go
|
||||
|
||||
@@ -133,6 +139,12 @@
|
||||
|
||||
# Useful for editing the book locally
|
||||
mdbook
|
||||
|
||||
# used for rust caching in CI to speed it up
|
||||
sccache
|
||||
|
||||
# needed so we can get rid of gcc and other unused deps that bloat OCI images
|
||||
removeReferencesTo
|
||||
])
|
||||
++ scope.main.buildInputs
|
||||
++ scope.main.propagatedBuildInputs
|
||||
@@ -144,6 +156,15 @@
|
||||
{
|
||||
packages = {
|
||||
default = scopeHost.main;
|
||||
default-debug = scopeHost.main.override {
|
||||
profile = "dev";
|
||||
# debug build users expect full logs
|
||||
disable_release_max_log_level = true;
|
||||
};
|
||||
default-test = scopeHost.main.override {
|
||||
profile = "test";
|
||||
disable_release_max_log_level = true;
|
||||
};
|
||||
all-features = scopeHost.main.override {
|
||||
all_features = true;
|
||||
disable_features = [
|
||||
@@ -153,6 +174,18 @@
|
||||
"experimental"
|
||||
];
|
||||
};
|
||||
all-features-debug = scopeHost.main.override {
|
||||
profile = "dev";
|
||||
all_features = true;
|
||||
# debug build users expect full logs
|
||||
disable_release_max_log_level = true;
|
||||
disable_features = [
|
||||
# this is non-functional on nix for some reason
|
||||
"hardened_malloc"
|
||||
# dont include experimental features
|
||||
"experimental"
|
||||
];
|
||||
};
|
||||
hmalloc = scopeHost.main.override { features = ["hardened_malloc"]; };
|
||||
|
||||
oci-image = scopeHost.oci-image;
|
||||
@@ -167,6 +200,20 @@
|
||||
];
|
||||
};
|
||||
};
|
||||
oci-image-all-features-debug = scopeHost.oci-image.override {
|
||||
main = scopeHost.main.override {
|
||||
profile = "dev";
|
||||
all_features = true;
|
||||
# debug build users expect full logs
|
||||
disable_release_max_log_level = true;
|
||||
disable_features = [
|
||||
# this is non-functional on nix for some reason
|
||||
"hardened_malloc"
|
||||
# dont include experimental features
|
||||
"experimental"
|
||||
];
|
||||
};
|
||||
};
|
||||
oci-image-hmalloc = scopeHost.oci-image.override {
|
||||
main = scopeHost.main.override {
|
||||
features = ["hardened_malloc"];
|
||||
@@ -201,6 +248,26 @@
|
||||
value = scopeCrossStatic.main;
|
||||
}
|
||||
|
||||
# An output for a statically-linked unstripped debug ("dev") binary
|
||||
{
|
||||
name = "${binaryName}-debug";
|
||||
value = scopeCrossStatic.main.override {
|
||||
profile = "dev";
|
||||
# debug build users expect full logs
|
||||
disable_release_max_log_level = true;
|
||||
};
|
||||
}
|
||||
|
||||
# An output for a statically-linked unstripped debug binary with the
|
||||
# "test" profile (for CI usage only)
|
||||
{
|
||||
name = "${binaryName}-test";
|
||||
value = scopeCrossStatic.main.override {
|
||||
profile = "test";
|
||||
disable_release_max_log_level = true;
|
||||
};
|
||||
}
|
||||
|
||||
# An output for a statically-linked binary with `--all-features`
|
||||
{
|
||||
name = "${binaryName}-all-features";
|
||||
@@ -215,6 +282,23 @@
|
||||
};
|
||||
}
|
||||
|
||||
# An output for a statically-linked unstripped debug ("dev") binary with `--all-features`
|
||||
{
|
||||
name = "${binaryName}-all-features-debug";
|
||||
value = scopeCrossStatic.main.override {
|
||||
profile = "dev";
|
||||
all_features = true;
|
||||
# debug build users expect full logs
|
||||
disable_release_max_log_level = true;
|
||||
disable_features = [
|
||||
# this is non-functional on nix for some reason
|
||||
"hardened_malloc"
|
||||
# dont include experimental features
|
||||
"experimental"
|
||||
];
|
||||
};
|
||||
}
|
||||
|
||||
# An output for a statically-linked binary with hardened_malloc
|
||||
{
|
||||
name = "${binaryName}-hmalloc";
|
||||
@@ -229,6 +313,18 @@
|
||||
value = scopeCrossStatic.oci-image;
|
||||
}
|
||||
|
||||
# An output for an OCI image based on that unstripped debug ("dev") binary
|
||||
{
|
||||
name = "oci-image-${crossSystem}-debug";
|
||||
value = scopeCrossStatic.oci-image.override {
|
||||
main = scopeCrossStatic.main.override {
|
||||
profile = "dev";
|
||||
# debug build users expect full logs
|
||||
disable_release_max_log_level = true;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
# An output for an OCI image based on that binary with `--all-features`
|
||||
{
|
||||
name = "oci-image-${crossSystem}-all-features";
|
||||
@@ -245,6 +341,25 @@
|
||||
};
|
||||
}
|
||||
|
||||
# An output for an OCI image based on that unstripped debug ("dev") binary with `--all-features`
|
||||
{
|
||||
name = "oci-image-${crossSystem}-all-features-debug";
|
||||
value = scopeCrossStatic.oci-image.override {
|
||||
main = scopeCrossStatic.main.override {
|
||||
profile = "dev";
|
||||
all_features = true;
|
||||
# debug build users expect full logs
|
||||
disable_release_max_log_level = true;
|
||||
disable_features = [
|
||||
# this is non-functional on nix for some reason
|
||||
"hardened_malloc"
|
||||
# dont include experimental features
|
||||
"experimental"
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
# An output for an OCI image based on that binary with hardened_malloc
|
||||
{
|
||||
name = "oci-image-${crossSystem}-hmalloc";
|
||||
|
||||
@@ -14,7 +14,7 @@ yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse = true
|
||||
ip_range_denylist = []
|
||||
url_preview_domain_contains_allowlist = ["*"]
|
||||
media_compat_file_link = false
|
||||
media_statup_check = false
|
||||
media_startup_check = false
|
||||
rocksdb_direct_io = false
|
||||
|
||||
[global.tls]
|
||||
|
||||
@@ -14,8 +14,15 @@
|
||||
|
||||
let
|
||||
main' = main.override {
|
||||
profile = "dev";
|
||||
features = ["axum_dual_protocol"];
|
||||
profile = "test";
|
||||
all_features = true;
|
||||
disable_release_max_log_level = true;
|
||||
disable_features = [
|
||||
# this is non-functional on nix for some reason
|
||||
"hardened_malloc"
|
||||
# dont include experimental features
|
||||
"experimental"
|
||||
];
|
||||
};
|
||||
|
||||
start = writeShellScriptBin "start" ''
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
, liburing
|
||||
, pkgsBuildHost
|
||||
, rocksdb
|
||||
, removeReferencesTo
|
||||
, rust
|
||||
, rust-jemalloc-sys
|
||||
, stdenv
|
||||
@@ -51,8 +52,14 @@ rust-jemalloc-sys' = (rust-jemalloc-sys.override {
|
||||
unprefixed = true;
|
||||
}).overrideAttrs (old: {
|
||||
configureFlags = old.configureFlags ++
|
||||
# we dont need docs
|
||||
[ "--disable-doc" ] ++
|
||||
# we dont need cxx/C++ integration
|
||||
[ "--disable-cxx" ] ++
|
||||
# tikv-jemalloc-sys/profiling feature
|
||||
lib.optional (featureEnabled "jemalloc_prof") "--enable-prof";
|
||||
lib.optional (featureEnabled "jemalloc_prof") "--enable-prof" ++
|
||||
# tikv-jemalloc-sys/stats feature
|
||||
(if (featureEnabled "jemalloc_stats") then [ "--enable-stats" ] else [ "--disable-stats" ]);
|
||||
});
|
||||
|
||||
buildDepsOnlyEnv =
|
||||
@@ -90,8 +97,8 @@ buildDepsOnlyEnv =
|
||||
else if stdenv.targetPlatform.isAarch64
|
||||
then lib.subtractLists [ "-DPORTABLE=1" ] old.cmakeFlags
|
||||
++ lib.optionals stdenv.targetPlatform.isAarch64 [
|
||||
# cortex-a55 == ARMv8.2-a
|
||||
"-DPORTABLE=armv8.2-a"
|
||||
# cortex-a73 == ARMv8-A
|
||||
"-DPORTABLE=armv8-a"
|
||||
]
|
||||
else old.cmakeFlags;
|
||||
});
|
||||
@@ -124,7 +131,7 @@ buildPackageEnv = {
|
||||
+ lib.optionalString stdenv.targetPlatform.isx86_64
|
||||
" -Ctarget-cpu=x86-64-v2"
|
||||
+ lib.optionalString stdenv.targetPlatform.isAarch64
|
||||
" -Ctarget-cpu=cortex-a55"; # cortex-a55 == ARMv8.2-a
|
||||
" -Ctarget-cpu=cortex-a73"; # cortex-a73 == ARMv8-A
|
||||
};
|
||||
|
||||
|
||||
@@ -149,7 +156,8 @@ commonAttrs = {
|
||||
];
|
||||
};
|
||||
|
||||
dontStrip = profile == "dev";
|
||||
dontStrip = profile == "dev" || profile == "test";
|
||||
dontPatchELF = profile == "dev" || profile == "test";
|
||||
|
||||
buildInputs = lib.optional (featureEnabled "jemalloc") rust-jemalloc-sys';
|
||||
|
||||
@@ -164,6 +172,9 @@ commonAttrs = {
|
||||
# differing values for `NIX_CFLAGS_COMPILE`, which contributes to spurious
|
||||
# rebuilds of bindgen and its depedents.
|
||||
jq
|
||||
|
||||
# needed so we can get rid of gcc and other unused deps that bloat OCI images
|
||||
removeReferencesTo
|
||||
]
|
||||
++ lib.optionals stdenv.isDarwin [
|
||||
# https://github.com/NixOS/nixpkgs/issues/206242
|
||||
@@ -173,6 +184,13 @@ commonAttrs = {
|
||||
# https://discourse.nixos.org/t/compile-a-rust-binary-on-macos-dbcrossbar/8612
|
||||
pkgsBuildHost.darwin.apple_sdk.frameworks.Security
|
||||
];
|
||||
|
||||
# for some reason gcc and other weird deps are added to OCI images and bloats it up
|
||||
#
|
||||
# <https://github.com/input-output-hk/haskell.nix/issues/829>
|
||||
postInstall = with pkgsBuildHost; ''
|
||||
find "$out" -type f -exec remove-references-to -t ${stdenv.cc} -t ${gcc} -t ${libgcc} -t ${linuxHeaders} -t ${libidn2} -t ${libunistring} '{}' +
|
||||
'';
|
||||
};
|
||||
in
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
# If you're having trouble making the relevant changes, bug a maintainer.
|
||||
|
||||
[toolchain]
|
||||
channel = "1.77.0"
|
||||
channel = "1.80.1"
|
||||
components = [
|
||||
# For rust-analyzer
|
||||
"rust-src",
|
||||
|
||||
@@ -29,6 +29,7 @@ release_max_log_level = [
|
||||
clap.workspace = true
|
||||
conduit-api.workspace = true
|
||||
conduit-core.workspace = true
|
||||
conduit-macros.workspace = true
|
||||
conduit-service.workspace = true
|
||||
const-str.workspace = true
|
||||
futures-util.workspace = true
|
||||
|
||||
66
src/admin/admin.rs
Normal file
66
src/admin/admin.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
use clap::Parser;
|
||||
use conduit::Result;
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
|
||||
use crate::{
|
||||
appservice, appservice::AppserviceCommand, check, check::CheckCommand, command::Command, debug,
|
||||
debug::DebugCommand, federation, federation::FederationCommand, media, media::MediaCommand, query,
|
||||
query::QueryCommand, room, room::RoomCommand, server, server::ServerCommand, user, user::UserCommand,
|
||||
};
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(name = "admin", version = env!("CARGO_PKG_VERSION"))]
|
||||
pub(super) enum AdminCommand {
|
||||
#[command(subcommand)]
|
||||
/// - Commands for managing appservices
|
||||
Appservices(AppserviceCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for managing local users
|
||||
Users(UserCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for managing rooms
|
||||
Rooms(RoomCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for managing federation
|
||||
Federation(FederationCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for managing the server
|
||||
Server(ServerCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for managing media
|
||||
Media(MediaCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for checking integrity
|
||||
Check(CheckCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for debugging things
|
||||
Debug(DebugCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Low-level queries for database getters and iterators
|
||||
Query(QueryCommand),
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, name = "command")]
|
||||
pub(super) async fn process(command: AdminCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||
use AdminCommand::*;
|
||||
|
||||
Ok(match command {
|
||||
Appservices(command) => appservice::process(command, context).await?,
|
||||
Media(command) => media::process(command, context).await?,
|
||||
Users(command) => user::process(command, context).await?,
|
||||
Rooms(command) => room::process(command, context).await?,
|
||||
Federation(command) => federation::process(command, context).await?,
|
||||
Server(command) => server::process(command, context).await?,
|
||||
Debug(command) => debug::process(command, context).await?,
|
||||
Query(command) => query::process(command, context).await?,
|
||||
Check(command) => check::process(command, context).await?,
|
||||
})
|
||||
}
|
||||
@@ -1,18 +1,20 @@
|
||||
use ruma::{api::appservice::Registration, events::room::message::RoomMessageEventContent};
|
||||
|
||||
use crate::{services, Result};
|
||||
use crate::{admin_command, Result};
|
||||
|
||||
pub(super) async fn register(body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
||||
#[admin_command]
|
||||
pub(super) async fn register(&self) -> Result<RoomMessageEventContent> {
|
||||
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||
{
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Expected code block in command body. Add --help for details.",
|
||||
));
|
||||
}
|
||||
|
||||
let appservice_config = body[1..body.len().checked_sub(1).unwrap()].join("\n");
|
||||
let appservice_config = self.body[1..self.body.len().checked_sub(1).unwrap()].join("\n");
|
||||
let parsed_config = serde_yaml::from_str::<Registration>(&appservice_config);
|
||||
match parsed_config {
|
||||
Ok(yaml) => match services().appservice.register_appservice(yaml).await {
|
||||
Ok(yaml) => match self.services.appservice.register_appservice(yaml).await {
|
||||
Ok(id) => Ok(RoomMessageEventContent::text_plain(format!(
|
||||
"Appservice registered with ID: {id}."
|
||||
))),
|
||||
@@ -26,8 +28,10 @@ pub(super) async fn register(body: Vec<&str>) -> Result<RoomMessageEventContent>
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn unregister(_body: Vec<&str>, appservice_identifier: String) -> Result<RoomMessageEventContent> {
|
||||
match services()
|
||||
#[admin_command]
|
||||
pub(super) async fn unregister(&self, appservice_identifier: String) -> Result<RoomMessageEventContent> {
|
||||
match self
|
||||
.services
|
||||
.appservice
|
||||
.unregister_appservice(&appservice_identifier)
|
||||
.await
|
||||
@@ -39,8 +43,10 @@ pub(super) async fn unregister(_body: Vec<&str>, appservice_identifier: String)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn show(_body: Vec<&str>, appservice_identifier: String) -> Result<RoomMessageEventContent> {
|
||||
match services()
|
||||
#[admin_command]
|
||||
pub(super) async fn show_appservice_config(&self, appservice_identifier: String) -> Result<RoomMessageEventContent> {
|
||||
match self
|
||||
.services
|
||||
.appservice
|
||||
.get_registration(&appservice_identifier)
|
||||
.await
|
||||
@@ -54,8 +60,9 @@ pub(super) async fn show(_body: Vec<&str>, appservice_identifier: String) -> Res
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn list(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
let appservices = services().appservice.iter_ids().await;
|
||||
#[admin_command]
|
||||
pub(super) async fn list_registered(&self) -> Result<RoomMessageEventContent> {
|
||||
let appservices = self.services.appservice.iter_ids().await;
|
||||
let output = format!("Appservices ({}): {}", appservices.len(), appservices.join(", "));
|
||||
Ok(RoomMessageEventContent::text_plain(output))
|
||||
}
|
||||
|
||||
@@ -2,12 +2,11 @@
|
||||
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
|
||||
use self::commands::*;
|
||||
use crate::admin_command_dispatch;
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
#[derive(Debug, Subcommand)]
|
||||
#[admin_command_dispatch]
|
||||
pub(super) enum AppserviceCommand {
|
||||
/// - Register an appservice using its registration YAML
|
||||
///
|
||||
@@ -29,24 +28,13 @@ pub(super) enum AppserviceCommand {
|
||||
/// - Show an appservice's config using its ID
|
||||
///
|
||||
/// You can find the ID using the `list-appservices` command.
|
||||
Show {
|
||||
#[clap(alias("show"))]
|
||||
ShowAppserviceConfig {
|
||||
/// The appservice to show
|
||||
appservice_identifier: String,
|
||||
},
|
||||
|
||||
/// - List all the currently registered appservices
|
||||
List,
|
||||
}
|
||||
|
||||
pub(super) async fn process(command: AppserviceCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
Ok(match command {
|
||||
AppserviceCommand::Register => register(body).await?,
|
||||
AppserviceCommand::Unregister {
|
||||
appservice_identifier,
|
||||
} => unregister(body, appservice_identifier).await?,
|
||||
AppserviceCommand::Show {
|
||||
appservice_identifier,
|
||||
} => show(body, appservice_identifier).await?,
|
||||
AppserviceCommand::List => list(body).await?,
|
||||
})
|
||||
#[clap(alias("list"))]
|
||||
ListRegistered,
|
||||
}
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
use conduit::Result;
|
||||
use conduit_macros::implement;
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
|
||||
use crate::services;
|
||||
use crate::Command;
|
||||
|
||||
/// Uses the iterator in `src/database/key_value/users.rs` to iterator over
|
||||
/// every user in our database (remote and local). Reports total count, any
|
||||
/// errors if there were any, etc
|
||||
pub(super) async fn check_all_users(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
#[implement(Command, params = "<'_>")]
|
||||
pub(super) async fn check_all_users(&self) -> Result<RoomMessageEventContent> {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().users.db.iter();
|
||||
let results = self.services.users.db.iter();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
let users = results.collect::<Vec<_>>();
|
||||
|
||||
@@ -4,16 +4,15 @@
|
||||
use conduit::Result;
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
|
||||
use self::commands::*;
|
||||
use crate::Command;
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(super) enum CheckCommand {
|
||||
AllUsers,
|
||||
}
|
||||
|
||||
pub(super) async fn process(command: CheckCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
pub(super) async fn process(command: CheckCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||
Ok(match command {
|
||||
CheckCommand::AllUsers => check_all_users(body).await?,
|
||||
CheckCommand::AllUsers => context.check_all_users().await?,
|
||||
})
|
||||
}
|
||||
|
||||
11
src/admin/command.rs
Normal file
11
src/admin/command.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
use std::time::SystemTime;
|
||||
|
||||
use conduit_service::Services;
|
||||
use ruma::EventId;
|
||||
|
||||
pub(crate) struct Command<'a> {
|
||||
pub(crate) services: &'a Services,
|
||||
pub(crate) body: &'a [&'a str],
|
||||
pub(crate) timer: SystemTime,
|
||||
pub(crate) reply_id: Option<&'a EventId>,
|
||||
}
|
||||
@@ -1,33 +1,33 @@
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::{Arc, Mutex},
|
||||
time::Instant,
|
||||
fmt::Write,
|
||||
sync::Arc,
|
||||
time::{Instant, SystemTime},
|
||||
};
|
||||
|
||||
use api::client::validate_and_add_event_id;
|
||||
use conduit::{
|
||||
debug, info, log,
|
||||
log::{capture, Capture},
|
||||
warn, Error, Result,
|
||||
};
|
||||
use conduit::{debug, debug_error, err, info, trace, utils, warn, Error, PduEvent, Result};
|
||||
use ruma::{
|
||||
api::{client::error::ErrorKind, federation::event::get_room_state},
|
||||
events::room::message::RoomMessageEventContent,
|
||||
CanonicalJsonObject, EventId, OwnedRoomOrAliasId, RoomId, RoomVersionId, ServerName,
|
||||
};
|
||||
use service::{rooms::event_handler::parse_incoming_pdu, sending::resolve_actual_dest, services, PduEvent};
|
||||
use tokio::sync::RwLock;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
pub(super) async fn echo(_body: Vec<&str>, message: Vec<String>) -> Result<RoomMessageEventContent> {
|
||||
use crate::admin_command;
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn echo(&self, message: Vec<String>) -> Result<RoomMessageEventContent> {
|
||||
let message = message.join(" ");
|
||||
|
||||
Ok(RoomMessageEventContent::notice_plain(message))
|
||||
}
|
||||
|
||||
pub(super) async fn get_auth_chain(_body: Vec<&str>, event_id: Box<EventId>) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
pub(super) async fn get_auth_chain(&self, event_id: Box<EventId>) -> Result<RoomMessageEventContent> {
|
||||
let event_id = Arc::<EventId>::from(event_id);
|
||||
if let Some(event) = services().rooms.timeline.get_pdu_json(&event_id)? {
|
||||
if let Some(event) = self.services.rooms.timeline.get_pdu_json(&event_id)? {
|
||||
let room_id_str = event
|
||||
.get("room_id")
|
||||
.and_then(|val| val.as_str())
|
||||
@@ -35,13 +35,16 @@ pub(super) async fn get_auth_chain(_body: Vec<&str>, event_id: Box<EventId>) ->
|
||||
|
||||
let room_id = <&RoomId>::try_from(room_id_str)
|
||||
.map_err(|_| Error::bad_database("Invalid room id field in event in database"))?;
|
||||
|
||||
let start = Instant::now();
|
||||
let count = services()
|
||||
let count = self
|
||||
.services
|
||||
.rooms
|
||||
.auth_chain
|
||||
.event_ids_iter(room_id, vec![event_id])
|
||||
.await?
|
||||
.count();
|
||||
|
||||
let elapsed = start.elapsed();
|
||||
Ok(RoomMessageEventContent::text_plain(format!(
|
||||
"Loaded auth chain with length {count} in {elapsed:?}"
|
||||
@@ -51,14 +54,16 @@ pub(super) async fn get_auth_chain(_body: Vec<&str>, event_id: Box<EventId>) ->
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn parse_pdu(body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
||||
#[admin_command]
|
||||
pub(super) async fn parse_pdu(&self) -> Result<RoomMessageEventContent> {
|
||||
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||
{
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Expected code block in command body. Add --help for details.",
|
||||
));
|
||||
}
|
||||
|
||||
let string = body[1..body.len().saturating_sub(1)].join("\n");
|
||||
let string = self.body[1..self.body.len().saturating_sub(1)].join("\n");
|
||||
match serde_json::from_str(&string) {
|
||||
Ok(value) => match ruma::signatures::reference_hash(&value, &RoomVersionId::V6) {
|
||||
Ok(hash) => {
|
||||
@@ -79,15 +84,17 @@ pub(super) async fn parse_pdu(body: Vec<&str>) -> Result<RoomMessageEventContent
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn get_pdu(_body: Vec<&str>, event_id: Box<EventId>) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
pub(super) async fn get_pdu(&self, event_id: Box<EventId>) -> Result<RoomMessageEventContent> {
|
||||
let mut outlier = false;
|
||||
let mut pdu_json = services()
|
||||
let mut pdu_json = self
|
||||
.services
|
||||
.rooms
|
||||
.timeline
|
||||
.get_non_outlier_pdu_json(&event_id)?;
|
||||
if pdu_json.is_none() {
|
||||
outlier = true;
|
||||
pdu_json = services().rooms.timeline.get_pdu_json(&event_id)?;
|
||||
pdu_json = self.services.rooms.timeline.get_pdu_json(&event_id)?;
|
||||
}
|
||||
match pdu_json {
|
||||
Some(json) => {
|
||||
@@ -106,69 +113,84 @@ pub(super) async fn get_pdu(_body: Vec<&str>, event_id: Box<EventId>) -> Result<
|
||||
}
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn get_remote_pdu_list(
|
||||
body: Vec<&str>, server: Box<ServerName>, force: bool,
|
||||
&self, server: Box<ServerName>, force: bool,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
if !services().globals.config.allow_federation {
|
||||
if !self.services.globals.config.allow_federation {
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Federation is disabled on this homeserver.",
|
||||
));
|
||||
}
|
||||
|
||||
if server == services().globals.server_name() {
|
||||
if server == self.services.globals.server_name() {
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for fetching local PDUs from \
|
||||
the database.",
|
||||
));
|
||||
}
|
||||
|
||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
||||
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||
{
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Expected code block in command body. Add --help for details.",
|
||||
));
|
||||
}
|
||||
|
||||
let list = body
|
||||
.clone()
|
||||
.drain(1..body.len().checked_sub(1).unwrap())
|
||||
let list = self
|
||||
.body
|
||||
.iter()
|
||||
.collect::<Vec<_>>()
|
||||
.drain(1..self.body.len().saturating_sub(1))
|
||||
.filter_map(|pdu| EventId::parse(pdu).ok())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let mut failed_count: usize = 0;
|
||||
let mut success_count: usize = 0;
|
||||
|
||||
for pdu in list {
|
||||
if force {
|
||||
if let Err(e) = get_remote_pdu(Vec::new(), Box::from(pdu), server.clone()).await {
|
||||
services()
|
||||
if let Err(e) = self.get_remote_pdu(Box::from(pdu), server.clone()).await {
|
||||
failed_count = failed_count.saturating_add(1);
|
||||
self.services
|
||||
.admin
|
||||
.send_message(RoomMessageEventContent::text_plain(format!(
|
||||
"Failed to get remote PDU, ignoring error: {e}"
|
||||
)))
|
||||
.await;
|
||||
warn!(%e, "Failed to get remote PDU, ignoring error");
|
||||
warn!("Failed to get remote PDU, ignoring error: {e}");
|
||||
} else {
|
||||
success_count = success_count.saturating_add(1);
|
||||
}
|
||||
} else {
|
||||
get_remote_pdu(Vec::new(), Box::from(pdu), server.clone()).await?;
|
||||
self.get_remote_pdu(Box::from(pdu), server.clone()).await?;
|
||||
success_count = success_count.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(RoomMessageEventContent::text_plain("Fetched list of remote PDUs."))
|
||||
Ok(RoomMessageEventContent::text_plain(format!(
|
||||
"Fetched {success_count} remote PDUs successfully with {failed_count} failures"
|
||||
)))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn get_remote_pdu(
|
||||
_body: Vec<&str>, event_id: Box<EventId>, server: Box<ServerName>,
|
||||
&self, event_id: Box<EventId>, server: Box<ServerName>,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
if !services().globals.config.allow_federation {
|
||||
if !self.services.globals.config.allow_federation {
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Federation is disabled on this homeserver.",
|
||||
));
|
||||
}
|
||||
|
||||
if server == services().globals.server_name() {
|
||||
if server == self.services.globals.server_name() {
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for fetching local PDUs.",
|
||||
));
|
||||
}
|
||||
|
||||
match services()
|
||||
match self
|
||||
.services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
&server,
|
||||
@@ -187,9 +209,13 @@ pub(super) async fn get_remote_pdu(
|
||||
Error::BadRequest(ErrorKind::Unknown, "Received response from server but failed to parse PDU")
|
||||
})?;
|
||||
|
||||
debug!("Attempting to parse PDU: {:?}", &response.pdu);
|
||||
trace!("Attempting to parse PDU: {:?}", &response.pdu);
|
||||
let parsed_pdu = {
|
||||
let parsed_result = parse_incoming_pdu(&response.pdu);
|
||||
let parsed_result = self
|
||||
.services
|
||||
.rooms
|
||||
.event_handler
|
||||
.parse_incoming_pdu(&response.pdu);
|
||||
let (event_id, value, room_id) = match parsed_result {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
@@ -207,9 +233,8 @@ pub(super) async fn get_remote_pdu(
|
||||
let pub_key_map = RwLock::new(BTreeMap::new());
|
||||
|
||||
debug!("Attempting to fetch homeserver signing keys for {server}");
|
||||
services()
|
||||
.rooms
|
||||
.event_handler
|
||||
self.services
|
||||
.server_keys
|
||||
.fetch_required_signing_keys(parsed_pdu.iter().map(|(_event_id, event, _room_id)| event), &pub_key_map)
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
@@ -217,7 +242,7 @@ pub(super) async fn get_remote_pdu(
|
||||
});
|
||||
|
||||
info!("Attempting to handle event ID {event_id} as backfilled PDU");
|
||||
services()
|
||||
self.services
|
||||
.rooms
|
||||
.timeline
|
||||
.backfill_pdu(&server, response.pdu, &pub_key_map)
|
||||
@@ -236,9 +261,11 @@ pub(super) async fn get_remote_pdu(
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn get_room_state(_body: Vec<&str>, room: OwnedRoomOrAliasId) -> Result<RoomMessageEventContent> {
|
||||
let room_id = services().rooms.alias.resolve(&room).await?;
|
||||
let room_state = services()
|
||||
#[admin_command]
|
||||
pub(super) async fn get_room_state(&self, room: OwnedRoomOrAliasId) -> Result<RoomMessageEventContent> {
|
||||
let room_id = self.services.rooms.alias.resolve(&room).await?;
|
||||
let room_state = self
|
||||
.services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.room_state_full(&room_id)
|
||||
@@ -263,8 +290,9 @@ pub(super) async fn get_room_state(_body: Vec<&str>, room: OwnedRoomOrAliasId) -
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!("```json\n{json}\n```")))
|
||||
}
|
||||
|
||||
pub(super) async fn ping(_body: Vec<&str>, server: Box<ServerName>) -> Result<RoomMessageEventContent> {
|
||||
if server == services().globals.server_name() {
|
||||
#[admin_command]
|
||||
pub(super) async fn ping(&self, server: Box<ServerName>) -> Result<RoomMessageEventContent> {
|
||||
if server == self.services.globals.server_name() {
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Not allowed to send federation requests to ourselves.",
|
||||
));
|
||||
@@ -272,7 +300,8 @@ pub(super) async fn ping(_body: Vec<&str>, server: Box<ServerName>) -> Result<Ro
|
||||
|
||||
let timer = tokio::time::Instant::now();
|
||||
|
||||
match services()
|
||||
match self
|
||||
.services
|
||||
.sending
|
||||
.send_federation_request(&server, ruma::api::federation::discovery::get_server_version::v1::Request {})
|
||||
.await
|
||||
@@ -301,23 +330,23 @@ pub(super) async fn ping(_body: Vec<&str>, server: Box<ServerName>) -> Result<Ro
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn force_device_list_updates(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
pub(super) async fn force_device_list_updates(&self) -> Result<RoomMessageEventContent> {
|
||||
// Force E2EE device list updates for all users
|
||||
for user_id in services().users.iter().filter_map(Result::ok) {
|
||||
services().users.mark_device_key_update(&user_id)?;
|
||||
for user_id in self.services.users.iter().filter_map(Result::ok) {
|
||||
self.services.users.mark_device_key_update(&user_id)?;
|
||||
}
|
||||
Ok(RoomMessageEventContent::text_plain(
|
||||
"Marked all devices for all users as having new keys to update",
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn change_log_level(
|
||||
_body: Vec<&str>, filter: Option<String>, reset: bool,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
pub(super) async fn change_log_level(&self, filter: Option<String>, reset: bool) -> Result<RoomMessageEventContent> {
|
||||
let handles = &["console"];
|
||||
|
||||
if reset {
|
||||
let old_filter_layer = match EnvFilter::try_new(&services().globals.config.log) {
|
||||
let old_filter_layer = match EnvFilter::try_new(&self.services.globals.config.log) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
return Ok(RoomMessageEventContent::text_plain(format!(
|
||||
@@ -326,7 +355,8 @@ pub(super) async fn change_log_level(
|
||||
},
|
||||
};
|
||||
|
||||
match services()
|
||||
match self
|
||||
.services
|
||||
.server
|
||||
.log
|
||||
.reload
|
||||
@@ -335,7 +365,7 @@ pub(super) async fn change_log_level(
|
||||
Ok(()) => {
|
||||
return Ok(RoomMessageEventContent::text_plain(format!(
|
||||
"Successfully changed log level back to config value {}",
|
||||
services().globals.config.log
|
||||
self.services.globals.config.log
|
||||
)));
|
||||
},
|
||||
Err(e) => {
|
||||
@@ -356,7 +386,8 @@ pub(super) async fn change_log_level(
|
||||
},
|
||||
};
|
||||
|
||||
match services()
|
||||
match self
|
||||
.services
|
||||
.server
|
||||
.log
|
||||
.reload
|
||||
@@ -376,19 +407,21 @@ pub(super) async fn change_log_level(
|
||||
Ok(RoomMessageEventContent::text_plain("No log level was specified."))
|
||||
}
|
||||
|
||||
pub(super) async fn sign_json(body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
||||
#[admin_command]
|
||||
pub(super) async fn sign_json(&self) -> Result<RoomMessageEventContent> {
|
||||
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||
{
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Expected code block in command body. Add --help for details.",
|
||||
));
|
||||
}
|
||||
|
||||
let string = body[1..body.len().checked_sub(1).unwrap()].join("\n");
|
||||
let string = self.body[1..self.body.len().checked_sub(1).unwrap()].join("\n");
|
||||
match serde_json::from_str(&string) {
|
||||
Ok(mut value) => {
|
||||
ruma::signatures::sign_json(
|
||||
services().globals.server_name().as_str(),
|
||||
services().globals.keypair(),
|
||||
self.services.globals.server_name().as_str(),
|
||||
self.services.globals.keypair(),
|
||||
&mut value,
|
||||
)
|
||||
.expect("our request json is what ruma expects");
|
||||
@@ -399,21 +432,22 @@ pub(super) async fn sign_json(body: Vec<&str>) -> Result<RoomMessageEventContent
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn verify_json(body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
||||
#[admin_command]
|
||||
pub(super) async fn verify_json(&self) -> Result<RoomMessageEventContent> {
|
||||
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||
{
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Expected code block in command body. Add --help for details.",
|
||||
));
|
||||
}
|
||||
|
||||
let string = body[1..body.len().checked_sub(1).unwrap()].join("\n");
|
||||
let string = self.body[1..self.body.len().checked_sub(1).unwrap()].join("\n");
|
||||
match serde_json::from_str(&string) {
|
||||
Ok(value) => {
|
||||
let pub_key_map = RwLock::new(BTreeMap::new());
|
||||
|
||||
services()
|
||||
.rooms
|
||||
.event_handler
|
||||
self.services
|
||||
.server_keys
|
||||
.fetch_required_signing_keys([&value], &pub_key_map)
|
||||
.await?;
|
||||
|
||||
@@ -429,19 +463,22 @@ pub(super) async fn verify_json(body: Vec<&str>) -> Result<RoomMessageEventConte
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(_body))]
|
||||
pub(super) async fn first_pdu_in_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||
if !services()
|
||||
#[admin_command]
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub(super) async fn first_pdu_in_room(&self, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||
if !self
|
||||
.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.server_in_room(&services().globals.config.server_name, &room_id)?
|
||||
.server_in_room(&self.services.globals.config.server_name, &room_id)?
|
||||
{
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"We are not participating in the room / we don't know about the room ID.",
|
||||
));
|
||||
}
|
||||
|
||||
let first_pdu = services()
|
||||
let first_pdu = self
|
||||
.services
|
||||
.rooms
|
||||
.timeline
|
||||
.first_pdu_in_room(&room_id)?
|
||||
@@ -450,19 +487,22 @@ pub(super) async fn first_pdu_in_room(_body: Vec<&str>, room_id: Box<RoomId>) ->
|
||||
Ok(RoomMessageEventContent::text_plain(format!("{first_pdu:?}")))
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(_body))]
|
||||
pub(super) async fn latest_pdu_in_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||
if !services()
|
||||
#[admin_command]
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub(super) async fn latest_pdu_in_room(&self, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||
if !self
|
||||
.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.server_in_room(&services().globals.config.server_name, &room_id)?
|
||||
.server_in_room(&self.services.globals.config.server_name, &room_id)?
|
||||
{
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"We are not participating in the room / we don't know about the room ID.",
|
||||
));
|
||||
}
|
||||
|
||||
let latest_pdu = services()
|
||||
let latest_pdu = self
|
||||
.services
|
||||
.rooms
|
||||
.timeline
|
||||
.latest_pdu_in_room(&room_id)?
|
||||
@@ -471,32 +511,36 @@ pub(super) async fn latest_pdu_in_room(_body: Vec<&str>, room_id: Box<RoomId>) -
|
||||
Ok(RoomMessageEventContent::text_plain(format!("{latest_pdu:?}")))
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(_body))]
|
||||
#[admin_command]
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub(super) async fn force_set_room_state_from_server(
|
||||
_body: Vec<&str>, server_name: Box<ServerName>, room_id: Box<RoomId>,
|
||||
&self, room_id: Box<RoomId>, server_name: Box<ServerName>,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
if !services()
|
||||
if !self
|
||||
.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.server_in_room(&services().globals.config.server_name, &room_id)?
|
||||
.server_in_room(&self.services.globals.config.server_name, &room_id)?
|
||||
{
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"We are not participating in the room / we don't know about the room ID.",
|
||||
));
|
||||
}
|
||||
|
||||
let first_pdu = services()
|
||||
let first_pdu = self
|
||||
.services
|
||||
.rooms
|
||||
.timeline
|
||||
.latest_pdu_in_room(&room_id)?
|
||||
.ok_or_else(|| Error::bad_database("Failed to find the latest PDU in database"))?;
|
||||
|
||||
let room_version = services().rooms.state.get_room_version(&room_id)?;
|
||||
let room_version = self.services.rooms.state.get_room_version(&room_id)?;
|
||||
|
||||
let mut state: HashMap<u64, Arc<EventId>> = HashMap::new();
|
||||
let pub_key_map = RwLock::new(BTreeMap::new());
|
||||
|
||||
let remote_state_response = services()
|
||||
let remote_state_response = self
|
||||
.services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
&server_name,
|
||||
@@ -510,7 +554,7 @@ pub(super) async fn force_set_room_state_from_server(
|
||||
let mut events = Vec::with_capacity(remote_state_response.pdus.len());
|
||||
|
||||
for pdu in remote_state_response.pdus.clone() {
|
||||
events.push(match parse_incoming_pdu(&pdu) {
|
||||
events.push(match self.services.rooms.event_handler.parse_incoming_pdu(&pdu) {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
warn!("Could not parse PDU, ignoring: {e}");
|
||||
@@ -520,9 +564,8 @@ pub(super) async fn force_set_room_state_from_server(
|
||||
}
|
||||
|
||||
info!("Fetching required signing keys for all the state events we got");
|
||||
services()
|
||||
.rooms
|
||||
.event_handler
|
||||
self.services
|
||||
.server_keys
|
||||
.fetch_required_signing_keys(events.iter().map(|(_event_id, event, _room_id)| event), &pub_key_map)
|
||||
.await?;
|
||||
|
||||
@@ -530,23 +573,24 @@ pub(super) async fn force_set_room_state_from_server(
|
||||
for result in remote_state_response
|
||||
.pdus
|
||||
.iter()
|
||||
.map(|pdu| validate_and_add_event_id(pdu, &room_version, &pub_key_map))
|
||||
.map(|pdu| validate_and_add_event_id(self.services, pdu, &room_version, &pub_key_map))
|
||||
{
|
||||
let Ok((event_id, value)) = result.await else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let pdu = PduEvent::from_id_val(&event_id, value.clone()).map_err(|e| {
|
||||
warn!("Invalid PDU in fetching remote room state PDUs response: {} {:?}", e, value);
|
||||
Error::BadServerResponse("Invalid PDU in send_join response.")
|
||||
debug_error!("Invalid PDU in fetching remote room state PDUs response: {value:#?}");
|
||||
err!(BadServerResponse(debug_error!("Invalid PDU in send_join response: {e:?}")))
|
||||
})?;
|
||||
|
||||
services()
|
||||
self.services
|
||||
.rooms
|
||||
.outlier
|
||||
.add_pdu_outlier(&event_id, &value)?;
|
||||
if let Some(state_key) = &pdu.state_key {
|
||||
let shortstatekey = services()
|
||||
let shortstatekey = self
|
||||
.services
|
||||
.rooms
|
||||
.short
|
||||
.get_or_create_shortstatekey(&pdu.kind.to_string().into(), state_key)?;
|
||||
@@ -558,32 +602,34 @@ pub(super) async fn force_set_room_state_from_server(
|
||||
for result in remote_state_response
|
||||
.auth_chain
|
||||
.iter()
|
||||
.map(|pdu| validate_and_add_event_id(pdu, &room_version, &pub_key_map))
|
||||
.map(|pdu| validate_and_add_event_id(self.services, pdu, &room_version, &pub_key_map))
|
||||
{
|
||||
let Ok((event_id, value)) = result.await else {
|
||||
continue;
|
||||
};
|
||||
|
||||
services()
|
||||
self.services
|
||||
.rooms
|
||||
.outlier
|
||||
.add_pdu_outlier(&event_id, &value)?;
|
||||
}
|
||||
|
||||
let new_room_state = services()
|
||||
let new_room_state = self
|
||||
.services
|
||||
.rooms
|
||||
.event_handler
|
||||
.resolve_state(room_id.clone().as_ref(), &room_version, state)
|
||||
.await?;
|
||||
|
||||
info!("Forcing new room state");
|
||||
let (short_state_hash, new, removed) = services()
|
||||
let (short_state_hash, new, removed) = self
|
||||
.services
|
||||
.rooms
|
||||
.state_compressor
|
||||
.save_state(room_id.clone().as_ref(), new_room_state)?;
|
||||
|
||||
let state_lock = services().rooms.state.mutex.lock(&room_id).await;
|
||||
services()
|
||||
let state_lock = self.services.rooms.state.mutex.lock(&room_id).await;
|
||||
self.services
|
||||
.rooms
|
||||
.state
|
||||
.force_state(room_id.clone().as_ref(), short_state_hash, new, removed, &state_lock)
|
||||
@@ -593,7 +639,10 @@ pub(super) async fn force_set_room_state_from_server(
|
||||
"Updating joined counts for room just in case (e.g. we may have found a difference in the room's \
|
||||
m.room.member state"
|
||||
);
|
||||
services().rooms.state_cache.update_joined_count(&room_id)?;
|
||||
self.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.update_joined_count(&room_id)?;
|
||||
|
||||
drop(state_lock);
|
||||
|
||||
@@ -602,61 +651,99 @@ pub(super) async fn force_set_room_state_from_server(
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_true_destination(
|
||||
_body: Vec<&str>, server_name: Box<ServerName>, no_cache: bool,
|
||||
#[admin_command]
|
||||
pub(super) async fn get_signing_keys(
|
||||
&self, server_name: Option<Box<ServerName>>, _cached: bool,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
if !services().globals.config.allow_federation {
|
||||
let server_name = server_name.unwrap_or_else(|| self.services.server.config.server_name.clone().into());
|
||||
let signing_keys = self.services.globals.signing_keys_for(&server_name)?;
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"```rs\n{signing_keys:#?}\n```"
|
||||
)))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
#[allow(dead_code)]
|
||||
pub(super) async fn get_verify_keys(
|
||||
&self, server_name: Option<Box<ServerName>>, cached: bool,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
let server_name = server_name.unwrap_or_else(|| self.services.server.config.server_name.clone().into());
|
||||
let mut out = String::new();
|
||||
|
||||
if cached {
|
||||
writeln!(out, "| Key ID | VerifyKey |")?;
|
||||
writeln!(out, "| --- | --- |")?;
|
||||
for (key_id, verify_key) in self.services.globals.verify_keys_for(&server_name)? {
|
||||
writeln!(out, "| {key_id} | {verify_key:?} |")?;
|
||||
}
|
||||
|
||||
return Ok(RoomMessageEventContent::notice_markdown(out));
|
||||
}
|
||||
|
||||
let signature_ids: Vec<String> = Vec::new();
|
||||
let keys = self
|
||||
.services
|
||||
.server_keys
|
||||
.fetch_signing_keys_for_server(&server_name, signature_ids)
|
||||
.await?;
|
||||
|
||||
writeln!(out, "| Key ID | Public Key |")?;
|
||||
writeln!(out, "| --- | --- |")?;
|
||||
for (key_id, key) in keys {
|
||||
writeln!(out, "| {key_id} | {key} |")?;
|
||||
}
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(out))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn resolve_true_destination(
|
||||
&self, server_name: Box<ServerName>, no_cache: bool,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
if !self.services.globals.config.allow_federation {
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Federation is disabled on this homeserver.",
|
||||
));
|
||||
}
|
||||
|
||||
if server_name == services().globals.config.server_name {
|
||||
if server_name == self.services.globals.config.server_name {
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for fetching local PDUs.",
|
||||
));
|
||||
}
|
||||
|
||||
let filter: &capture::Filter = &|data| {
|
||||
data.level() <= log::Level::DEBUG
|
||||
&& data.mod_name().starts_with("conduit")
|
||||
&& matches!(data.span_name(), "actual" | "well-known" | "srv")
|
||||
};
|
||||
let actual = self
|
||||
.services
|
||||
.resolver
|
||||
.resolve_actual_dest(&server_name, !no_cache)
|
||||
.await?;
|
||||
|
||||
let state = &services().server.log.capture;
|
||||
let logs = Arc::new(Mutex::new(String::new()));
|
||||
let capture = Capture::new(state, Some(filter), capture::fmt_markdown(logs.clone()));
|
||||
let msg = format!("Destination: {}\nHostname URI: {}", actual.dest, actual.host,);
|
||||
|
||||
let capture_scope = capture.start();
|
||||
let actual = resolve_actual_dest(&server_name, !no_cache).await?;
|
||||
drop(capture_scope);
|
||||
|
||||
let msg = format!(
|
||||
"{}\nDestination: {}\nHostname URI: {}",
|
||||
logs.lock().expect("locked"),
|
||||
actual.dest,
|
||||
actual.host,
|
||||
);
|
||||
Ok(RoomMessageEventContent::text_markdown(msg))
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub(super) fn memory_stats() -> RoomMessageEventContent {
|
||||
#[admin_command]
|
||||
pub(super) async fn memory_stats(&self) -> Result<RoomMessageEventContent> {
|
||||
let html_body = conduit::alloc::memory_stats();
|
||||
|
||||
if html_body.is_none() {
|
||||
return RoomMessageEventContent::text_plain("malloc stats are not supported on your compiled malloc.");
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"malloc stats are not supported on your compiled malloc.",
|
||||
));
|
||||
}
|
||||
|
||||
RoomMessageEventContent::text_html(
|
||||
Ok(RoomMessageEventContent::text_html(
|
||||
"This command's output can only be viewed by clients that render HTML.".to_owned(),
|
||||
html_body.expect("string result"),
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(tokio_unstable)]
|
||||
pub(super) async fn runtime_metrics(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
let out = services().server.metrics.runtime_metrics().map_or_else(
|
||||
#[admin_command]
|
||||
pub(super) async fn runtime_metrics(&self) -> Result<RoomMessageEventContent> {
|
||||
let out = self.services.server.metrics.runtime_metrics().map_or_else(
|
||||
|| "Runtime metrics are not available.".to_owned(),
|
||||
|metrics| format!("```rs\n{metrics:#?}\n```"),
|
||||
);
|
||||
@@ -665,15 +752,17 @@ pub(super) async fn runtime_metrics(_body: Vec<&str>) -> Result<RoomMessageEvent
|
||||
}
|
||||
|
||||
#[cfg(not(tokio_unstable))]
|
||||
pub(super) async fn runtime_metrics(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
pub(super) async fn runtime_metrics(&self) -> Result<RoomMessageEventContent> {
|
||||
Ok(RoomMessageEventContent::text_markdown(
|
||||
"Runtime metrics require building with `tokio_unstable`.",
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(tokio_unstable)]
|
||||
pub(super) async fn runtime_interval(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
let out = services().server.metrics.runtime_interval().map_or_else(
|
||||
#[admin_command]
|
||||
pub(super) async fn runtime_interval(&self) -> Result<RoomMessageEventContent> {
|
||||
let out = self.services.server.metrics.runtime_interval().map_or_else(
|
||||
|| "Runtime metrics are not available.".to_owned(),
|
||||
|metrics| format!("```rs\n{metrics:#?}\n```"),
|
||||
);
|
||||
@@ -682,8 +771,61 @@ pub(super) async fn runtime_interval(_body: Vec<&str>) -> Result<RoomMessageEven
|
||||
}
|
||||
|
||||
#[cfg(not(tokio_unstable))]
|
||||
pub(super) async fn runtime_interval(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
pub(super) async fn runtime_interval(&self) -> Result<RoomMessageEventContent> {
|
||||
Ok(RoomMessageEventContent::text_markdown(
|
||||
"Runtime metrics require building with `tokio_unstable`.",
|
||||
))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn time(&self) -> Result<RoomMessageEventContent> {
|
||||
let now = SystemTime::now();
|
||||
Ok(RoomMessageEventContent::text_markdown(utils::time::format(now, "%+")))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn list_dependencies(&self, names: bool) -> Result<RoomMessageEventContent> {
|
||||
if names {
|
||||
let out = info::cargo::dependencies_names().join(" ");
|
||||
return Ok(RoomMessageEventContent::notice_markdown(out));
|
||||
}
|
||||
|
||||
let deps = info::cargo::dependencies();
|
||||
let mut out = String::new();
|
||||
writeln!(out, "| name | version | features |")?;
|
||||
writeln!(out, "| ---- | ------- | -------- |")?;
|
||||
for (name, dep) in deps {
|
||||
let version = dep.try_req().unwrap_or("*");
|
||||
let feats = dep.req_features();
|
||||
let feats = if !feats.is_empty() {
|
||||
feats.join(" ")
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
writeln!(out, "{name} | {version} | {feats}")?;
|
||||
}
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(out))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn database_stats(
|
||||
&self, property: Option<String>, map: Option<String>,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
let property = property.unwrap_or_else(|| "rocksdb.stats".to_owned());
|
||||
let map_name = map.as_ref().map_or(utils::string::EMPTY, String::as_str);
|
||||
|
||||
let mut out = String::new();
|
||||
for (name, map) in self.services.db.iter_maps() {
|
||||
if !map_name.is_empty() && *map_name != *name {
|
||||
continue;
|
||||
}
|
||||
|
||||
let res = map.property(&property)?;
|
||||
let res = res.trim();
|
||||
writeln!(out, "##### {name}:\n```\n{res}\n```")?;
|
||||
}
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(out))
|
||||
}
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, EventId, OwnedRoomOrAliasId, RoomId, ServerName};
|
||||
use tester::TesterCommand;
|
||||
use ruma::{EventId, OwnedRoomOrAliasId, RoomId, ServerName};
|
||||
|
||||
use self::commands::*;
|
||||
use self::tester::TesterCommand;
|
||||
use crate::admin_command_dispatch;
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
#[admin_command_dispatch]
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(super) enum DebugCommand {
|
||||
/// - Echo input of admin command
|
||||
Echo {
|
||||
@@ -76,6 +76,14 @@ pub(super) enum DebugCommand {
|
||||
room_id: OwnedRoomOrAliasId,
|
||||
},
|
||||
|
||||
/// - Get and display signing keys from local cache or remote server.
|
||||
GetSigningKeys {
|
||||
server_name: Option<Box<ServerName>>,
|
||||
|
||||
#[arg(short, long)]
|
||||
cached: bool,
|
||||
},
|
||||
|
||||
/// - Sends a federation request to the remote server's
|
||||
/// `/_matrix/federation/v1/version` endpoint and measures the latency it
|
||||
/// took for the server to respond
|
||||
@@ -167,61 +175,26 @@ pub(super) enum DebugCommand {
|
||||
/// invocation.
|
||||
RuntimeInterval,
|
||||
|
||||
/// - Print the current time
|
||||
Time,
|
||||
|
||||
/// - List dependencies
|
||||
ListDependencies {
|
||||
#[arg(short, long)]
|
||||
names: bool,
|
||||
},
|
||||
|
||||
/// - Get database statistics
|
||||
DatabaseStats {
|
||||
property: Option<String>,
|
||||
|
||||
#[arg(short, long, alias("column"))]
|
||||
map: Option<String>,
|
||||
},
|
||||
|
||||
/// - Developer test stubs
|
||||
#[command(subcommand)]
|
||||
#[allow(non_snake_case)]
|
||||
#[clap(hide(true))]
|
||||
Tester(TesterCommand),
|
||||
}
|
||||
|
||||
pub(super) async fn process(command: DebugCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
Ok(match command {
|
||||
DebugCommand::Echo {
|
||||
message,
|
||||
} => echo(body, message).await?,
|
||||
DebugCommand::GetAuthChain {
|
||||
event_id,
|
||||
} => get_auth_chain(body, event_id).await?,
|
||||
DebugCommand::ParsePdu => parse_pdu(body).await?,
|
||||
DebugCommand::GetPdu {
|
||||
event_id,
|
||||
} => get_pdu(body, event_id).await?,
|
||||
DebugCommand::GetRemotePdu {
|
||||
event_id,
|
||||
server,
|
||||
} => get_remote_pdu(body, event_id, server).await?,
|
||||
DebugCommand::GetRoomState {
|
||||
room_id,
|
||||
} => get_room_state(body, room_id).await?,
|
||||
DebugCommand::Ping {
|
||||
server,
|
||||
} => ping(body, server).await?,
|
||||
DebugCommand::ForceDeviceListUpdates => force_device_list_updates(body).await?,
|
||||
DebugCommand::ChangeLogLevel {
|
||||
filter,
|
||||
reset,
|
||||
} => change_log_level(body, filter, reset).await?,
|
||||
DebugCommand::SignJson => sign_json(body).await?,
|
||||
DebugCommand::VerifyJson => verify_json(body).await?,
|
||||
DebugCommand::FirstPduInRoom {
|
||||
room_id,
|
||||
} => first_pdu_in_room(body, room_id).await?,
|
||||
DebugCommand::LatestPduInRoom {
|
||||
room_id,
|
||||
} => latest_pdu_in_room(body, room_id).await?,
|
||||
DebugCommand::GetRemotePduList {
|
||||
server,
|
||||
force,
|
||||
} => get_remote_pdu_list(body, server, force).await?,
|
||||
DebugCommand::ForceSetRoomStateFromServer {
|
||||
room_id,
|
||||
server_name,
|
||||
} => force_set_room_state_from_server(body, server_name, room_id).await?,
|
||||
DebugCommand::ResolveTrueDestination {
|
||||
server_name,
|
||||
no_cache,
|
||||
} => resolve_true_destination(body, server_name, no_cache).await?,
|
||||
DebugCommand::MemoryStats => memory_stats(),
|
||||
DebugCommand::RuntimeMetrics => runtime_metrics(body).await?,
|
||||
DebugCommand::RuntimeInterval => runtime_interval(body).await?,
|
||||
DebugCommand::Tester(command) => tester::process(command, body).await?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,34 +1,45 @@
|
||||
use conduit::Err;
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
|
||||
use crate::Result;
|
||||
use crate::{admin_command, admin_command_dispatch, Result};
|
||||
|
||||
#[derive(clap::Subcommand)]
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[admin_command_dispatch]
|
||||
#[derive(Debug, clap::Subcommand)]
|
||||
pub(crate) enum TesterCommand {
|
||||
Panic,
|
||||
Failure,
|
||||
Tester,
|
||||
Timer,
|
||||
}
|
||||
|
||||
pub(super) async fn process(command: TesterCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
match command {
|
||||
TesterCommand::Tester => tester(body).await,
|
||||
TesterCommand::Timer => timer(body).await,
|
||||
}
|
||||
#[rustfmt::skip]
|
||||
#[admin_command]
|
||||
async fn panic(&self) -> Result<RoomMessageEventContent> {
|
||||
|
||||
panic!("panicked")
|
||||
}
|
||||
|
||||
#[rustfmt::skip]
|
||||
#[admin_command]
|
||||
async fn failure(&self) -> Result<RoomMessageEventContent> {
|
||||
|
||||
Err!("failed")
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
#[rustfmt::skip]
|
||||
#[allow(unused_variables)]
|
||||
async fn tester(body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
async fn tester(&self) -> Result<RoomMessageEventContent> {
|
||||
|
||||
Ok(RoomMessageEventContent::notice_plain("completed"))
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
#[rustfmt::skip]
|
||||
async fn timer(body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
async fn timer(&self) -> Result<RoomMessageEventContent> {
|
||||
let started = std::time::Instant::now();
|
||||
timed(&body);
|
||||
timed(self.body);
|
||||
|
||||
let elapsed = started.elapsed();
|
||||
Ok(RoomMessageEventContent::notice_plain(format!("completed in {elapsed:#?}")))
|
||||
|
||||
@@ -1,21 +1,26 @@
|
||||
use std::fmt::Write;
|
||||
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId, RoomId, ServerName, UserId};
|
||||
|
||||
use crate::{escape_html, get_room_info, services, Result};
|
||||
use crate::{admin_command, escape_html, get_room_info};
|
||||
|
||||
pub(super) async fn disable_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||
services().rooms.metadata.disable_room(&room_id, true)?;
|
||||
#[admin_command]
|
||||
pub(super) async fn disable_room(&self, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||
self.services.rooms.metadata.disable_room(&room_id, true)?;
|
||||
Ok(RoomMessageEventContent::text_plain("Room disabled."))
|
||||
}
|
||||
|
||||
pub(super) async fn enable_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||
services().rooms.metadata.disable_room(&room_id, false)?;
|
||||
#[admin_command]
|
||||
pub(super) async fn enable_room(&self, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||
self.services.rooms.metadata.disable_room(&room_id, false)?;
|
||||
Ok(RoomMessageEventContent::text_plain("Room enabled."))
|
||||
}
|
||||
|
||||
pub(super) async fn incoming_federation(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
let map = services()
|
||||
#[admin_command]
|
||||
pub(super) async fn incoming_federation(&self) -> Result<RoomMessageEventContent> {
|
||||
let map = self
|
||||
.services
|
||||
.rooms
|
||||
.event_handler
|
||||
.federation_handletime
|
||||
@@ -31,11 +36,10 @@ pub(super) async fn incoming_federation(_body: Vec<&str>) -> Result<RoomMessageE
|
||||
Ok(RoomMessageEventContent::text_plain(&msg))
|
||||
}
|
||||
|
||||
pub(super) async fn fetch_support_well_known(
|
||||
_body: Vec<&str>, server_name: Box<ServerName>,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
let response = services()
|
||||
.globals
|
||||
#[admin_command]
|
||||
pub(super) async fn fetch_support_well_known(&self, server_name: Box<ServerName>) -> Result<RoomMessageEventContent> {
|
||||
let response = self
|
||||
.services
|
||||
.client
|
||||
.default
|
||||
.get(format!("https://{server_name}/.well-known/matrix/support"))
|
||||
@@ -73,25 +77,27 @@ pub(super) async fn fetch_support_well_known(
|
||||
)))
|
||||
}
|
||||
|
||||
pub(super) async fn remote_user_in_rooms(_body: Vec<&str>, user_id: Box<UserId>) -> Result<RoomMessageEventContent> {
|
||||
if user_id.server_name() == services().globals.config.server_name {
|
||||
#[admin_command]
|
||||
pub(super) async fn remote_user_in_rooms(&self, user_id: Box<UserId>) -> Result<RoomMessageEventContent> {
|
||||
if user_id.server_name() == self.services.globals.config.server_name {
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"User belongs to our server, please use `list-joined-rooms` user admin command instead.",
|
||||
));
|
||||
}
|
||||
|
||||
if !services().users.exists(&user_id)? {
|
||||
if !self.services.users.exists(&user_id)? {
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Remote user does not exist in our database.",
|
||||
));
|
||||
}
|
||||
|
||||
let mut rooms: Vec<(OwnedRoomId, u64, String)> = services()
|
||||
let mut rooms: Vec<(OwnedRoomId, u64, String)> = self
|
||||
.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.rooms_joined(&user_id)
|
||||
.filter_map(Result::ok)
|
||||
.map(|room_id| get_room_info(&room_id))
|
||||
.map(|room_id| get_room_info(self.services, &room_id))
|
||||
.collect();
|
||||
|
||||
if rooms.is_empty() {
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, RoomId, ServerName, UserId};
|
||||
use ruma::{RoomId, ServerName, UserId};
|
||||
|
||||
use self::commands::*;
|
||||
use crate::admin_command_dispatch;
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
#[admin_command_dispatch]
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(super) enum FederationCommand {
|
||||
/// - List all rooms we are currently handling an incoming pdu from
|
||||
IncomingFederation,
|
||||
@@ -40,21 +40,3 @@ pub(super) enum FederationCommand {
|
||||
user_id: Box<UserId>,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) async fn process(command: FederationCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
Ok(match command {
|
||||
FederationCommand::DisableRoom {
|
||||
room_id,
|
||||
} => disable_room(body, room_id).await?,
|
||||
FederationCommand::EnableRoom {
|
||||
room_id,
|
||||
} => enable_room(body, room_id).await?,
|
||||
FederationCommand::IncomingFederation => incoming_federation(body).await?,
|
||||
FederationCommand::FetchSupportWellKnown {
|
||||
server_name,
|
||||
} => fetch_support_well_known(body, server_name).await?,
|
||||
FederationCommand::RemoteUserInRooms {
|
||||
user_id,
|
||||
} => remote_user_in_rooms(body, user_id).await?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,241 +0,0 @@
|
||||
use std::{panic::AssertUnwindSafe, time::Instant};
|
||||
|
||||
use clap::{CommandFactory, Parser};
|
||||
use conduit::{error, trace, Error};
|
||||
use futures_util::future::FutureExt;
|
||||
use ruma::{
|
||||
events::{
|
||||
relation::InReplyTo,
|
||||
room::message::{Relation::Reply, RoomMessageEventContent},
|
||||
},
|
||||
OwnedEventId,
|
||||
};
|
||||
|
||||
extern crate conduit_service as service;
|
||||
|
||||
use conduit::{utils::string::common_prefix, Result};
|
||||
pub(crate) use service::admin::{Command, Service};
|
||||
use service::admin::{CommandOutput, CommandResult, HandlerResult};
|
||||
|
||||
use crate::{
|
||||
appservice, appservice::AppserviceCommand, check, check::CheckCommand, debug, debug::DebugCommand, federation,
|
||||
federation::FederationCommand, media, media::MediaCommand, query, query::QueryCommand, room, room::RoomCommand,
|
||||
server, server::ServerCommand, services, user, user::UserCommand,
|
||||
};
|
||||
pub(crate) const PAGE_SIZE: usize = 100;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "admin", version = env!("CARGO_PKG_VERSION"))]
|
||||
pub(crate) enum AdminCommand {
|
||||
#[command(subcommand)]
|
||||
/// - Commands for managing appservices
|
||||
Appservices(AppserviceCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for managing local users
|
||||
Users(UserCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for managing rooms
|
||||
Rooms(RoomCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for managing federation
|
||||
Federation(FederationCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for managing the server
|
||||
Server(ServerCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for managing media
|
||||
Media(MediaCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for checking integrity
|
||||
Check(CheckCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Commands for debugging things
|
||||
Debug(DebugCommand),
|
||||
|
||||
#[command(subcommand)]
|
||||
/// - Low-level queries for database getters and iterators
|
||||
Query(QueryCommand),
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub(crate) fn handle(command: Command) -> HandlerResult { Box::pin(handle_command(command)) }
|
||||
|
||||
#[must_use]
|
||||
pub(crate) fn complete(line: &str) -> String { complete_admin_command(AdminCommand::command(), line) }
|
||||
|
||||
#[tracing::instrument(skip_all, name = "admin")]
|
||||
async fn handle_command(command: Command) -> CommandResult {
|
||||
AssertUnwindSafe(process_command(&command))
|
||||
.catch_unwind()
|
||||
.await
|
||||
.map_err(Error::from_panic)
|
||||
.or_else(|error| handle_panic(&error, command))
|
||||
}
|
||||
|
||||
async fn process_command(command: &Command) -> CommandOutput {
|
||||
process_admin_message(&command.command)
|
||||
.await
|
||||
.and_then(|content| reply(content, command.reply_id.clone()))
|
||||
}
|
||||
|
||||
fn handle_panic(error: &Error, command: Command) -> CommandResult {
|
||||
let link = "Please submit a [bug report](https://github.com/girlbossceo/conduwuit/issues/new). 🥺";
|
||||
let msg = format!("Panic occurred while processing command:\n```\n{error:#?}\n```\n{link}");
|
||||
let content = RoomMessageEventContent::notice_markdown(msg);
|
||||
error!("Panic while processing command: {error:?}");
|
||||
Ok(reply(content, command.reply_id))
|
||||
}
|
||||
|
||||
fn reply(mut content: RoomMessageEventContent, reply_id: Option<OwnedEventId>) -> Option<RoomMessageEventContent> {
|
||||
content.relates_to = reply_id.map(|event_id| Reply {
|
||||
in_reply_to: InReplyTo {
|
||||
event_id,
|
||||
},
|
||||
});
|
||||
|
||||
Some(content)
|
||||
}
|
||||
|
||||
// Parse and process a message from the admin room
|
||||
async fn process_admin_message(msg: &str) -> CommandOutput {
|
||||
let mut lines = msg.lines().filter(|l| !l.trim().is_empty());
|
||||
let command = lines.next().expect("each string has at least one line");
|
||||
let body = lines.collect::<Vec<_>>();
|
||||
let parsed = match parse_admin_command(command) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => {
|
||||
let server_name = services().globals.server_name();
|
||||
let message = error.replace("server.name", server_name.as_str());
|
||||
return Some(RoomMessageEventContent::notice_markdown(message));
|
||||
},
|
||||
};
|
||||
|
||||
let timer = Instant::now();
|
||||
let result = process_admin_command(parsed, body).await;
|
||||
let elapsed = timer.elapsed();
|
||||
conduit::debug!(?command, ok = result.is_ok(), "command processed in {elapsed:?}");
|
||||
match result {
|
||||
Ok(reply) => Some(reply),
|
||||
Err(error) => Some(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Encountered an error while handling the command:\n```\n{error:#?}\n```"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, name = "command")]
|
||||
async fn process_admin_command(command: AdminCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
let reply_message_content = match command {
|
||||
AdminCommand::Appservices(command) => appservice::process(command, body).await?,
|
||||
AdminCommand::Media(command) => media::process(command, body).await?,
|
||||
AdminCommand::Users(command) => user::process(command, body).await?,
|
||||
AdminCommand::Rooms(command) => room::process(command, body).await?,
|
||||
AdminCommand::Federation(command) => federation::process(command, body).await?,
|
||||
AdminCommand::Server(command) => server::process(command, body).await?,
|
||||
AdminCommand::Debug(command) => debug::process(command, body).await?,
|
||||
AdminCommand::Query(command) => query::process(command, body).await?,
|
||||
AdminCommand::Check(command) => check::process(command, body).await?,
|
||||
};
|
||||
|
||||
Ok(reply_message_content)
|
||||
}
|
||||
|
||||
// Parse chat messages from the admin room into an AdminCommand object
|
||||
fn parse_admin_command(command_line: &str) -> Result<AdminCommand, String> {
|
||||
let argv = parse_command_line(command_line);
|
||||
AdminCommand::try_parse_from(argv).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn complete_admin_command(mut cmd: clap::Command, line: &str) -> String {
|
||||
let argv = parse_command_line(line);
|
||||
let mut ret = Vec::<String>::with_capacity(argv.len().saturating_add(1));
|
||||
|
||||
'token: for token in argv.into_iter().skip(1) {
|
||||
let cmd_ = cmd.clone();
|
||||
let mut choice = Vec::new();
|
||||
|
||||
for sub in cmd_.get_subcommands() {
|
||||
let name = sub.get_name();
|
||||
if *name == token {
|
||||
// token already complete; recurse to subcommand
|
||||
ret.push(token);
|
||||
cmd.clone_from(sub);
|
||||
continue 'token;
|
||||
} else if name.starts_with(&token) {
|
||||
// partial match; add to choices
|
||||
choice.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
if choice.len() == 1 {
|
||||
// One choice. Add extra space because it's complete
|
||||
let choice = *choice.first().expect("only choice");
|
||||
ret.push(choice.to_owned());
|
||||
ret.push(String::new());
|
||||
} else if choice.is_empty() {
|
||||
// Nothing found, return original string
|
||||
ret.push(token);
|
||||
} else {
|
||||
// Find the common prefix
|
||||
ret.push(common_prefix(&choice).into());
|
||||
}
|
||||
|
||||
// Return from completion
|
||||
return ret.join(" ");
|
||||
}
|
||||
|
||||
// Return from no completion. Needs a space though.
|
||||
ret.push(String::new());
|
||||
ret.join(" ")
|
||||
}
|
||||
|
||||
// Parse chat messages from the admin room into an AdminCommand object
|
||||
fn parse_command_line(command_line: &str) -> Vec<String> {
|
||||
let mut argv = command_line
|
||||
.split_whitespace()
|
||||
.map(str::to_owned)
|
||||
.collect::<Vec<String>>();
|
||||
|
||||
// Remove any escapes that came with a server-side escape command
|
||||
if !argv.is_empty() && argv[0].ends_with("admin") {
|
||||
argv[0] = argv[0].trim_start_matches('\\').into();
|
||||
}
|
||||
|
||||
// First indice has to be "admin" but for console convenience we add it here
|
||||
let server_user = services().globals.server_user.as_str();
|
||||
if !argv.is_empty() && !argv[0].ends_with("admin") && !argv[0].starts_with(server_user) {
|
||||
argv.insert(0, "admin".to_owned());
|
||||
}
|
||||
|
||||
// Replace `help command` with `command --help`
|
||||
// Clap has a help subcommand, but it omits the long help description.
|
||||
if argv.len() > 1 && argv[1] == "help" {
|
||||
argv.remove(1);
|
||||
argv.push("--help".to_owned());
|
||||
}
|
||||
|
||||
// Backwards compatibility with `register_appservice`-style commands
|
||||
if argv.len() > 1 && argv[1].contains('_') {
|
||||
argv[1] = argv[1].replace('_', "-");
|
||||
}
|
||||
|
||||
// Backwards compatibility with `register_appservice`-style commands
|
||||
if argv.len() > 2 && argv[2].contains('_') {
|
||||
argv[2] = argv[2].replace('_', "-");
|
||||
}
|
||||
|
||||
// if the user is using the `query` command (argv[1]), replace the database
|
||||
// function/table calls with underscores to match the codebase
|
||||
if argv.len() > 3 && argv[1].eq("query") {
|
||||
argv[3] = argv[3].replace('_', "-");
|
||||
}
|
||||
|
||||
trace!(?command_line, ?argv, "parse");
|
||||
argv
|
||||
}
|
||||
@@ -1,11 +1,16 @@
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, EventId, MxcUri};
|
||||
use tracing::{debug, info};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::services;
|
||||
use conduit::{debug, info, trace, utils::time::parse_timepoint_ago, warn, Result};
|
||||
use conduit_service::media::Dim;
|
||||
use ruma::{
|
||||
events::room::message::RoomMessageEventContent, EventId, Mxc, MxcUri, OwnedMxcUri, OwnedServerName, ServerName,
|
||||
};
|
||||
|
||||
use crate::{admin_command, utils::parse_local_user_id};
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn delete(
|
||||
_body: Vec<&str>, mxc: Option<Box<MxcUri>>, event_id: Option<Box<EventId>>,
|
||||
&self, mxc: Option<Box<MxcUri>>, event_id: Option<Box<EventId>>,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
if event_id.is_some() && mxc.is_some() {
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
@@ -15,7 +20,10 @@ pub(super) async fn delete(
|
||||
|
||||
if let Some(mxc) = mxc {
|
||||
debug!("Got MXC URL: {mxc}");
|
||||
services().media.delete(mxc.as_ref()).await?;
|
||||
self.services
|
||||
.media
|
||||
.delete(&mxc.as_str().try_into()?)
|
||||
.await?;
|
||||
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Deleted the MXC from our database and on our filesystem.",
|
||||
@@ -27,7 +35,7 @@ pub(super) async fn delete(
|
||||
let mut mxc_deletion_count: usize = 0;
|
||||
|
||||
// parsing the PDU for any MXC URLs begins here
|
||||
if let Some(event_json) = services().rooms.timeline.get_pdu_json(&event_id)? {
|
||||
if let Some(event_json) = self.services.rooms.timeline.get_pdu_json(&event_id)? {
|
||||
if let Some(content_key) = event_json.get("content") {
|
||||
debug!("Event ID has \"content\".");
|
||||
let content_obj = content_key.as_object();
|
||||
@@ -123,7 +131,10 @@ pub(super) async fn delete(
|
||||
}
|
||||
|
||||
for mxc_url in mxc_urls {
|
||||
services().media.delete(&mxc_url).await?;
|
||||
self.services
|
||||
.media
|
||||
.delete(&mxc_url.as_str().try_into()?)
|
||||
.await?;
|
||||
mxc_deletion_count = mxc_deletion_count.saturating_add(1);
|
||||
}
|
||||
|
||||
@@ -138,23 +149,26 @@ pub(super) async fn delete(
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn delete_list(body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
||||
#[admin_command]
|
||||
pub(super) async fn delete_list(&self) -> Result<RoomMessageEventContent> {
|
||||
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||
{
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Expected code block in command body. Add --help for details.",
|
||||
));
|
||||
}
|
||||
|
||||
let mxc_list = body
|
||||
.clone()
|
||||
.drain(1..body.len().checked_sub(1).unwrap())
|
||||
let mxc_list = self
|
||||
.body
|
||||
.to_vec()
|
||||
.drain(1..self.body.len().checked_sub(1).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let mut mxc_deletion_count: usize = 0;
|
||||
|
||||
for mxc in mxc_list {
|
||||
debug!("Deleting MXC {mxc} in bulk");
|
||||
services().media.delete(mxc).await?;
|
||||
self.services.media.delete(&mxc.try_into()?).await?;
|
||||
mxc_deletion_count = mxc_deletion_count
|
||||
.checked_add(1)
|
||||
.expect("mxc_deletion_count should not get this high");
|
||||
@@ -165,10 +179,11 @@ pub(super) async fn delete_list(body: Vec<&str>) -> Result<RoomMessageEventConte
|
||||
)))
|
||||
}
|
||||
|
||||
pub(super) async fn delete_past_remote_media(
|
||||
_body: Vec<&str>, duration: String, force: bool,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
let deleted_count = services()
|
||||
#[admin_command]
|
||||
pub(super) async fn delete_past_remote_media(&self, duration: String, force: bool) -> Result<RoomMessageEventContent> {
|
||||
let duration = parse_timepoint_ago(&duration)?;
|
||||
let deleted_count = self
|
||||
.services
|
||||
.media
|
||||
.delete_all_remote_media_at_after_time(duration, force)
|
||||
.await?;
|
||||
@@ -177,3 +192,123 @@ pub(super) async fn delete_past_remote_media(
|
||||
"Deleted {deleted_count} total files.",
|
||||
)))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn delete_all_from_user(&self, username: String, force: bool) -> Result<RoomMessageEventContent> {
|
||||
let user_id = parse_local_user_id(self.services, &username)?;
|
||||
|
||||
let deleted_count = self
|
||||
.services
|
||||
.media
|
||||
.delete_from_user(&user_id, force)
|
||||
.await?;
|
||||
|
||||
Ok(RoomMessageEventContent::text_plain(format!(
|
||||
"Deleted {deleted_count} total files.",
|
||||
)))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn delete_all_from_server(
|
||||
&self, server_name: Box<ServerName>, force: bool,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
if server_name == self.services.globals.server_name() {
|
||||
return Ok(RoomMessageEventContent::text_plain("This command only works for remote media."));
|
||||
}
|
||||
|
||||
let Ok(all_mxcs) = self.services.media.get_all_mxcs().await else {
|
||||
return Ok(RoomMessageEventContent::text_plain("Failed to get MXC URIs from our database"));
|
||||
};
|
||||
|
||||
let mut deleted_count: usize = 0;
|
||||
|
||||
for mxc in all_mxcs {
|
||||
let mxc_server_name = match mxc.server_name() {
|
||||
Ok(server_name) => server_name,
|
||||
Err(e) => {
|
||||
if force {
|
||||
warn!("Failed to parse MXC {mxc} server name from database, ignoring error and skipping: {e}");
|
||||
continue;
|
||||
}
|
||||
|
||||
return Ok(RoomMessageEventContent::text_plain(format!(
|
||||
"Failed to parse MXC {mxc} server name from database: {e}",
|
||||
)));
|
||||
},
|
||||
};
|
||||
|
||||
if mxc_server_name != server_name || self.services.globals.server_is_ours(mxc_server_name) {
|
||||
trace!("skipping MXC URI {mxc}");
|
||||
continue;
|
||||
}
|
||||
|
||||
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
||||
|
||||
match self.services.media.delete(&mxc).await {
|
||||
Ok(()) => {
|
||||
deleted_count = deleted_count.saturating_add(1);
|
||||
},
|
||||
Err(e) => {
|
||||
if force {
|
||||
warn!("Failed to delete {mxc}, ignoring error and skipping: {e}");
|
||||
continue;
|
||||
}
|
||||
|
||||
return Ok(RoomMessageEventContent::text_plain(format!("Failed to delete MXC {mxc}: {e}")));
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
Ok(RoomMessageEventContent::text_plain(format!(
|
||||
"Deleted {deleted_count} total files.",
|
||||
)))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn get_file_info(&self, mxc: OwnedMxcUri) -> Result<RoomMessageEventContent> {
|
||||
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
||||
let metadata = self.services.media.get_metadata(&mxc);
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!("```\n{metadata:#?}\n```")))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn get_remote_file(
|
||||
&self, mxc: OwnedMxcUri, server: Option<OwnedServerName>, timeout: u32,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
||||
let timeout = Duration::from_millis(timeout.into());
|
||||
let mut result = self
|
||||
.services
|
||||
.media
|
||||
.fetch_remote_content(&mxc, None, server.as_deref(), timeout)
|
||||
.await?;
|
||||
|
||||
// Grab the length of the content before clearing it to not flood the output
|
||||
let len = result.content.as_ref().expect("content").len();
|
||||
result.content.as_mut().expect("content").clear();
|
||||
|
||||
let out = format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```");
|
||||
Ok(RoomMessageEventContent::notice_markdown(out))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn get_remote_thumbnail(
|
||||
&self, mxc: OwnedMxcUri, server: Option<OwnedServerName>, timeout: u32, width: u32, height: u32,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
||||
let timeout = Duration::from_millis(timeout.into());
|
||||
let dim = Dim::new(width, height, None);
|
||||
let mut result = self
|
||||
.services
|
||||
.media
|
||||
.fetch_remote_thumbnail(&mxc, None, server.as_deref(), timeout, &dim)
|
||||
.await?;
|
||||
|
||||
// Grab the length of the content before clearing it to not flood the output
|
||||
let len = result.content.as_ref().expect("content").len();
|
||||
result.content.as_mut().expect("content").clear();
|
||||
|
||||
let out = format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```");
|
||||
Ok(RoomMessageEventContent::notice_markdown(out))
|
||||
}
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, EventId, MxcUri};
|
||||
use ruma::{EventId, MxcUri, OwnedMxcUri, OwnedServerName, ServerName};
|
||||
|
||||
use self::commands::*;
|
||||
use crate::admin_command_dispatch;
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
#[admin_command_dispatch]
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(super) enum MediaCommand {
|
||||
/// - Deletes a single media file from our database and on the filesystem
|
||||
/// via a single MXC URL
|
||||
@@ -32,22 +32,60 @@ pub(super) enum MediaCommand {
|
||||
/// - The duration (at or after), e.g. "5m" to delete all media in the
|
||||
/// past 5 minutes
|
||||
duration: String,
|
||||
|
||||
/// Continues deleting remote media if an undeletable object is found
|
||||
#[arg(short, long)]
|
||||
force: bool,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) async fn process(command: MediaCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
Ok(match command {
|
||||
MediaCommand::Delete {
|
||||
mxc,
|
||||
event_id,
|
||||
} => delete(body, mxc, event_id).await?,
|
||||
MediaCommand::DeleteList => delete_list(body).await?,
|
||||
MediaCommand::DeletePastRemoteMedia {
|
||||
duration,
|
||||
force,
|
||||
} => delete_past_remote_media(body, duration, force).await?,
|
||||
})
|
||||
/// - Deletes all the local media from a local user on our server
|
||||
DeleteAllFromUser {
|
||||
username: String,
|
||||
|
||||
/// Continues deleting media if an undeletable object is found
|
||||
#[arg(short, long)]
|
||||
force: bool,
|
||||
},
|
||||
|
||||
/// - Deletes all remote media from the specified remote server
|
||||
DeleteAllFromServer {
|
||||
server_name: Box<ServerName>,
|
||||
|
||||
/// Continues deleting media if an undeletable object is found
|
||||
#[arg(short, long)]
|
||||
force: bool,
|
||||
},
|
||||
|
||||
GetFileInfo {
|
||||
/// The MXC URL to lookup info for.
|
||||
mxc: OwnedMxcUri,
|
||||
},
|
||||
|
||||
GetRemoteFile {
|
||||
/// The MXC URL to fetch
|
||||
mxc: OwnedMxcUri,
|
||||
|
||||
#[arg(short, long)]
|
||||
server: Option<OwnedServerName>,
|
||||
|
||||
#[arg(short, long, default_value("10000"))]
|
||||
timeout: u32,
|
||||
},
|
||||
|
||||
GetRemoteThumbnail {
|
||||
/// The MXC URL to fetch
|
||||
mxc: OwnedMxcUri,
|
||||
|
||||
#[arg(short, long)]
|
||||
server: Option<OwnedServerName>,
|
||||
|
||||
#[arg(short, long, default_value("10000"))]
|
||||
timeout: u32,
|
||||
|
||||
#[arg(short, long)]
|
||||
width: u32,
|
||||
|
||||
#[arg(short, long)]
|
||||
height: u32,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,54 +1,59 @@
|
||||
#![recursion_limit = "192"]
|
||||
#![allow(clippy::wildcard_imports)]
|
||||
#![allow(clippy::enum_glob_use)]
|
||||
|
||||
pub(crate) mod admin;
|
||||
pub(crate) mod command;
|
||||
pub(crate) mod processor;
|
||||
mod tests;
|
||||
pub(crate) mod utils;
|
||||
|
||||
pub(crate) mod appservice;
|
||||
pub(crate) mod check;
|
||||
pub(crate) mod debug;
|
||||
pub(crate) mod federation;
|
||||
pub(crate) mod handler;
|
||||
pub(crate) mod media;
|
||||
pub(crate) mod query;
|
||||
pub(crate) mod room;
|
||||
pub(crate) mod server;
|
||||
mod tests;
|
||||
pub(crate) mod user;
|
||||
pub(crate) mod utils;
|
||||
|
||||
extern crate conduit_api as api;
|
||||
extern crate conduit_core as conduit;
|
||||
extern crate conduit_service as service;
|
||||
|
||||
pub(crate) use conduit::{mod_ctor, mod_dtor, Result};
|
||||
pub(crate) use service::{services, user_is_local};
|
||||
pub(crate) use conduit::Result;
|
||||
pub(crate) use conduit_macros::{admin_command, admin_command_dispatch};
|
||||
|
||||
pub(crate) use crate::{
|
||||
handler::Service,
|
||||
command::Command,
|
||||
utils::{escape_html, get_room_info},
|
||||
};
|
||||
|
||||
mod_ctor! {}
|
||||
mod_dtor! {}
|
||||
pub(crate) const PAGE_SIZE: usize = 100;
|
||||
|
||||
/// Install the admin command handler
|
||||
pub async fn init() {
|
||||
_ = services()
|
||||
.admin
|
||||
conduit::mod_ctor! {}
|
||||
conduit::mod_dtor! {}
|
||||
conduit::rustc_flags_capture! {}
|
||||
|
||||
/// Install the admin command processor
|
||||
pub async fn init(admin_service: &service::admin::Service) {
|
||||
_ = admin_service
|
||||
.complete
|
||||
.write()
|
||||
.expect("locked for writing")
|
||||
.insert(handler::complete);
|
||||
_ = services()
|
||||
.admin
|
||||
.insert(processor::complete);
|
||||
_ = admin_service
|
||||
.handle
|
||||
.write()
|
||||
.await
|
||||
.insert(handler::handle);
|
||||
.insert(processor::dispatch);
|
||||
}
|
||||
|
||||
/// Uninstall the admin command handler
|
||||
pub async fn fini() {
|
||||
_ = services().admin.handle.write().await.take();
|
||||
_ = services()
|
||||
.admin
|
||||
pub async fn fini(admin_service: &service::admin::Service) {
|
||||
_ = admin_service.handle.write().await.take();
|
||||
_ = admin_service
|
||||
.complete
|
||||
.write()
|
||||
.expect("locked for writing")
|
||||
|
||||
261
src/admin/processor.rs
Normal file
261
src/admin/processor.rs
Normal file
@@ -0,0 +1,261 @@
|
||||
use std::{
|
||||
fmt::Write,
|
||||
panic::AssertUnwindSafe,
|
||||
sync::{Arc, Mutex},
|
||||
time::SystemTime,
|
||||
};
|
||||
|
||||
use clap::{CommandFactory, Parser};
|
||||
use conduit::{
|
||||
debug, error,
|
||||
log::{
|
||||
capture,
|
||||
capture::Capture,
|
||||
fmt::{markdown_table, markdown_table_head},
|
||||
},
|
||||
trace,
|
||||
utils::string::{collect_stream, common_prefix},
|
||||
Error, Result,
|
||||
};
|
||||
use futures_util::future::FutureExt;
|
||||
use ruma::{
|
||||
events::{
|
||||
relation::InReplyTo,
|
||||
room::message::{Relation::Reply, RoomMessageEventContent},
|
||||
},
|
||||
EventId,
|
||||
};
|
||||
use service::{
|
||||
admin::{CommandInput, CommandOutput, ProcessorFuture, ProcessorResult},
|
||||
Services,
|
||||
};
|
||||
use tracing::Level;
|
||||
use tracing_subscriber::{filter::LevelFilter, EnvFilter};
|
||||
|
||||
use crate::{admin, admin::AdminCommand, Command};
|
||||
|
||||
#[must_use]
|
||||
pub(super) fn complete(line: &str) -> String { complete_command(AdminCommand::command(), line) }
|
||||
|
||||
#[must_use]
|
||||
pub(super) fn dispatch(services: Arc<Services>, command: CommandInput) -> ProcessorFuture {
|
||||
Box::pin(handle_command(services, command))
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, name = "admin")]
|
||||
async fn handle_command(services: Arc<Services>, command: CommandInput) -> ProcessorResult {
|
||||
AssertUnwindSafe(Box::pin(process_command(services, &command)))
|
||||
.catch_unwind()
|
||||
.await
|
||||
.map_err(Error::from_panic)
|
||||
.unwrap_or_else(|error| handle_panic(&error, &command))
|
||||
}
|
||||
|
||||
async fn process_command(services: Arc<Services>, input: &CommandInput) -> ProcessorResult {
|
||||
let (command, args, body) = match parse(&services, input) {
|
||||
Err(error) => return Err(error),
|
||||
Ok(parsed) => parsed,
|
||||
};
|
||||
|
||||
let context = Command {
|
||||
services: &services,
|
||||
body: &body,
|
||||
timer: SystemTime::now(),
|
||||
reply_id: input.reply_id.as_deref(),
|
||||
};
|
||||
|
||||
process(&context, command, &args).await
|
||||
}
|
||||
|
||||
fn handle_panic(error: &Error, command: &CommandInput) -> ProcessorResult {
|
||||
let link = "Please submit a [bug report](https://github.com/girlbossceo/conduwuit/issues/new). 🥺";
|
||||
let msg = format!("Panic occurred while processing command:\n```\n{error:#?}\n```\n{link}");
|
||||
let content = RoomMessageEventContent::notice_markdown(msg);
|
||||
error!("Panic while processing command: {error:?}");
|
||||
Err(reply(content, command.reply_id.as_deref()))
|
||||
}
|
||||
|
||||
// Parse and process a message from the admin room
|
||||
async fn process(context: &Command<'_>, command: AdminCommand, args: &[String]) -> ProcessorResult {
|
||||
let (capture, logs) = capture_create(context);
|
||||
|
||||
let capture_scope = capture.start();
|
||||
let result = Box::pin(admin::process(command, context)).await;
|
||||
drop(capture_scope);
|
||||
|
||||
debug!(
|
||||
ok = result.is_ok(),
|
||||
elapsed = ?context.timer.elapsed(),
|
||||
command = ?args,
|
||||
"command processed"
|
||||
);
|
||||
|
||||
let mut output = String::new();
|
||||
|
||||
// Prepend the logs only if any were captured
|
||||
let logs = logs.lock().expect("locked");
|
||||
if logs.lines().count() > 2 {
|
||||
writeln!(&mut output, "{logs}").expect("failed to format logs to command output");
|
||||
}
|
||||
drop(logs);
|
||||
|
||||
match result {
|
||||
Ok(content) => {
|
||||
write!(&mut output, "{0}", content.body()).expect("failed to format command result to output buffer");
|
||||
Ok(Some(reply(RoomMessageEventContent::notice_markdown(output), context.reply_id)))
|
||||
},
|
||||
Err(error) => {
|
||||
write!(&mut output, "Command failed with error:\n```\n{error:#?}\n```")
|
||||
.expect("failed to format command result to output");
|
||||
Err(reply(RoomMessageEventContent::notice_markdown(output), context.reply_id))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn capture_create(context: &Command<'_>) -> (Arc<Capture>, Arc<Mutex<String>>) {
|
||||
let env_config = &context.services.server.config.admin_log_capture;
|
||||
let env_filter = EnvFilter::try_new(env_config).unwrap_or_else(|_| "debug".into());
|
||||
let log_level = env_filter
|
||||
.max_level_hint()
|
||||
.and_then(LevelFilter::into_level)
|
||||
.unwrap_or(Level::DEBUG);
|
||||
|
||||
let filter =
|
||||
move |data: capture::Data<'_>| data.level() <= log_level && data.our_modules() && data.scope.contains(&"admin");
|
||||
|
||||
let logs = Arc::new(Mutex::new(
|
||||
collect_stream(|s| markdown_table_head(s)).expect("markdown table header"),
|
||||
));
|
||||
|
||||
let capture = Capture::new(
|
||||
&context.services.server.log.capture,
|
||||
Some(filter),
|
||||
capture::fmt(markdown_table, logs.clone()),
|
||||
);
|
||||
|
||||
(capture, logs)
|
||||
}
|
||||
|
||||
// Parse chat messages from the admin room into an AdminCommand object
|
||||
fn parse<'a>(
|
||||
services: &Arc<Services>, input: &'a CommandInput,
|
||||
) -> Result<(AdminCommand, Vec<String>, Vec<&'a str>), CommandOutput> {
|
||||
let lines = input.command.lines().filter(|line| !line.trim().is_empty());
|
||||
let command_line = lines.clone().next().expect("command missing first line");
|
||||
let body = lines.skip(1).collect();
|
||||
match parse_command(command_line) {
|
||||
Ok((command, args)) => Ok((command, args, body)),
|
||||
Err(error) => {
|
||||
let message = error
|
||||
.to_string()
|
||||
.replace("server.name", services.globals.server_name().as_str());
|
||||
Err(reply(
|
||||
RoomMessageEventContent::notice_markdown(message),
|
||||
input.reply_id.as_deref(),
|
||||
))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_command(line: &str) -> Result<(AdminCommand, Vec<String>)> {
|
||||
let argv = parse_line(line);
|
||||
let command = AdminCommand::try_parse_from(&argv)?;
|
||||
Ok((command, argv))
|
||||
}
|
||||
|
||||
fn complete_command(mut cmd: clap::Command, line: &str) -> String {
|
||||
let argv = parse_line(line);
|
||||
let mut ret = Vec::<String>::with_capacity(argv.len().saturating_add(1));
|
||||
|
||||
'token: for token in argv.into_iter().skip(1) {
|
||||
let cmd_ = cmd.clone();
|
||||
let mut choice = Vec::new();
|
||||
|
||||
for sub in cmd_.get_subcommands() {
|
||||
let name = sub.get_name();
|
||||
if *name == token {
|
||||
// token already complete; recurse to subcommand
|
||||
ret.push(token);
|
||||
cmd.clone_from(sub);
|
||||
continue 'token;
|
||||
} else if name.starts_with(&token) {
|
||||
// partial match; add to choices
|
||||
choice.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
if choice.len() == 1 {
|
||||
// One choice. Add extra space because it's complete
|
||||
let choice = *choice.first().expect("only choice");
|
||||
ret.push(choice.to_owned());
|
||||
ret.push(String::new());
|
||||
} else if choice.is_empty() {
|
||||
// Nothing found, return original string
|
||||
ret.push(token);
|
||||
} else {
|
||||
// Find the common prefix
|
||||
ret.push(common_prefix(&choice).into());
|
||||
}
|
||||
|
||||
// Return from completion
|
||||
return ret.join(" ");
|
||||
}
|
||||
|
||||
// Return from no completion. Needs a space though.
|
||||
ret.push(String::new());
|
||||
ret.join(" ")
|
||||
}
|
||||
|
||||
// Parse chat messages from the admin room into an AdminCommand object
|
||||
fn parse_line(command_line: &str) -> Vec<String> {
|
||||
let mut argv = command_line
|
||||
.split_whitespace()
|
||||
.map(str::to_owned)
|
||||
.collect::<Vec<String>>();
|
||||
|
||||
// Remove any escapes that came with a server-side escape command
|
||||
if !argv.is_empty() && argv[0].ends_with("admin") {
|
||||
argv[0] = argv[0].trim_start_matches('\\').into();
|
||||
}
|
||||
|
||||
// First indice has to be "admin" but for console convenience we add it here
|
||||
if !argv.is_empty() && !argv[0].ends_with("admin") && !argv[0].starts_with('@') {
|
||||
argv.insert(0, "admin".to_owned());
|
||||
}
|
||||
|
||||
// Replace `help command` with `command --help`
|
||||
// Clap has a help subcommand, but it omits the long help description.
|
||||
if argv.len() > 1 && argv[1] == "help" {
|
||||
argv.remove(1);
|
||||
argv.push("--help".to_owned());
|
||||
}
|
||||
|
||||
// Backwards compatibility with `register_appservice`-style commands
|
||||
if argv.len() > 1 && argv[1].contains('_') {
|
||||
argv[1] = argv[1].replace('_', "-");
|
||||
}
|
||||
|
||||
// Backwards compatibility with `register_appservice`-style commands
|
||||
if argv.len() > 2 && argv[2].contains('_') {
|
||||
argv[2] = argv[2].replace('_', "-");
|
||||
}
|
||||
|
||||
// if the user is using the `query` command (argv[1]), replace the database
|
||||
// function/table calls with underscores to match the codebase
|
||||
if argv.len() > 3 && argv[1].eq("query") {
|
||||
argv[3] = argv[3].replace('_', "-");
|
||||
}
|
||||
|
||||
trace!(?command_line, ?argv, "parse");
|
||||
argv
|
||||
}
|
||||
|
||||
fn reply(mut content: RoomMessageEventContent, reply_id: Option<&EventId>) -> RoomMessageEventContent {
|
||||
content.relates_to = reply_id.map(|event_id| Reply {
|
||||
in_reply_to: InReplyTo {
|
||||
event_id: event_id.to_owned(),
|
||||
},
|
||||
});
|
||||
|
||||
content
|
||||
}
|
||||
@@ -1,18 +1,48 @@
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{
|
||||
events::{room::message::RoomMessageEventContent, RoomAccountDataEventType},
|
||||
RoomId, UserId,
|
||||
};
|
||||
|
||||
use super::AccountData;
|
||||
use crate::{services, Result};
|
||||
use crate::Command;
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/account_data.rs
|
||||
pub(crate) enum AccountDataCommand {
|
||||
/// - Returns all changes to the account data that happened after `since`.
|
||||
ChangesSince {
|
||||
/// Full user ID
|
||||
user_id: Box<UserId>,
|
||||
/// UNIX timestamp since (u64)
|
||||
since: u64,
|
||||
/// Optional room ID of the account data
|
||||
room_id: Option<Box<RoomId>>,
|
||||
},
|
||||
|
||||
/// - Searches the account data for a specific kind.
|
||||
Get {
|
||||
/// Full user ID
|
||||
user_id: Box<UserId>,
|
||||
/// Account data event type
|
||||
kind: RoomAccountDataEventType,
|
||||
/// Optional room ID of the account data
|
||||
room_id: Option<Box<RoomId>>,
|
||||
},
|
||||
}
|
||||
|
||||
/// All the getters and iterators from src/database/key_value/account_data.rs
|
||||
pub(super) async fn account_data(subcommand: AccountData) -> Result<RoomMessageEventContent> {
|
||||
pub(super) async fn process(subcommand: AccountDataCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||
let services = context.services;
|
||||
|
||||
match subcommand {
|
||||
AccountData::ChangesSince {
|
||||
AccountDataCommand::ChangesSince {
|
||||
user_id,
|
||||
since,
|
||||
room_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services()
|
||||
let results = services
|
||||
.account_data
|
||||
.changes_since(room_id.as_deref(), &user_id, since)?;
|
||||
let query_time = timer.elapsed();
|
||||
@@ -21,13 +51,13 @@ pub(super) async fn account_data(subcommand: AccountData) -> Result<RoomMessageE
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
AccountData::Get {
|
||||
AccountDataCommand::Get {
|
||||
user_id,
|
||||
kind,
|
||||
room_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services()
|
||||
let results = services
|
||||
.account_data
|
||||
.get(room_id.as_deref(), &user_id, kind)?;
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
@@ -1,16 +1,32 @@
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
|
||||
use super::Appservice;
|
||||
use crate::{services, Result};
|
||||
use crate::Command;
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/appservice.rs
|
||||
pub(crate) enum AppserviceCommand {
|
||||
/// - Gets the appservice registration info/details from the ID as a string
|
||||
GetRegistration {
|
||||
/// Appservice registration ID
|
||||
appservice_id: Box<str>,
|
||||
},
|
||||
|
||||
/// - Gets all appservice registrations with their ID and registration info
|
||||
All,
|
||||
}
|
||||
|
||||
/// All the getters and iterators from src/database/key_value/appservice.rs
|
||||
pub(super) async fn appservice(subcommand: Appservice) -> Result<RoomMessageEventContent> {
|
||||
pub(super) async fn process(subcommand: AppserviceCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||
let services = context.services;
|
||||
|
||||
match subcommand {
|
||||
Appservice::GetRegistration {
|
||||
AppserviceCommand::GetRegistration {
|
||||
appservice_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services()
|
||||
let results = services
|
||||
.appservice
|
||||
.db
|
||||
.get_registration(appservice_id.as_ref());
|
||||
@@ -20,9 +36,9 @@ pub(super) async fn appservice(subcommand: Appservice) -> Result<RoomMessageEven
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
Appservice::All => {
|
||||
AppserviceCommand::All => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().appservice.all();
|
||||
let results = services.appservice.all();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
|
||||
@@ -1,52 +1,73 @@
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, ServerName};
|
||||
|
||||
use super::Globals;
|
||||
use crate::{services, Result};
|
||||
use crate::Command;
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/globals.rs
|
||||
pub(crate) enum GlobalsCommand {
|
||||
DatabaseVersion,
|
||||
|
||||
CurrentCount,
|
||||
|
||||
LastCheckForUpdatesId,
|
||||
|
||||
LoadKeypair,
|
||||
|
||||
/// - This returns an empty `Ok(BTreeMap<..>)` when there are no keys found
|
||||
/// for the server.
|
||||
SigningKeysFor {
|
||||
origin: Box<ServerName>,
|
||||
},
|
||||
}
|
||||
|
||||
/// All the getters and iterators from src/database/key_value/globals.rs
|
||||
pub(super) async fn globals(subcommand: Globals) -> Result<RoomMessageEventContent> {
|
||||
pub(super) async fn process(subcommand: GlobalsCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||
let services = context.services;
|
||||
|
||||
match subcommand {
|
||||
Globals::DatabaseVersion => {
|
||||
GlobalsCommand::DatabaseVersion => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().globals.db.database_version();
|
||||
let results = services.globals.db.database_version();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
Globals::CurrentCount => {
|
||||
GlobalsCommand::CurrentCount => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().globals.db.current_count();
|
||||
let results = services.globals.db.current_count();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
Globals::LastCheckForUpdatesId => {
|
||||
GlobalsCommand::LastCheckForUpdatesId => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().updates.last_check_for_updates_id();
|
||||
let results = services.updates.last_check_for_updates_id();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
Globals::LoadKeypair => {
|
||||
GlobalsCommand::LoadKeypair => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().globals.db.load_keypair();
|
||||
let results = services.globals.db.load_keypair();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
Globals::SigningKeysFor {
|
||||
GlobalsCommand::SigningKeysFor {
|
||||
origin,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().globals.db.signing_keys_for(&origin);
|
||||
let results = services.globals.db.verify_keys_for(&origin);
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
|
||||
@@ -10,314 +10,51 @@
|
||||
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use room_state_cache::room_state_cache;
|
||||
use ruma::{
|
||||
events::{room::message::RoomMessageEventContent, RoomAccountDataEventType},
|
||||
OwnedServerName, RoomAliasId, RoomId, ServerName, UserId,
|
||||
};
|
||||
|
||||
use self::{
|
||||
account_data::account_data, appservice::appservice, globals::globals, presence::presence, resolver::resolver,
|
||||
room_alias::room_alias, sending::sending, users::users,
|
||||
account_data::AccountDataCommand, appservice::AppserviceCommand, globals::GlobalsCommand,
|
||||
presence::PresenceCommand, resolver::ResolverCommand, room_alias::RoomAliasCommand,
|
||||
room_state_cache::RoomStateCacheCommand, sending::SendingCommand, users::UsersCommand,
|
||||
};
|
||||
use crate::admin_command_dispatch;
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
#[admin_command_dispatch]
|
||||
#[derive(Debug, Subcommand)]
|
||||
/// Query tables from database
|
||||
pub(super) enum QueryCommand {
|
||||
/// - account_data.rs iterators and getters
|
||||
#[command(subcommand)]
|
||||
AccountData(AccountData),
|
||||
AccountData(AccountDataCommand),
|
||||
|
||||
/// - appservice.rs iterators and getters
|
||||
#[command(subcommand)]
|
||||
Appservice(Appservice),
|
||||
Appservice(AppserviceCommand),
|
||||
|
||||
/// - presence.rs iterators and getters
|
||||
#[command(subcommand)]
|
||||
Presence(Presence),
|
||||
Presence(PresenceCommand),
|
||||
|
||||
/// - rooms/alias.rs iterators and getters
|
||||
#[command(subcommand)]
|
||||
RoomAlias(RoomAlias),
|
||||
RoomAlias(RoomAliasCommand),
|
||||
|
||||
/// - rooms/state_cache iterators and getters
|
||||
#[command(subcommand)]
|
||||
RoomStateCache(RoomStateCache),
|
||||
RoomStateCache(RoomStateCacheCommand),
|
||||
|
||||
/// - globals.rs iterators and getters
|
||||
#[command(subcommand)]
|
||||
Globals(Globals),
|
||||
Globals(GlobalsCommand),
|
||||
|
||||
/// - sending.rs iterators and getters
|
||||
#[command(subcommand)]
|
||||
Sending(Sending),
|
||||
Sending(SendingCommand),
|
||||
|
||||
/// - users.rs iterators and getters
|
||||
#[command(subcommand)]
|
||||
Users(Users),
|
||||
Users(UsersCommand),
|
||||
|
||||
/// - resolver service
|
||||
#[command(subcommand)]
|
||||
Resolver(Resolver),
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/account_data.rs
|
||||
pub(super) enum AccountData {
|
||||
/// - Returns all changes to the account data that happened after `since`.
|
||||
ChangesSince {
|
||||
/// Full user ID
|
||||
user_id: Box<UserId>,
|
||||
/// UNIX timestamp since (u64)
|
||||
since: u64,
|
||||
/// Optional room ID of the account data
|
||||
room_id: Option<Box<RoomId>>,
|
||||
},
|
||||
|
||||
/// - Searches the account data for a specific kind.
|
||||
Get {
|
||||
/// Full user ID
|
||||
user_id: Box<UserId>,
|
||||
/// Account data event type
|
||||
kind: RoomAccountDataEventType,
|
||||
/// Optional room ID of the account data
|
||||
room_id: Option<Box<RoomId>>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/appservice.rs
|
||||
pub(super) enum Appservice {
|
||||
/// - Gets the appservice registration info/details from the ID as a string
|
||||
GetRegistration {
|
||||
/// Appservice registration ID
|
||||
appservice_id: Box<str>,
|
||||
},
|
||||
|
||||
/// - Gets all appservice registrations with their ID and registration info
|
||||
All,
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/presence.rs
|
||||
pub(super) enum Presence {
|
||||
/// - Returns the latest presence event for the given user.
|
||||
GetPresence {
|
||||
/// Full user ID
|
||||
user_id: Box<UserId>,
|
||||
},
|
||||
|
||||
/// - Iterator of the most recent presence updates that happened after the
|
||||
/// event with id `since`.
|
||||
PresenceSince {
|
||||
/// UNIX timestamp since (u64)
|
||||
since: u64,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/rooms/alias.rs
|
||||
pub(super) enum RoomAlias {
|
||||
ResolveLocalAlias {
|
||||
/// Full room alias
|
||||
alias: Box<RoomAliasId>,
|
||||
},
|
||||
|
||||
/// - Iterator of all our local room aliases for the room ID
|
||||
LocalAliasesForRoom {
|
||||
/// Full room ID
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
/// - Iterator of all our local aliases in our database with their room IDs
|
||||
AllLocalAliases,
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
pub(super) enum RoomStateCache {
|
||||
ServerInRoom {
|
||||
server: Box<ServerName>,
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
RoomServers {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
ServerRooms {
|
||||
server: Box<ServerName>,
|
||||
},
|
||||
|
||||
RoomMembers {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
LocalUsersInRoom {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
ActiveLocalUsersInRoom {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
RoomJoinedCount {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
RoomInvitedCount {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
RoomUserOnceJoined {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
RoomMembersInvited {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
GetInviteCount {
|
||||
room_id: Box<RoomId>,
|
||||
user_id: Box<UserId>,
|
||||
},
|
||||
|
||||
GetLeftCount {
|
||||
room_id: Box<RoomId>,
|
||||
user_id: Box<UserId>,
|
||||
},
|
||||
|
||||
RoomsJoined {
|
||||
user_id: Box<UserId>,
|
||||
},
|
||||
|
||||
RoomsLeft {
|
||||
user_id: Box<UserId>,
|
||||
},
|
||||
|
||||
RoomsInvited {
|
||||
user_id: Box<UserId>,
|
||||
},
|
||||
|
||||
InviteState {
|
||||
user_id: Box<UserId>,
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/globals.rs
|
||||
pub(super) enum Globals {
|
||||
DatabaseVersion,
|
||||
|
||||
CurrentCount,
|
||||
|
||||
LastCheckForUpdatesId,
|
||||
|
||||
LoadKeypair,
|
||||
|
||||
/// - This returns an empty `Ok(BTreeMap<..>)` when there are no keys found
|
||||
/// for the server.
|
||||
SigningKeysFor {
|
||||
origin: Box<ServerName>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/sending.rs
|
||||
pub(super) enum Sending {
|
||||
/// - Queries database for all `servercurrentevent_data`
|
||||
ActiveRequests,
|
||||
|
||||
/// - Queries database for `servercurrentevent_data` but for a specific
|
||||
/// destination
|
||||
///
|
||||
/// This command takes only *one* format of these arguments:
|
||||
///
|
||||
/// appservice_id
|
||||
/// server_name
|
||||
/// user_id AND push_key
|
||||
///
|
||||
/// See src/service/sending/mod.rs for the definition of the `Destination`
|
||||
/// enum
|
||||
ActiveRequestsFor {
|
||||
#[arg(short, long)]
|
||||
appservice_id: Option<String>,
|
||||
#[arg(short, long)]
|
||||
server_name: Option<Box<ServerName>>,
|
||||
#[arg(short, long)]
|
||||
user_id: Option<Box<UserId>>,
|
||||
#[arg(short, long)]
|
||||
push_key: Option<String>,
|
||||
},
|
||||
|
||||
/// - Queries database for `servernameevent_data` which are the queued up
|
||||
/// requests that will eventually be sent
|
||||
///
|
||||
/// This command takes only *one* format of these arguments:
|
||||
///
|
||||
/// appservice_id
|
||||
/// server_name
|
||||
/// user_id AND push_key
|
||||
///
|
||||
/// See src/service/sending/mod.rs for the definition of the `Destination`
|
||||
/// enum
|
||||
QueuedRequests {
|
||||
#[arg(short, long)]
|
||||
appservice_id: Option<String>,
|
||||
#[arg(short, long)]
|
||||
server_name: Option<Box<ServerName>>,
|
||||
#[arg(short, long)]
|
||||
user_id: Option<Box<UserId>>,
|
||||
#[arg(short, long)]
|
||||
push_key: Option<String>,
|
||||
},
|
||||
|
||||
GetLatestEduCount {
|
||||
server_name: Box<ServerName>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/users.rs
|
||||
pub(super) enum Users {
|
||||
Iter,
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
/// Resolver service and caches
|
||||
pub(super) enum Resolver {
|
||||
/// Query the destinations cache
|
||||
DestinationsCache {
|
||||
server_name: Option<OwnedServerName>,
|
||||
},
|
||||
|
||||
/// Query the overrides cache
|
||||
OverridesCache {
|
||||
name: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Processes admin query commands
|
||||
pub(super) async fn process(command: QueryCommand, _body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
Ok(match command {
|
||||
QueryCommand::AccountData(command) => account_data(command).await?,
|
||||
QueryCommand::Appservice(command) => appservice(command).await?,
|
||||
QueryCommand::Presence(command) => presence(command).await?,
|
||||
QueryCommand::RoomAlias(command) => room_alias(command).await?,
|
||||
QueryCommand::RoomStateCache(command) => room_state_cache(command).await?,
|
||||
QueryCommand::Globals(command) => globals(command).await?,
|
||||
QueryCommand::Sending(command) => sending(command).await?,
|
||||
QueryCommand::Users(command) => users(command).await?,
|
||||
QueryCommand::Resolver(command) => resolver(command).await?,
|
||||
})
|
||||
Resolver(ResolverCommand),
|
||||
}
|
||||
|
||||
@@ -1,27 +1,47 @@
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, UserId};
|
||||
|
||||
use super::Presence;
|
||||
use crate::{services, Result};
|
||||
use crate::Command;
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/presence.rs
|
||||
pub(crate) enum PresenceCommand {
|
||||
/// - Returns the latest presence event for the given user.
|
||||
GetPresence {
|
||||
/// Full user ID
|
||||
user_id: Box<UserId>,
|
||||
},
|
||||
|
||||
/// - Iterator of the most recent presence updates that happened after the
|
||||
/// event with id `since`.
|
||||
PresenceSince {
|
||||
/// UNIX timestamp since (u64)
|
||||
since: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// All the getters and iterators in key_value/presence.rs
|
||||
pub(super) async fn presence(subcommand: Presence) -> Result<RoomMessageEventContent> {
|
||||
pub(super) async fn process(subcommand: PresenceCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||
let services = context.services;
|
||||
|
||||
match subcommand {
|
||||
Presence::GetPresence {
|
||||
PresenceCommand::GetPresence {
|
||||
user_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().presence.db.get_presence(&user_id)?;
|
||||
let results = services.presence.db.get_presence(&user_id)?;
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
Presence::PresenceSince {
|
||||
PresenceCommand::PresenceSince {
|
||||
since,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().presence.db.presence_since(since);
|
||||
let results = services.presence.db.presence_since(since);
|
||||
let presence_since: Vec<(_, _, _)> = results.collect();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
|
||||
@@ -1,25 +1,29 @@
|
||||
use std::fmt::Write;
|
||||
|
||||
use clap::Subcommand;
|
||||
use conduit::{utils::time, Result};
|
||||
use ruma::{events::room::message::RoomMessageEventContent, OwnedServerName};
|
||||
|
||||
use super::Resolver;
|
||||
use crate::services;
|
||||
use crate::{admin_command, admin_command_dispatch};
|
||||
|
||||
/// All the getters and iterators in key_value/users.rs
|
||||
pub(super) async fn resolver(subcommand: Resolver) -> Result<RoomMessageEventContent> {
|
||||
match subcommand {
|
||||
Resolver::DestinationsCache {
|
||||
server_name,
|
||||
} => destinations_cache(server_name).await,
|
||||
Resolver::OverridesCache {
|
||||
name,
|
||||
} => overrides_cache(name).await,
|
||||
}
|
||||
#[admin_command_dispatch]
|
||||
#[derive(Debug, Subcommand)]
|
||||
/// Resolver service and caches
|
||||
pub(crate) enum ResolverCommand {
|
||||
/// Query the destinations cache
|
||||
DestinationsCache {
|
||||
server_name: Option<OwnedServerName>,
|
||||
},
|
||||
|
||||
/// Query the overrides cache
|
||||
OverridesCache {
|
||||
name: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
async fn destinations_cache(server_name: Option<OwnedServerName>) -> Result<RoomMessageEventContent> {
|
||||
use service::sending::CachedDest;
|
||||
#[admin_command]
|
||||
async fn destinations_cache(&self, server_name: Option<OwnedServerName>) -> Result<RoomMessageEventContent> {
|
||||
use service::resolver::cache::CachedDest;
|
||||
|
||||
let mut out = String::new();
|
||||
writeln!(out, "| Server Name | Destination | Hostname | Expires |")?;
|
||||
@@ -36,9 +40,10 @@ async fn destinations_cache(server_name: Option<OwnedServerName>) -> Result<Room
|
||||
writeln!(out, "| {name} | {dest} | {host} | {expire} |").expect("wrote line");
|
||||
};
|
||||
|
||||
let map = services()
|
||||
.globals
|
||||
let map = self
|
||||
.services
|
||||
.resolver
|
||||
.cache
|
||||
.destinations
|
||||
.read()
|
||||
.expect("locked");
|
||||
@@ -52,8 +57,9 @@ async fn destinations_cache(server_name: Option<OwnedServerName>) -> Result<Room
|
||||
Ok(RoomMessageEventContent::notice_markdown(out))
|
||||
}
|
||||
|
||||
async fn overrides_cache(server_name: Option<String>) -> Result<RoomMessageEventContent> {
|
||||
use service::sending::CachedOverride;
|
||||
#[admin_command]
|
||||
async fn overrides_cache(&self, server_name: Option<String>) -> Result<RoomMessageEventContent> {
|
||||
use service::resolver::cache::CachedOverride;
|
||||
|
||||
let mut out = String::new();
|
||||
writeln!(out, "| Server Name | IP | Port | Expires |")?;
|
||||
@@ -70,9 +76,10 @@ async fn overrides_cache(server_name: Option<String>) -> Result<RoomMessageEvent
|
||||
writeln!(out, "| {name} | {ips:?} | {port} | {expire} |").expect("wrote line");
|
||||
};
|
||||
|
||||
let map = services()
|
||||
.globals
|
||||
let map = self
|
||||
.services
|
||||
.resolver
|
||||
.cache
|
||||
.overrides
|
||||
.read()
|
||||
.expect("locked");
|
||||
|
||||
@@ -1,27 +1,48 @@
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, RoomAliasId, RoomId};
|
||||
|
||||
use super::RoomAlias;
|
||||
use crate::{services, Result};
|
||||
use crate::Command;
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/rooms/alias.rs
|
||||
pub(crate) enum RoomAliasCommand {
|
||||
ResolveLocalAlias {
|
||||
/// Full room alias
|
||||
alias: Box<RoomAliasId>,
|
||||
},
|
||||
|
||||
/// - Iterator of all our local room aliases for the room ID
|
||||
LocalAliasesForRoom {
|
||||
/// Full room ID
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
/// - Iterator of all our local aliases in our database with their room IDs
|
||||
AllLocalAliases,
|
||||
}
|
||||
|
||||
/// All the getters and iterators in src/database/key_value/rooms/alias.rs
|
||||
pub(super) async fn room_alias(subcommand: RoomAlias) -> Result<RoomMessageEventContent> {
|
||||
pub(super) async fn process(subcommand: RoomAliasCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||
let services = context.services;
|
||||
|
||||
match subcommand {
|
||||
RoomAlias::ResolveLocalAlias {
|
||||
RoomAliasCommand::ResolveLocalAlias {
|
||||
alias,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().rooms.alias.resolve_local_alias(&alias);
|
||||
let results = services.rooms.alias.resolve_local_alias(&alias);
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomAlias::LocalAliasesForRoom {
|
||||
RoomAliasCommand::LocalAliasesForRoom {
|
||||
room_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().rooms.alias.local_aliases_for_room(&room_id);
|
||||
let results = services.rooms.alias.local_aliases_for_room(&room_id);
|
||||
let aliases: Vec<_> = results.collect();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
@@ -29,9 +50,9 @@ pub(super) async fn room_alias(subcommand: RoomAlias) -> Result<RoomMessageEvent
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{aliases:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomAlias::AllLocalAliases => {
|
||||
RoomAliasCommand::AllLocalAliases => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().rooms.alias.all_local_aliases();
|
||||
let results = services.rooms.alias.all_local_aliases();
|
||||
let aliases: Vec<_> = results.collect();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
|
||||
@@ -1,71 +1,136 @@
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, RoomId, ServerName, UserId};
|
||||
|
||||
use super::RoomStateCache;
|
||||
use crate::{services, Result};
|
||||
use crate::Command;
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(crate) enum RoomStateCacheCommand {
|
||||
ServerInRoom {
|
||||
server: Box<ServerName>,
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
RoomServers {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
ServerRooms {
|
||||
server: Box<ServerName>,
|
||||
},
|
||||
|
||||
RoomMembers {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
LocalUsersInRoom {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
ActiveLocalUsersInRoom {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
RoomJoinedCount {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
RoomInvitedCount {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
RoomUserOnceJoined {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
RoomMembersInvited {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
GetInviteCount {
|
||||
room_id: Box<RoomId>,
|
||||
user_id: Box<UserId>,
|
||||
},
|
||||
|
||||
GetLeftCount {
|
||||
room_id: Box<RoomId>,
|
||||
user_id: Box<UserId>,
|
||||
},
|
||||
|
||||
RoomsJoined {
|
||||
user_id: Box<UserId>,
|
||||
},
|
||||
|
||||
RoomsLeft {
|
||||
user_id: Box<UserId>,
|
||||
},
|
||||
|
||||
RoomsInvited {
|
||||
user_id: Box<UserId>,
|
||||
},
|
||||
|
||||
InviteState {
|
||||
user_id: Box<UserId>,
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) async fn process(
|
||||
subcommand: RoomStateCacheCommand, context: &Command<'_>,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
let services = context.services;
|
||||
|
||||
pub(super) async fn room_state_cache(subcommand: RoomStateCache) -> Result<RoomMessageEventContent> {
|
||||
match subcommand {
|
||||
RoomStateCache::ServerInRoom {
|
||||
RoomStateCacheCommand::ServerInRoom {
|
||||
server,
|
||||
room_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let result = services()
|
||||
.rooms
|
||||
.state_cache
|
||||
.server_in_room(&server, &room_id);
|
||||
let result = services.rooms.state_cache.server_in_room(&server, &room_id);
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::RoomServers {
|
||||
RoomStateCacheCommand::RoomServers {
|
||||
room_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results: Result<Vec<_>> = services()
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_servers(&room_id)
|
||||
.collect();
|
||||
let results: Result<Vec<_>> = services.rooms.state_cache.room_servers(&room_id).collect();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::ServerRooms {
|
||||
RoomStateCacheCommand::ServerRooms {
|
||||
server,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results: Result<Vec<_>> = services().rooms.state_cache.server_rooms(&server).collect();
|
||||
let results: Result<Vec<_>> = services.rooms.state_cache.server_rooms(&server).collect();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::RoomMembers {
|
||||
RoomStateCacheCommand::RoomMembers {
|
||||
room_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results: Result<Vec<_>> = services()
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_members(&room_id)
|
||||
.collect();
|
||||
let results: Result<Vec<_>> = services.rooms.state_cache.room_members(&room_id).collect();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::LocalUsersInRoom {
|
||||
RoomStateCacheCommand::LocalUsersInRoom {
|
||||
room_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results: Vec<_> = services()
|
||||
let results: Vec<_> = services
|
||||
.rooms
|
||||
.state_cache
|
||||
.local_users_in_room(&room_id)
|
||||
@@ -76,11 +141,11 @@ pub(super) async fn room_state_cache(subcommand: RoomStateCache) -> Result<RoomM
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::ActiveLocalUsersInRoom {
|
||||
RoomStateCacheCommand::ActiveLocalUsersInRoom {
|
||||
room_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results: Vec<_> = services()
|
||||
let results: Vec<_> = services
|
||||
.rooms
|
||||
.state_cache
|
||||
.active_local_users_in_room(&room_id)
|
||||
@@ -91,33 +156,33 @@ pub(super) async fn room_state_cache(subcommand: RoomStateCache) -> Result<RoomM
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::RoomJoinedCount {
|
||||
RoomStateCacheCommand::RoomJoinedCount {
|
||||
room_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().rooms.state_cache.room_joined_count(&room_id);
|
||||
let results = services.rooms.state_cache.room_joined_count(&room_id);
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::RoomInvitedCount {
|
||||
RoomStateCacheCommand::RoomInvitedCount {
|
||||
room_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().rooms.state_cache.room_invited_count(&room_id);
|
||||
let results = services.rooms.state_cache.room_invited_count(&room_id);
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::RoomUserOnceJoined {
|
||||
RoomStateCacheCommand::RoomUserOnceJoined {
|
||||
room_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results: Result<Vec<_>> = services()
|
||||
let results: Result<Vec<_>> = services
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_useroncejoined(&room_id)
|
||||
@@ -128,11 +193,11 @@ pub(super) async fn room_state_cache(subcommand: RoomStateCache) -> Result<RoomM
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::RoomMembersInvited {
|
||||
RoomStateCacheCommand::RoomMembersInvited {
|
||||
room_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results: Result<Vec<_>> = services()
|
||||
let results: Result<Vec<_>> = services
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_members_invited(&room_id)
|
||||
@@ -143,12 +208,12 @@ pub(super) async fn room_state_cache(subcommand: RoomStateCache) -> Result<RoomM
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::GetInviteCount {
|
||||
RoomStateCacheCommand::GetInviteCount {
|
||||
room_id,
|
||||
user_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services()
|
||||
let results = services
|
||||
.rooms
|
||||
.state_cache
|
||||
.get_invite_count(&room_id, &user_id);
|
||||
@@ -158,12 +223,12 @@ pub(super) async fn room_state_cache(subcommand: RoomStateCache) -> Result<RoomM
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::GetLeftCount {
|
||||
RoomStateCacheCommand::GetLeftCount {
|
||||
room_id,
|
||||
user_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services()
|
||||
let results = services
|
||||
.rooms
|
||||
.state_cache
|
||||
.get_left_count(&room_id, &user_id);
|
||||
@@ -173,56 +238,45 @@ pub(super) async fn room_state_cache(subcommand: RoomStateCache) -> Result<RoomM
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::RoomsJoined {
|
||||
RoomStateCacheCommand::RoomsJoined {
|
||||
user_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results: Result<Vec<_>> = services()
|
||||
.rooms
|
||||
.state_cache
|
||||
.rooms_joined(&user_id)
|
||||
.collect();
|
||||
let results: Result<Vec<_>> = services.rooms.state_cache.rooms_joined(&user_id).collect();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::RoomsInvited {
|
||||
RoomStateCacheCommand::RoomsInvited {
|
||||
user_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results: Result<Vec<_>> = services()
|
||||
.rooms
|
||||
.state_cache
|
||||
.rooms_invited(&user_id)
|
||||
.collect();
|
||||
let results: Result<Vec<_>> = services.rooms.state_cache.rooms_invited(&user_id).collect();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::RoomsLeft {
|
||||
RoomStateCacheCommand::RoomsLeft {
|
||||
user_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results: Result<Vec<_>> = services().rooms.state_cache.rooms_left(&user_id).collect();
|
||||
let results: Result<Vec<_>> = services.rooms.state_cache.rooms_left(&user_id).collect();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"
|
||||
)))
|
||||
},
|
||||
RoomStateCache::InviteState {
|
||||
RoomStateCacheCommand::InviteState {
|
||||
user_id,
|
||||
room_id,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services()
|
||||
.rooms
|
||||
.state_cache
|
||||
.invite_state(&user_id, &room_id);
|
||||
let results = services.rooms.state_cache.invite_state(&user_id, &room_id);
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
|
||||
@@ -1,14 +1,73 @@
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, ServerName, UserId};
|
||||
use service::sending::Destination;
|
||||
|
||||
use super::Sending;
|
||||
use crate::{service::sending::Destination, services, Result};
|
||||
use crate::Command;
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/sending.rs
|
||||
pub(crate) enum SendingCommand {
|
||||
/// - Queries database for all `servercurrentevent_data`
|
||||
ActiveRequests,
|
||||
|
||||
/// - Queries database for `servercurrentevent_data` but for a specific
|
||||
/// destination
|
||||
///
|
||||
/// This command takes only *one* format of these arguments:
|
||||
///
|
||||
/// appservice_id
|
||||
/// server_name
|
||||
/// user_id AND push_key
|
||||
///
|
||||
/// See src/service/sending/mod.rs for the definition of the `Destination`
|
||||
/// enum
|
||||
ActiveRequestsFor {
|
||||
#[arg(short, long)]
|
||||
appservice_id: Option<String>,
|
||||
#[arg(short, long)]
|
||||
server_name: Option<Box<ServerName>>,
|
||||
#[arg(short, long)]
|
||||
user_id: Option<Box<UserId>>,
|
||||
#[arg(short, long)]
|
||||
push_key: Option<String>,
|
||||
},
|
||||
|
||||
/// - Queries database for `servernameevent_data` which are the queued up
|
||||
/// requests that will eventually be sent
|
||||
///
|
||||
/// This command takes only *one* format of these arguments:
|
||||
///
|
||||
/// appservice_id
|
||||
/// server_name
|
||||
/// user_id AND push_key
|
||||
///
|
||||
/// See src/service/sending/mod.rs for the definition of the `Destination`
|
||||
/// enum
|
||||
QueuedRequests {
|
||||
#[arg(short, long)]
|
||||
appservice_id: Option<String>,
|
||||
#[arg(short, long)]
|
||||
server_name: Option<Box<ServerName>>,
|
||||
#[arg(short, long)]
|
||||
user_id: Option<Box<UserId>>,
|
||||
#[arg(short, long)]
|
||||
push_key: Option<String>,
|
||||
},
|
||||
|
||||
GetLatestEduCount {
|
||||
server_name: Box<ServerName>,
|
||||
},
|
||||
}
|
||||
|
||||
/// All the getters and iterators in key_value/sending.rs
|
||||
pub(super) async fn sending(subcommand: Sending) -> Result<RoomMessageEventContent> {
|
||||
pub(super) async fn process(subcommand: SendingCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||
let services = context.services;
|
||||
|
||||
match subcommand {
|
||||
Sending::ActiveRequests => {
|
||||
SendingCommand::ActiveRequests => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().sending.db.active_requests();
|
||||
let results = services.sending.db.active_requests();
|
||||
let active_requests: Result<Vec<(_, _, _)>> = results.collect();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
@@ -16,7 +75,7 @@ pub(super) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{active_requests:#?}\n```"
|
||||
)))
|
||||
},
|
||||
Sending::QueuedRequests {
|
||||
SendingCommand::QueuedRequests {
|
||||
appservice_id,
|
||||
server_name,
|
||||
user_id,
|
||||
@@ -38,12 +97,12 @@ pub(super) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
||||
));
|
||||
}
|
||||
|
||||
services()
|
||||
services
|
||||
.sending
|
||||
.db
|
||||
.queued_requests(&Destination::Appservice(appservice_id))
|
||||
},
|
||||
(None, Some(server_name), None, None) => services()
|
||||
(None, Some(server_name), None, None) => services
|
||||
.sending
|
||||
.db
|
||||
.queued_requests(&Destination::Normal(server_name.into())),
|
||||
@@ -55,7 +114,7 @@ pub(super) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
||||
));
|
||||
}
|
||||
|
||||
services()
|
||||
services
|
||||
.sending
|
||||
.db
|
||||
.queued_requests(&Destination::Push(user_id.into(), push_key))
|
||||
@@ -81,7 +140,7 @@ pub(super) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{queued_requests:#?}\n```"
|
||||
)))
|
||||
},
|
||||
Sending::ActiveRequestsFor {
|
||||
SendingCommand::ActiveRequestsFor {
|
||||
appservice_id,
|
||||
server_name,
|
||||
user_id,
|
||||
@@ -104,12 +163,12 @@ pub(super) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
||||
));
|
||||
}
|
||||
|
||||
services()
|
||||
services
|
||||
.sending
|
||||
.db
|
||||
.active_requests_for(&Destination::Appservice(appservice_id))
|
||||
},
|
||||
(None, Some(server_name), None, None) => services()
|
||||
(None, Some(server_name), None, None) => services
|
||||
.sending
|
||||
.db
|
||||
.active_requests_for(&Destination::Normal(server_name.into())),
|
||||
@@ -121,7 +180,7 @@ pub(super) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
||||
));
|
||||
}
|
||||
|
||||
services()
|
||||
services
|
||||
.sending
|
||||
.db
|
||||
.active_requests_for(&Destination::Push(user_id.into(), push_key))
|
||||
@@ -147,11 +206,11 @@ pub(super) async fn sending(subcommand: Sending) -> Result<RoomMessageEventConte
|
||||
"Query completed in {query_time:?}:\n\n```rs\n{active_requests:#?}\n```"
|
||||
)))
|
||||
},
|
||||
Sending::GetLatestEduCount {
|
||||
SendingCommand::GetLatestEduCount {
|
||||
server_name,
|
||||
} => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().sending.db.get_latest_educount(&server_name);
|
||||
let results = services.sending.db.get_latest_educount(&server_name);
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
|
||||
use super::Users;
|
||||
use crate::{services, Result};
|
||||
use crate::Command;
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
/// All the getters and iterators from src/database/key_value/users.rs
|
||||
pub(crate) enum UsersCommand {
|
||||
Iter,
|
||||
}
|
||||
|
||||
/// All the getters and iterators in key_value/users.rs
|
||||
pub(super) async fn users(subcommand: Users) -> Result<RoomMessageEventContent> {
|
||||
pub(super) async fn process(subcommand: UsersCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||
let services = context.services;
|
||||
|
||||
match subcommand {
|
||||
Users::Iter => {
|
||||
UsersCommand::Iter => {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let results = services().users.db.iter();
|
||||
let results = services.users.db.iter();
|
||||
let users = results.collect::<Vec<_>>();
|
||||
let query_time = timer.elapsed();
|
||||
|
||||
|
||||
@@ -1,12 +1,49 @@
|
||||
use std::fmt::Write;
|
||||
|
||||
use ruma::{events::room::message::RoomMessageEventContent, RoomAliasId};
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, RoomAliasId, RoomId};
|
||||
|
||||
use super::RoomAliasCommand;
|
||||
use crate::{escape_html, services, Result};
|
||||
use crate::{escape_html, Command};
|
||||
|
||||
pub(super) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
let server_user = &services().globals.server_user;
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(crate) enum RoomAliasCommand {
|
||||
/// - Make an alias point to a room.
|
||||
Set {
|
||||
#[arg(short, long)]
|
||||
/// Set the alias even if a room is already using it
|
||||
force: bool,
|
||||
|
||||
/// The room id to set the alias on
|
||||
room_id: Box<RoomId>,
|
||||
|
||||
/// The alias localpart to use (`alias`, not `#alias:servername.tld`)
|
||||
room_alias_localpart: String,
|
||||
},
|
||||
|
||||
/// - Remove a local alias
|
||||
Remove {
|
||||
/// The alias localpart to remove (`alias`, not `#alias:servername.tld`)
|
||||
room_alias_localpart: String,
|
||||
},
|
||||
|
||||
/// - Show which room is using an alias
|
||||
Which {
|
||||
/// The alias localpart to look up (`alias`, not
|
||||
/// `#alias:servername.tld`)
|
||||
room_alias_localpart: String,
|
||||
},
|
||||
|
||||
/// - List aliases currently being used
|
||||
List {
|
||||
/// If set, only list the aliases for this room
|
||||
room_id: Option<Box<RoomId>>,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) async fn process(command: RoomAliasCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||
let services = context.services;
|
||||
let server_user = &services.globals.server_user;
|
||||
|
||||
match command {
|
||||
RoomAliasCommand::Set {
|
||||
@@ -19,7 +56,7 @@ pub(super) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
||||
| RoomAliasCommand::Which {
|
||||
ref room_alias_localpart,
|
||||
} => {
|
||||
let room_alias_str = format!("#{}:{}", room_alias_localpart, services().globals.server_name());
|
||||
let room_alias_str = format!("#{}:{}", room_alias_localpart, services.globals.server_name());
|
||||
let room_alias = match RoomAliasId::parse_box(room_alias_str) {
|
||||
Ok(alias) => alias,
|
||||
Err(err) => return Ok(RoomMessageEventContent::text_plain(format!("Failed to parse alias: {err}"))),
|
||||
@@ -29,8 +66,8 @@ pub(super) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
||||
force,
|
||||
room_id,
|
||||
..
|
||||
} => match (force, services().rooms.alias.resolve_local_alias(&room_alias)) {
|
||||
(true, Ok(Some(id))) => match services()
|
||||
} => match (force, services.rooms.alias.resolve_local_alias(&room_alias)) {
|
||||
(true, Ok(Some(id))) => match services
|
||||
.rooms
|
||||
.alias
|
||||
.set_alias(&room_alias, &room_id, server_user)
|
||||
@@ -43,7 +80,7 @@ pub(super) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
||||
(false, Ok(Some(id))) => Ok(RoomMessageEventContent::text_plain(format!(
|
||||
"Refusing to overwrite in use alias for {id}, use -f or --force to overwrite"
|
||||
))),
|
||||
(_, Ok(None)) => match services()
|
||||
(_, Ok(None)) => match services
|
||||
.rooms
|
||||
.alias
|
||||
.set_alias(&room_alias, &room_id, server_user)
|
||||
@@ -55,8 +92,8 @@ pub(super) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
||||
},
|
||||
RoomAliasCommand::Remove {
|
||||
..
|
||||
} => match services().rooms.alias.resolve_local_alias(&room_alias) {
|
||||
Ok(Some(id)) => match services()
|
||||
} => match services.rooms.alias.resolve_local_alias(&room_alias) {
|
||||
Ok(Some(id)) => match services
|
||||
.rooms
|
||||
.alias
|
||||
.remove_alias(&room_alias, server_user)
|
||||
@@ -70,7 +107,7 @@ pub(super) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
||||
},
|
||||
RoomAliasCommand::Which {
|
||||
..
|
||||
} => match services().rooms.alias.resolve_local_alias(&room_alias) {
|
||||
} => match services.rooms.alias.resolve_local_alias(&room_alias) {
|
||||
Ok(Some(id)) => Ok(RoomMessageEventContent::text_plain(format!("Alias resolves to {id}"))),
|
||||
Ok(None) => Ok(RoomMessageEventContent::text_plain("Alias isn't in use.")),
|
||||
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to lookup alias: {err}"))),
|
||||
@@ -84,7 +121,7 @@ pub(super) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
||||
room_id,
|
||||
} => {
|
||||
if let Some(room_id) = room_id {
|
||||
let aliases = services()
|
||||
let aliases = services
|
||||
.rooms
|
||||
.alias
|
||||
.local_aliases_for_room(&room_id)
|
||||
@@ -109,14 +146,14 @@ pub(super) async fn process(command: RoomAliasCommand, _body: Vec<&str>) -> Resu
|
||||
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to list aliases: {err}"))),
|
||||
}
|
||||
} else {
|
||||
let aliases = services()
|
||||
let aliases = services
|
||||
.rooms
|
||||
.alias
|
||||
.all_local_aliases()
|
||||
.collect::<Result<Vec<_>, _>>();
|
||||
match aliases {
|
||||
Ok(aliases) => {
|
||||
let server_name = services().globals.server_name();
|
||||
let server_name = services.globals.server_name();
|
||||
let plain_list = aliases
|
||||
.iter()
|
||||
.fold(String::new(), |mut output, (alias, id)| {
|
||||
@@ -1,15 +1,18 @@
|
||||
use std::fmt::Write;
|
||||
|
||||
use conduit::Result;
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
|
||||
use crate::{escape_html, get_room_info, handler::PAGE_SIZE, services, Result};
|
||||
use crate::{admin_command, escape_html, get_room_info, PAGE_SIZE};
|
||||
|
||||
pub(super) async fn list(
|
||||
_body: Vec<&str>, page: Option<usize>, exclude_disabled: bool, exclude_banned: bool,
|
||||
#[admin_command]
|
||||
pub(super) async fn list_rooms(
|
||||
&self, page: Option<usize>, exclude_disabled: bool, exclude_banned: bool,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
// TODO: i know there's a way to do this with clap, but i can't seem to find it
|
||||
let page = page.unwrap_or(1);
|
||||
let mut rooms = services()
|
||||
let mut rooms = self
|
||||
.services
|
||||
.rooms
|
||||
.metadata
|
||||
.iter_ids()
|
||||
@@ -18,7 +21,8 @@ pub(super) async fn list(
|
||||
.ok()
|
||||
.filter(|room_id| {
|
||||
if exclude_disabled
|
||||
&& services()
|
||||
&& self
|
||||
.services
|
||||
.rooms
|
||||
.metadata
|
||||
.is_disabled(room_id)
|
||||
@@ -28,7 +32,8 @@ pub(super) async fn list(
|
||||
}
|
||||
|
||||
if exclude_banned
|
||||
&& services()
|
||||
&& self
|
||||
.services
|
||||
.rooms
|
||||
.metadata
|
||||
.is_banned(room_id)
|
||||
@@ -39,7 +44,7 @@ pub(super) async fn list(
|
||||
|
||||
true
|
||||
})
|
||||
.map(|room_id| get_room_info(&room_id))
|
||||
.map(|room_id| get_room_info(self.services, &room_id))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
rooms.sort_by_key(|r| r.1);
|
||||
@@ -1,21 +1,43 @@
|
||||
use std::fmt::Write;
|
||||
|
||||
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId};
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId, RoomId};
|
||||
|
||||
use super::RoomDirectoryCommand;
|
||||
use crate::{escape_html, get_room_info, handler::PAGE_SIZE, services, Result};
|
||||
use crate::{escape_html, get_room_info, Command, PAGE_SIZE};
|
||||
|
||||
pub(super) async fn process(command: RoomDirectoryCommand, _body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(crate) enum RoomDirectoryCommand {
|
||||
/// - Publish a room to the room directory
|
||||
Publish {
|
||||
/// The room id of the room to publish
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
/// - Unpublish a room to the room directory
|
||||
Unpublish {
|
||||
/// The room id of the room to unpublish
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
/// - List rooms that are published
|
||||
List {
|
||||
page: Option<usize>,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) async fn process(command: RoomDirectoryCommand, context: &Command<'_>) -> Result<RoomMessageEventContent> {
|
||||
let services = context.services;
|
||||
match command {
|
||||
RoomDirectoryCommand::Publish {
|
||||
room_id,
|
||||
} => match services().rooms.directory.set_public(&room_id) {
|
||||
} => match services.rooms.directory.set_public(&room_id) {
|
||||
Ok(()) => Ok(RoomMessageEventContent::text_plain("Room published")),
|
||||
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to update room: {err}"))),
|
||||
},
|
||||
RoomDirectoryCommand::Unpublish {
|
||||
room_id,
|
||||
} => match services().rooms.directory.set_not_public(&room_id) {
|
||||
} => match services.rooms.directory.set_not_public(&room_id) {
|
||||
Ok(()) => Ok(RoomMessageEventContent::text_plain("Room unpublished")),
|
||||
Err(err) => Ok(RoomMessageEventContent::text_plain(format!("Unable to update room: {err}"))),
|
||||
},
|
||||
@@ -24,12 +46,12 @@ pub(super) async fn process(command: RoomDirectoryCommand, _body: Vec<&str>) ->
|
||||
} => {
|
||||
// TODO: i know there's a way to do this with clap, but i can't seem to find it
|
||||
let page = page.unwrap_or(1);
|
||||
let mut rooms = services()
|
||||
let mut rooms = services
|
||||
.rooms
|
||||
.directory
|
||||
.public_rooms()
|
||||
.filter_map(Result::ok)
|
||||
.map(|id: OwnedRoomId| get_room_info(&id))
|
||||
.map(|id: OwnedRoomId| get_room_info(services, &id))
|
||||
.collect::<Vec<_>>();
|
||||
rooms.sort_by_key(|r| r.1);
|
||||
rooms.reverse();
|
||||
@@ -1,22 +1,30 @@
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, RoomId};
|
||||
use service::services;
|
||||
|
||||
use super::RoomInfoCommand;
|
||||
use crate::Result;
|
||||
use crate::{admin_command, admin_command_dispatch};
|
||||
|
||||
pub(super) async fn process(command: RoomInfoCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
match command {
|
||||
RoomInfoCommand::ListJoinedMembers {
|
||||
room_id,
|
||||
} => list_joined_members(body, room_id).await,
|
||||
RoomInfoCommand::ViewRoomTopic {
|
||||
room_id,
|
||||
} => view_room_topic(body, room_id).await,
|
||||
}
|
||||
#[admin_command_dispatch]
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(crate) enum RoomInfoCommand {
|
||||
/// - List joined members in a room
|
||||
ListJoinedMembers {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
/// - Displays room topic
|
||||
///
|
||||
/// Room topics can be huge, so this is in its
|
||||
/// own separate command
|
||||
ViewRoomTopic {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
}
|
||||
|
||||
async fn list_joined_members(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||
let room_name = services()
|
||||
#[admin_command]
|
||||
async fn list_joined_members(&self, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||
let room_name = self
|
||||
.services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.get_name(&room_id)
|
||||
@@ -24,7 +32,8 @@ async fn list_joined_members(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<R
|
||||
.flatten()
|
||||
.unwrap_or_else(|| room_id.to_string());
|
||||
|
||||
let members = services()
|
||||
let members = self
|
||||
.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_members(&room_id)
|
||||
@@ -35,7 +44,7 @@ async fn list_joined_members(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<R
|
||||
.map(|user_id| {
|
||||
(
|
||||
user_id.clone(),
|
||||
services()
|
||||
self.services
|
||||
.users
|
||||
.displayname(&user_id)
|
||||
.unwrap_or(None)
|
||||
@@ -58,12 +67,18 @@ async fn list_joined_members(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<R
|
||||
Ok(RoomMessageEventContent::notice_markdown(output_plain))
|
||||
}
|
||||
|
||||
async fn view_room_topic(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||
let Some(room_topic) = services().rooms.state_accessor.get_room_topic(&room_id)? else {
|
||||
#[admin_command]
|
||||
async fn view_room_topic(&self, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||
let Some(room_topic) = self
|
||||
.services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.get_room_topic(&room_id)?
|
||||
else {
|
||||
return Ok(RoomMessageEventContent::text_plain("Room does not have a room topic set."));
|
||||
};
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"Room topic:\n\n```{room_topic}\n```"
|
||||
"Room topic:\n```\n{room_topic}\n```"
|
||||
)))
|
||||
}
|
||||
@@ -1,20 +1,23 @@
|
||||
mod room_alias_commands;
|
||||
mod room_commands;
|
||||
mod room_directory_commands;
|
||||
mod room_info_commands;
|
||||
mod room_moderation_commands;
|
||||
mod alias;
|
||||
mod commands;
|
||||
mod directory;
|
||||
mod info;
|
||||
mod moderation;
|
||||
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, RoomId, RoomOrAliasId};
|
||||
|
||||
use self::room_commands::list;
|
||||
use self::{
|
||||
alias::RoomAliasCommand, directory::RoomDirectoryCommand, info::RoomInfoCommand, moderation::RoomModerationCommand,
|
||||
};
|
||||
use crate::admin_command_dispatch;
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
#[admin_command_dispatch]
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(super) enum RoomCommand {
|
||||
/// - List all rooms the server knows about
|
||||
List {
|
||||
#[clap(alias = "list")]
|
||||
ListRooms {
|
||||
page: Option<usize>,
|
||||
|
||||
/// Excludes rooms that we have federation disabled with
|
||||
@@ -42,153 +45,3 @@ pub(super) enum RoomCommand {
|
||||
/// - Manage the room directory
|
||||
Directory(RoomDirectoryCommand),
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
pub(super) enum RoomInfoCommand {
|
||||
/// - List joined members in a room
|
||||
ListJoinedMembers {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
/// - Displays room topic
|
||||
///
|
||||
/// Room topics can be huge, so this is in its
|
||||
/// own separate command
|
||||
ViewRoomTopic {
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
pub(super) enum RoomAliasCommand {
|
||||
/// - Make an alias point to a room.
|
||||
Set {
|
||||
#[arg(short, long)]
|
||||
/// Set the alias even if a room is already using it
|
||||
force: bool,
|
||||
|
||||
/// The room id to set the alias on
|
||||
room_id: Box<RoomId>,
|
||||
|
||||
/// The alias localpart to use (`alias`, not `#alias:servername.tld`)
|
||||
room_alias_localpart: String,
|
||||
},
|
||||
|
||||
/// - Remove a local alias
|
||||
Remove {
|
||||
/// The alias localpart to remove (`alias`, not `#alias:servername.tld`)
|
||||
room_alias_localpart: String,
|
||||
},
|
||||
|
||||
/// - Show which room is using an alias
|
||||
Which {
|
||||
/// The alias localpart to look up (`alias`, not
|
||||
/// `#alias:servername.tld`)
|
||||
room_alias_localpart: String,
|
||||
},
|
||||
|
||||
/// - List aliases currently being used
|
||||
List {
|
||||
/// If set, only list the aliases for this room
|
||||
room_id: Option<Box<RoomId>>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
pub(super) enum RoomDirectoryCommand {
|
||||
/// - Publish a room to the room directory
|
||||
Publish {
|
||||
/// The room id of the room to publish
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
/// - Unpublish a room to the room directory
|
||||
Unpublish {
|
||||
/// The room id of the room to unpublish
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
|
||||
/// - List rooms that are published
|
||||
List {
|
||||
page: Option<usize>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
pub(super) enum RoomModerationCommand {
|
||||
/// - Bans a room from local users joining and evicts all our local users
|
||||
/// from the room. Also blocks any invites (local and remote) for the
|
||||
/// banned room.
|
||||
///
|
||||
/// Server admins (users in the conduwuit admin room) will not be evicted
|
||||
/// and server admins can still join the room. To evict admins too, use
|
||||
/// --force (also ignores errors) To disable incoming federation of the
|
||||
/// room, use --disable-federation
|
||||
BanRoom {
|
||||
#[arg(short, long)]
|
||||
/// Evicts admins out of the room and ignores any potential errors when
|
||||
/// making our local users leave the room
|
||||
force: bool,
|
||||
|
||||
#[arg(long)]
|
||||
/// Disables incoming federation of the room after banning and evicting
|
||||
/// users
|
||||
disable_federation: bool,
|
||||
|
||||
/// The room in the format of `!roomid:example.com` or a room alias in
|
||||
/// the format of `#roomalias:example.com`
|
||||
room: Box<RoomOrAliasId>,
|
||||
},
|
||||
|
||||
/// - Bans a list of rooms (room IDs and room aliases) from a newline
|
||||
/// delimited codeblock similar to `user deactivate-all`
|
||||
BanListOfRooms {
|
||||
#[arg(short, long)]
|
||||
/// Evicts admins out of the room and ignores any potential errors when
|
||||
/// making our local users leave the room
|
||||
force: bool,
|
||||
|
||||
#[arg(long)]
|
||||
/// Disables incoming federation of the room after banning and evicting
|
||||
/// users
|
||||
disable_federation: bool,
|
||||
},
|
||||
|
||||
/// - Unbans a room to allow local users to join again
|
||||
///
|
||||
/// To re-enable incoming federation of the room, use --enable-federation
|
||||
UnbanRoom {
|
||||
#[arg(long)]
|
||||
/// Enables incoming federation of the room after unbanning
|
||||
enable_federation: bool,
|
||||
|
||||
/// The room in the format of `!roomid:example.com` or a room alias in
|
||||
/// the format of `#roomalias:example.com`
|
||||
room: Box<RoomOrAliasId>,
|
||||
},
|
||||
|
||||
/// - List of all rooms we have banned
|
||||
ListBannedRooms,
|
||||
}
|
||||
|
||||
pub(super) async fn process(command: RoomCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
Ok(match command {
|
||||
RoomCommand::Info(command) => room_info_commands::process(command, body).await?,
|
||||
|
||||
RoomCommand::Alias(command) => room_alias_commands::process(command, body).await?,
|
||||
|
||||
RoomCommand::Directory(command) => room_directory_commands::process(command, body).await?,
|
||||
|
||||
RoomCommand::Moderation(command) => room_moderation_commands::process(command, body).await?,
|
||||
|
||||
RoomCommand::List {
|
||||
page,
|
||||
exclude_disabled,
|
||||
exclude_banned,
|
||||
} => list(body, page, exclude_disabled, exclude_banned).await?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,37 +1,82 @@
|
||||
use api::client::leave_room;
|
||||
use clap::Subcommand;
|
||||
use conduit::{debug, error, info, warn, Result};
|
||||
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId, RoomAliasId, RoomId, RoomOrAliasId};
|
||||
use tracing::{debug, error, info, warn};
|
||||
|
||||
use super::{super::Service, RoomModerationCommand};
|
||||
use crate::{get_room_info, services, user_is_local, Result};
|
||||
use crate::{admin_command, admin_command_dispatch, get_room_info};
|
||||
|
||||
pub(super) async fn process(command: RoomModerationCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
match command {
|
||||
RoomModerationCommand::BanRoom {
|
||||
force,
|
||||
room,
|
||||
disable_federation,
|
||||
} => ban_room(body, force, room, disable_federation).await,
|
||||
RoomModerationCommand::BanListOfRooms {
|
||||
force,
|
||||
disable_federation,
|
||||
} => ban_list_of_rooms(body, force, disable_federation).await,
|
||||
RoomModerationCommand::UnbanRoom {
|
||||
room,
|
||||
enable_federation,
|
||||
} => unban_room(body, room, enable_federation).await,
|
||||
RoomModerationCommand::ListBannedRooms => list_banned_rooms(body).await,
|
||||
}
|
||||
#[admin_command_dispatch]
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(crate) enum RoomModerationCommand {
|
||||
/// - Bans a room from local users joining and evicts all our local users
|
||||
/// from the room. Also blocks any invites (local and remote) for the
|
||||
/// banned room.
|
||||
///
|
||||
/// Server admins (users in the conduwuit admin room) will not be evicted
|
||||
/// and server admins can still join the room. To evict admins too, use
|
||||
/// --force (also ignores errors) To disable incoming federation of the
|
||||
/// room, use --disable-federation
|
||||
BanRoom {
|
||||
#[arg(short, long)]
|
||||
/// Evicts admins out of the room and ignores any potential errors when
|
||||
/// making our local users leave the room
|
||||
force: bool,
|
||||
|
||||
#[arg(long)]
|
||||
/// Disables incoming federation of the room after banning and evicting
|
||||
/// users
|
||||
disable_federation: bool,
|
||||
|
||||
/// The room in the format of `!roomid:example.com` or a room alias in
|
||||
/// the format of `#roomalias:example.com`
|
||||
room: Box<RoomOrAliasId>,
|
||||
},
|
||||
|
||||
/// - Bans a list of rooms (room IDs and room aliases) from a newline
|
||||
/// delimited codeblock similar to `user deactivate-all`
|
||||
BanListOfRooms {
|
||||
#[arg(short, long)]
|
||||
/// Evicts admins out of the room and ignores any potential errors when
|
||||
/// making our local users leave the room
|
||||
force: bool,
|
||||
|
||||
#[arg(long)]
|
||||
/// Disables incoming federation of the room after banning and evicting
|
||||
/// users
|
||||
disable_federation: bool,
|
||||
},
|
||||
|
||||
/// - Unbans a room to allow local users to join again
|
||||
///
|
||||
/// To re-enable incoming federation of the room, use --enable-federation
|
||||
UnbanRoom {
|
||||
#[arg(long)]
|
||||
/// Enables incoming federation of the room after unbanning
|
||||
enable_federation: bool,
|
||||
|
||||
/// The room in the format of `!roomid:example.com` or a room alias in
|
||||
/// the format of `#roomalias:example.com`
|
||||
room: Box<RoomOrAliasId>,
|
||||
},
|
||||
|
||||
/// - List of all rooms we have banned
|
||||
ListBannedRooms {
|
||||
#[arg(long)]
|
||||
/// Whether to only output room IDs without supplementary room
|
||||
/// information
|
||||
no_details: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
async fn ban_room(
|
||||
_body: Vec<&str>, force: bool, room: Box<RoomOrAliasId>, disable_federation: bool,
|
||||
&self, force: bool, disable_federation: bool, room: Box<RoomOrAliasId>,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
debug!("Got room alias or ID: {}", room);
|
||||
|
||||
let admin_room_alias = &services().globals.admin_alias;
|
||||
let admin_room_alias = &self.services.globals.admin_alias;
|
||||
|
||||
if let Some(admin_room_id) = Service::get_admin_room()? {
|
||||
if let Some(admin_room_id) = self.services.admin.get_admin_room()? {
|
||||
if room.to_string().eq(&admin_room_id) || room.to_string().eq(admin_room_alias) {
|
||||
return Ok(RoomMessageEventContent::text_plain("Not allowed to ban the admin room."));
|
||||
}
|
||||
@@ -50,7 +95,7 @@ async fn ban_room(
|
||||
|
||||
debug!("Room specified is a room ID, banning room ID");
|
||||
|
||||
services().rooms.metadata.ban_room(&room_id, true)?;
|
||||
self.services.rooms.metadata.ban_room(&room_id, true)?;
|
||||
|
||||
room_id
|
||||
} else if room.is_room_alias_id() {
|
||||
@@ -69,12 +114,13 @@ async fn ban_room(
|
||||
get_alias_helper to fetch room ID remotely"
|
||||
);
|
||||
|
||||
let room_id = if let Some(room_id) = services().rooms.alias.resolve_local_alias(&room_alias)? {
|
||||
let room_id = if let Some(room_id) = self.services.rooms.alias.resolve_local_alias(&room_alias)? {
|
||||
room_id
|
||||
} else {
|
||||
debug!("We don't have this room alias to a room ID locally, attempting to fetch room ID over federation");
|
||||
|
||||
match services()
|
||||
match self
|
||||
.services
|
||||
.rooms
|
||||
.alias
|
||||
.resolve_alias(&room_alias, None)
|
||||
@@ -92,7 +138,7 @@ async fn ban_room(
|
||||
}
|
||||
};
|
||||
|
||||
services().rooms.metadata.ban_room(&room_id, true)?;
|
||||
self.services.rooms.metadata.ban_room(&room_id, true)?;
|
||||
|
||||
room_id
|
||||
} else {
|
||||
@@ -104,20 +150,21 @@ async fn ban_room(
|
||||
|
||||
debug!("Making all users leave the room {}", &room);
|
||||
if force {
|
||||
for local_user in services()
|
||||
for local_user in self
|
||||
.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_members(&room_id)
|
||||
.filter_map(|user| {
|
||||
user.ok().filter(|local_user| {
|
||||
user_is_local(local_user)
|
||||
self.services.globals.user_is_local(local_user)
|
||||
// additional wrapped check here is to avoid adding remote users
|
||||
// who are in the admin room to the list of local users (would
|
||||
// fail auth check)
|
||||
&& (user_is_local(local_user)
|
||||
&& (self.services.globals.user_is_local(local_user)
|
||||
// since this is a force operation, assume user is an admin
|
||||
// if somehow this fails
|
||||
&& services()
|
||||
&& self.services
|
||||
.users
|
||||
.is_admin(local_user)
|
||||
.unwrap_or(true))
|
||||
@@ -128,30 +175,31 @@ async fn ban_room(
|
||||
&local_user, &room_id
|
||||
);
|
||||
|
||||
if let Err(e) = leave_room(&local_user, &room_id, None).await {
|
||||
if let Err(e) = leave_room(self.services, &local_user, &room_id, None).await {
|
||||
warn!(%e, "Failed to leave room");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for local_user in services()
|
||||
for local_user in self
|
||||
.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_members(&room_id)
|
||||
.filter_map(|user| {
|
||||
user.ok().filter(|local_user| {
|
||||
local_user.server_name() == services().globals.server_name()
|
||||
local_user.server_name() == self.services.globals.server_name()
|
||||
// additional wrapped check here is to avoid adding remote users
|
||||
// who are in the admin room to the list of local users (would fail auth check)
|
||||
&& (local_user.server_name()
|
||||
== services().globals.server_name()
|
||||
&& !services()
|
||||
== self.services.globals.server_name()
|
||||
&& !self.services
|
||||
.users
|
||||
.is_admin(local_user)
|
||||
.unwrap_or(false))
|
||||
})
|
||||
}) {
|
||||
debug!("Attempting leave for user {} in room {}", &local_user, &room_id);
|
||||
if let Err(e) = leave_room(&local_user, &room_id, None).await {
|
||||
if let Err(e) = leave_room(self.services, &local_user, &room_id, None).await {
|
||||
error!(
|
||||
"Error attempting to make local user {} leave room {} during room banning: {}",
|
||||
&local_user, &room_id, e
|
||||
@@ -165,8 +213,27 @@ async fn ban_room(
|
||||
}
|
||||
}
|
||||
|
||||
// remove any local aliases, ignore errors
|
||||
for ref local_alias in self
|
||||
.services
|
||||
.rooms
|
||||
.alias
|
||||
.local_aliases_for_room(&room_id)
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
_ = self
|
||||
.services
|
||||
.rooms
|
||||
.alias
|
||||
.remove_alias(local_alias, &self.services.globals.server_user)
|
||||
.await;
|
||||
}
|
||||
|
||||
// unpublish from room directory, ignore errors
|
||||
_ = self.services.rooms.directory.set_not_public(&room_id);
|
||||
|
||||
if disable_federation {
|
||||
services().rooms.metadata.disable_room(&room_id, true)?;
|
||||
self.services.rooms.metadata.disable_room(&room_id, true)?;
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Room banned, removed all our local users, and disabled incoming federation with room.",
|
||||
));
|
||||
@@ -178,19 +245,22 @@ async fn ban_room(
|
||||
))
|
||||
}
|
||||
|
||||
async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: bool) -> Result<RoomMessageEventContent> {
|
||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
||||
#[admin_command]
|
||||
async fn ban_list_of_rooms(&self, force: bool, disable_federation: bool) -> Result<RoomMessageEventContent> {
|
||||
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||
{
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Expected code block in command body. Add --help for details.",
|
||||
));
|
||||
}
|
||||
|
||||
let rooms_s = body
|
||||
.clone()
|
||||
.drain(1..body.len().saturating_sub(1))
|
||||
let rooms_s = self
|
||||
.body
|
||||
.to_vec()
|
||||
.drain(1..self.body.len().saturating_sub(1))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let admin_room_alias = &services().globals.admin_alias;
|
||||
let admin_room_alias = &self.services.globals.admin_alias;
|
||||
|
||||
let mut room_ban_count: usize = 0;
|
||||
let mut room_ids: Vec<OwnedRoomId> = Vec::new();
|
||||
@@ -198,7 +268,7 @@ async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: boo
|
||||
for &room in &rooms_s {
|
||||
match <&RoomOrAliasId>::try_from(room) {
|
||||
Ok(room_alias_or_id) => {
|
||||
if let Some(admin_room_id) = Service::get_admin_room()? {
|
||||
if let Some(admin_room_id) = self.services.admin.get_admin_room()? {
|
||||
if room.to_owned().eq(&admin_room_id) || room.to_owned().eq(admin_room_alias) {
|
||||
info!("User specified admin room in bulk ban list, ignoring");
|
||||
continue;
|
||||
@@ -231,7 +301,7 @@ async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: boo
|
||||
match RoomAliasId::parse(room_alias_or_id) {
|
||||
Ok(room_alias) => {
|
||||
let room_id =
|
||||
if let Some(room_id) = services().rooms.alias.resolve_local_alias(&room_alias)? {
|
||||
if let Some(room_id) = self.services.rooms.alias.resolve_local_alias(&room_alias)? {
|
||||
room_id
|
||||
} else {
|
||||
debug!(
|
||||
@@ -239,7 +309,8 @@ async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: boo
|
||||
ID over federation"
|
||||
);
|
||||
|
||||
match services()
|
||||
match self
|
||||
.services
|
||||
.rooms
|
||||
.alias
|
||||
.resolve_alias(&room_alias, None)
|
||||
@@ -303,28 +374,35 @@ async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: boo
|
||||
}
|
||||
|
||||
for room_id in room_ids {
|
||||
if services().rooms.metadata.ban_room(&room_id, true).is_ok() {
|
||||
if self
|
||||
.services
|
||||
.rooms
|
||||
.metadata
|
||||
.ban_room(&room_id, true)
|
||||
.is_ok()
|
||||
{
|
||||
debug!("Banned {room_id} successfully");
|
||||
room_ban_count = room_ban_count.saturating_add(1);
|
||||
}
|
||||
|
||||
debug!("Making all users leave the room {}", &room_id);
|
||||
if force {
|
||||
for local_user in services()
|
||||
for local_user in self
|
||||
.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_members(&room_id)
|
||||
.filter_map(|user| {
|
||||
user.ok().filter(|local_user| {
|
||||
local_user.server_name() == services().globals.server_name()
|
||||
local_user.server_name() == self.services.globals.server_name()
|
||||
// additional wrapped check here is to avoid adding remote
|
||||
// users who are in the admin room to the list of local
|
||||
// users (would fail auth check)
|
||||
&& (local_user.server_name()
|
||||
== services().globals.server_name()
|
||||
== self.services.globals.server_name()
|
||||
// since this is a force operation, assume user is an
|
||||
// admin if somehow this fails
|
||||
&& services()
|
||||
&& self.services
|
||||
.users
|
||||
.is_admin(local_user)
|
||||
.unwrap_or(true))
|
||||
@@ -334,31 +412,32 @@ async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: boo
|
||||
"Attempting leave for user {} in room {} (forced, ignoring all errors, evicting admins too)",
|
||||
&local_user, room_id
|
||||
);
|
||||
if let Err(e) = leave_room(&local_user, &room_id, None).await {
|
||||
if let Err(e) = leave_room(self.services, &local_user, &room_id, None).await {
|
||||
warn!(%e, "Failed to leave room");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for local_user in services()
|
||||
for local_user in self
|
||||
.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_members(&room_id)
|
||||
.filter_map(|user| {
|
||||
user.ok().filter(|local_user| {
|
||||
local_user.server_name() == services().globals.server_name()
|
||||
local_user.server_name() == self.services.globals.server_name()
|
||||
// additional wrapped check here is to avoid adding remote
|
||||
// users who are in the admin room to the list of local
|
||||
// users (would fail auth check)
|
||||
&& (local_user.server_name()
|
||||
== services().globals.server_name()
|
||||
&& !services()
|
||||
== self.services.globals.server_name()
|
||||
&& !self.services
|
||||
.users
|
||||
.is_admin(local_user)
|
||||
.unwrap_or(false))
|
||||
})
|
||||
}) {
|
||||
debug!("Attempting leave for user {} in room {}", &local_user, &room_id);
|
||||
if let Err(e) = leave_room(&local_user, &room_id, None).await {
|
||||
if let Err(e) = leave_room(self.services, &local_user, &room_id, None).await {
|
||||
error!(
|
||||
"Error attempting to make local user {} leave room {} during bulk room banning: {}",
|
||||
&local_user, &room_id, e
|
||||
@@ -373,8 +452,27 @@ async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: boo
|
||||
}
|
||||
}
|
||||
|
||||
// remove any local aliases, ignore errors
|
||||
for ref local_alias in self
|
||||
.services
|
||||
.rooms
|
||||
.alias
|
||||
.local_aliases_for_room(&room_id)
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
_ = self
|
||||
.services
|
||||
.rooms
|
||||
.alias
|
||||
.remove_alias(local_alias, &self.services.globals.server_user)
|
||||
.await;
|
||||
}
|
||||
|
||||
// unpublish from room directory, ignore errors
|
||||
_ = self.services.rooms.directory.set_not_public(&room_id);
|
||||
|
||||
if disable_federation {
|
||||
services().rooms.metadata.disable_room(&room_id, true)?;
|
||||
self.services.rooms.metadata.disable_room(&room_id, true)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -390,9 +488,8 @@ async fn ban_list_of_rooms(body: Vec<&str>, force: bool, disable_federation: boo
|
||||
}
|
||||
}
|
||||
|
||||
async fn unban_room(
|
||||
_body: Vec<&str>, room: Box<RoomOrAliasId>, enable_federation: bool,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
async fn unban_room(&self, enable_federation: bool, room: Box<RoomOrAliasId>) -> Result<RoomMessageEventContent> {
|
||||
let room_id = if room.is_room_id() {
|
||||
let room_id = match RoomId::parse(&room) {
|
||||
Ok(room_id) => room_id,
|
||||
@@ -406,7 +503,7 @@ async fn unban_room(
|
||||
|
||||
debug!("Room specified is a room ID, unbanning room ID");
|
||||
|
||||
services().rooms.metadata.ban_room(&room_id, false)?;
|
||||
self.services.rooms.metadata.ban_room(&room_id, false)?;
|
||||
|
||||
room_id
|
||||
} else if room.is_room_alias_id() {
|
||||
@@ -425,12 +522,13 @@ async fn unban_room(
|
||||
get_alias_helper to fetch room ID remotely"
|
||||
);
|
||||
|
||||
let room_id = if let Some(room_id) = services().rooms.alias.resolve_local_alias(&room_alias)? {
|
||||
let room_id = if let Some(room_id) = self.services.rooms.alias.resolve_local_alias(&room_alias)? {
|
||||
room_id
|
||||
} else {
|
||||
debug!("We don't have this room alias to a room ID locally, attempting to fetch room ID over federation");
|
||||
|
||||
match services()
|
||||
match self
|
||||
.services
|
||||
.rooms
|
||||
.alias
|
||||
.resolve_alias(&room_alias, None)
|
||||
@@ -448,7 +546,7 @@ async fn unban_room(
|
||||
}
|
||||
};
|
||||
|
||||
services().rooms.metadata.ban_room(&room_id, false)?;
|
||||
self.services.rooms.metadata.ban_room(&room_id, false)?;
|
||||
|
||||
room_id
|
||||
} else {
|
||||
@@ -459,7 +557,7 @@ async fn unban_room(
|
||||
};
|
||||
|
||||
if enable_federation {
|
||||
services().rooms.metadata.disable_room(&room_id, false)?;
|
||||
self.services.rooms.metadata.disable_room(&room_id, false)?;
|
||||
return Ok(RoomMessageEventContent::text_plain("Room unbanned."));
|
||||
}
|
||||
|
||||
@@ -469,8 +567,10 @@ async fn unban_room(
|
||||
))
|
||||
}
|
||||
|
||||
async fn list_banned_rooms(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
let rooms = services()
|
||||
#[admin_command]
|
||||
async fn list_banned_rooms(&self, no_details: bool) -> Result<RoomMessageEventContent> {
|
||||
let rooms = self
|
||||
.services
|
||||
.rooms
|
||||
.metadata
|
||||
.list_banned_rooms()
|
||||
@@ -484,17 +584,21 @@ async fn list_banned_rooms(_body: Vec<&str>) -> Result<RoomMessageEventContent>
|
||||
|
||||
let mut rooms = room_ids
|
||||
.into_iter()
|
||||
.map(|room_id| get_room_info(&room_id))
|
||||
.map(|room_id| get_room_info(self.services, &room_id))
|
||||
.collect::<Vec<_>>();
|
||||
rooms.sort_by_key(|r| r.1);
|
||||
rooms.reverse();
|
||||
|
||||
let output_plain = format!(
|
||||
"Rooms Banned ({}):\n```\n{}```",
|
||||
"Rooms Banned ({}):\n```\n{}\n```",
|
||||
rooms.len(),
|
||||
rooms
|
||||
.iter()
|
||||
.map(|(id, members, name)| format!("{id}\tMembers: {members}\tName: {name}"))
|
||||
.map(|(id, members, name)| if no_details {
|
||||
format!("{id}")
|
||||
} else {
|
||||
format!("{id}\tMembers: {members}\tName: {name}")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
);
|
||||
@@ -502,7 +606,7 @@ async fn list_banned_rooms(_body: Vec<&str>) -> Result<RoomMessageEventContent>
|
||||
Ok(RoomMessageEventContent::notice_markdown(output_plain))
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Failed to list banned rooms: {}", e);
|
||||
error!("Failed to list banned rooms: {e}");
|
||||
Ok(RoomMessageEventContent::text_plain(format!("Unable to list banned rooms: {e}")))
|
||||
},
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
use conduit::{utils::time, warn, Err, Result};
|
||||
use std::{fmt::Write, sync::Arc};
|
||||
|
||||
use conduit::{info, utils::time, warn, Err, Result};
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
|
||||
use crate::services;
|
||||
use crate::admin_command;
|
||||
|
||||
pub(super) async fn uptime(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
let elapsed = services()
|
||||
#[admin_command]
|
||||
pub(super) async fn uptime(&self) -> Result<RoomMessageEventContent> {
|
||||
let elapsed = self
|
||||
.services
|
||||
.server
|
||||
.started
|
||||
.elapsed()
|
||||
@@ -14,14 +18,58 @@ pub(super) async fn uptime(_body: Vec<&str>) -> Result<RoomMessageEventContent>
|
||||
Ok(RoomMessageEventContent::notice_plain(format!("{result}.")))
|
||||
}
|
||||
|
||||
pub(super) async fn show_config(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
pub(super) async fn show_config(&self) -> Result<RoomMessageEventContent> {
|
||||
// Construct and send the response
|
||||
Ok(RoomMessageEventContent::text_plain(format!("{}", services().globals.config)))
|
||||
Ok(RoomMessageEventContent::text_plain(format!("{}", self.services.globals.config)))
|
||||
}
|
||||
|
||||
pub(super) async fn memory_usage(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
let services_usage = services().memory_usage().await?;
|
||||
let database_usage = services().db.db.memory_usage()?;
|
||||
#[admin_command]
|
||||
pub(super) async fn list_features(
|
||||
&self, available: bool, enabled: bool, comma: bool,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
let delim = if comma {
|
||||
","
|
||||
} else {
|
||||
" "
|
||||
};
|
||||
if enabled && !available {
|
||||
let features = info::rustc::features().join(delim);
|
||||
let out = format!("`\n{features}\n`");
|
||||
return Ok(RoomMessageEventContent::text_markdown(out));
|
||||
}
|
||||
|
||||
if available && !enabled {
|
||||
let features = info::cargo::features().join(delim);
|
||||
let out = format!("`\n{features}\n`");
|
||||
return Ok(RoomMessageEventContent::text_markdown(out));
|
||||
}
|
||||
|
||||
let mut features = String::new();
|
||||
let enabled = info::rustc::features();
|
||||
let available = info::cargo::features();
|
||||
for feature in available {
|
||||
let active = enabled.contains(&feature.as_str());
|
||||
let emoji = if active {
|
||||
"✅"
|
||||
} else {
|
||||
"❌"
|
||||
};
|
||||
let remark = if active {
|
||||
"[enabled]"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
writeln!(features, "{emoji} {feature} {remark}")?;
|
||||
}
|
||||
|
||||
Ok(RoomMessageEventContent::text_markdown(features))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn memory_usage(&self) -> Result<RoomMessageEventContent> {
|
||||
let services_usage = self.services.memory_usage().await?;
|
||||
let database_usage = self.services.db.db.memory_usage()?;
|
||||
let allocator_usage = conduit::alloc::memory_usage().map_or(String::new(), |s| format!("\nAllocator:\n{s}"));
|
||||
|
||||
Ok(RoomMessageEventContent::text_plain(format!(
|
||||
@@ -29,14 +77,16 @@ pub(super) async fn memory_usage(_body: Vec<&str>) -> Result<RoomMessageEventCon
|
||||
)))
|
||||
}
|
||||
|
||||
pub(super) async fn clear_caches(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
services().clear_cache().await;
|
||||
#[admin_command]
|
||||
pub(super) async fn clear_caches(&self) -> Result<RoomMessageEventContent> {
|
||||
self.services.clear_cache().await;
|
||||
|
||||
Ok(RoomMessageEventContent::text_plain("Done."))
|
||||
}
|
||||
|
||||
pub(super) async fn list_backups(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
let result = services().globals.db.backup_list()?;
|
||||
#[admin_command]
|
||||
pub(super) async fn list_backups(&self) -> Result<RoomMessageEventContent> {
|
||||
let result = self.services.globals.db.backup_list()?;
|
||||
|
||||
if result.is_empty() {
|
||||
Ok(RoomMessageEventContent::text_plain("No backups found."))
|
||||
@@ -45,46 +95,51 @@ pub(super) async fn list_backups(_body: Vec<&str>) -> Result<RoomMessageEventCon
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn backup_database(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
let mut result = services()
|
||||
#[admin_command]
|
||||
pub(super) async fn backup_database(&self) -> Result<RoomMessageEventContent> {
|
||||
let globals = Arc::clone(&self.services.globals);
|
||||
let mut result = self
|
||||
.services
|
||||
.server
|
||||
.runtime()
|
||||
.spawn_blocking(move || match services().globals.db.backup() {
|
||||
.spawn_blocking(move || match globals.db.backup() {
|
||||
Ok(()) => String::new(),
|
||||
Err(e) => (*e).to_string(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
.await?;
|
||||
|
||||
if result.is_empty() {
|
||||
result = services().globals.db.backup_list()?;
|
||||
result = self.services.globals.db.backup_list()?;
|
||||
}
|
||||
|
||||
Ok(RoomMessageEventContent::text_plain(&result))
|
||||
}
|
||||
|
||||
pub(super) async fn list_database_files(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
let result = services().globals.db.file_list()?;
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(result))
|
||||
}
|
||||
|
||||
pub(super) async fn admin_notice(_body: Vec<&str>, message: Vec<String>) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
pub(super) async fn list_database_files(&self) -> Result<RoomMessageEventContent> {
|
||||
let result = self.services.globals.db.file_list()?;
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(result))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn admin_notice(&self, message: Vec<String>) -> Result<RoomMessageEventContent> {
|
||||
let message = message.join(" ");
|
||||
services().admin.send_text(&message).await;
|
||||
self.services.admin.send_text(&message).await;
|
||||
|
||||
Ok(RoomMessageEventContent::notice_plain("Notice was sent to #admins"))
|
||||
}
|
||||
|
||||
#[cfg(conduit_mods)]
|
||||
pub(super) async fn reload(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
services().server.reload()?;
|
||||
#[admin_command]
|
||||
pub(super) async fn reload_mods(&self) -> Result<RoomMessageEventContent> {
|
||||
self.services.server.reload()?;
|
||||
|
||||
Ok(RoomMessageEventContent::notice_plain("Reloading server..."))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
#[cfg(unix)]
|
||||
pub(super) async fn restart(_body: Vec<&str>, force: bool) -> Result<RoomMessageEventContent> {
|
||||
pub(super) async fn restart(&self, force: bool) -> Result<RoomMessageEventContent> {
|
||||
use conduit::utils::sys::current_exe_deleted;
|
||||
|
||||
if !force && current_exe_deleted() {
|
||||
@@ -94,14 +149,15 @@ pub(super) async fn restart(_body: Vec<&str>, force: bool) -> Result<RoomMessage
|
||||
);
|
||||
}
|
||||
|
||||
services().server.restart()?;
|
||||
self.services.server.restart()?;
|
||||
|
||||
Ok(RoomMessageEventContent::notice_plain("Restarting server..."))
|
||||
}
|
||||
|
||||
pub(super) async fn shutdown(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
pub(super) async fn shutdown(&self) -> Result<RoomMessageEventContent> {
|
||||
warn!("shutdown command");
|
||||
services().server.shutdown()?;
|
||||
self.services.server.shutdown()?;
|
||||
|
||||
Ok(RoomMessageEventContent::notice_plain("Shutting down server..."))
|
||||
}
|
||||
|
||||
@@ -2,12 +2,11 @@
|
||||
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::events::room::message::RoomMessageEventContent;
|
||||
|
||||
use self::commands::*;
|
||||
use crate::admin_command_dispatch;
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
#[admin_command_dispatch]
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(super) enum ServerCommand {
|
||||
/// - Time elapsed since startup
|
||||
Uptime,
|
||||
@@ -15,6 +14,18 @@ pub(super) enum ServerCommand {
|
||||
/// - Show configuration values
|
||||
ShowConfig,
|
||||
|
||||
/// - List the features built into the server
|
||||
ListFeatures {
|
||||
#[arg(short, long)]
|
||||
available: bool,
|
||||
|
||||
#[arg(short, long)]
|
||||
enabled: bool,
|
||||
|
||||
#[arg(short, long)]
|
||||
comma: bool,
|
||||
},
|
||||
|
||||
/// - Print database memory usage statistics
|
||||
MemoryUsage,
|
||||
|
||||
@@ -36,9 +47,9 @@ pub(super) enum ServerCommand {
|
||||
message: Vec<String>,
|
||||
},
|
||||
|
||||
#[cfg(conduit_mods)]
|
||||
/// - Hot-reload the server
|
||||
Reload,
|
||||
#[clap(alias = "reload")]
|
||||
ReloadMods,
|
||||
|
||||
#[cfg(unix)]
|
||||
/// - Restart the server
|
||||
@@ -50,25 +61,3 @@ pub(super) enum ServerCommand {
|
||||
/// - Shutdown the server
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
pub(super) async fn process(command: ServerCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
Ok(match command {
|
||||
ServerCommand::Uptime => uptime(body).await?,
|
||||
ServerCommand::ShowConfig => show_config(body).await?,
|
||||
ServerCommand::MemoryUsage => memory_usage(body).await?,
|
||||
ServerCommand::ClearCaches => clear_caches(body).await?,
|
||||
ServerCommand::ListBackups => list_backups(body).await?,
|
||||
ServerCommand::BackupDatabase => backup_database(body).await?,
|
||||
ServerCommand::ListDatabaseFiles => list_database_files(body).await?,
|
||||
ServerCommand::AdminNotice {
|
||||
message,
|
||||
} => admin_notice(body, message).await?,
|
||||
#[cfg(conduit_mods)]
|
||||
ServerCommand::Reload => reload(body).await?,
|
||||
#[cfg(unix)]
|
||||
ServerCommand::Restart {
|
||||
force,
|
||||
} => restart(body, force).await?,
|
||||
ServerCommand::Shutdown => shutdown(body).await?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
fn get_help_inner(input: &str) {
|
||||
use clap::Parser;
|
||||
|
||||
use crate::handler::AdminCommand;
|
||||
use crate::admin::AdminCommand;
|
||||
|
||||
let Err(error) = AdminCommand::try_parse_from(["argv[0] doesn't matter", input]) else {
|
||||
panic!("no error!");
|
||||
|
||||
@@ -1,26 +1,27 @@
|
||||
use std::{collections::BTreeMap, fmt::Write as _};
|
||||
|
||||
use api::client::{join_room_by_id_helper, leave_all_rooms, update_avatar_url, update_displayname};
|
||||
use conduit::{utils, Result};
|
||||
use conduit::{error, info, utils, warn, PduBuilder, Result};
|
||||
use ruma::{
|
||||
events::{
|
||||
room::message::RoomMessageEventContent,
|
||||
room::{message::RoomMessageEventContent, redaction::RoomRedactionEventContent},
|
||||
tag::{TagEvent, TagEventContent, TagInfo},
|
||||
RoomAccountDataEventType,
|
||||
RoomAccountDataEventType, TimelineEventType,
|
||||
},
|
||||
OwnedRoomId, OwnedRoomOrAliasId, OwnedUserId, RoomId,
|
||||
EventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedUserId, RoomId,
|
||||
};
|
||||
use tracing::{error, info, warn};
|
||||
use serde_json::value::to_raw_value;
|
||||
|
||||
use crate::{
|
||||
escape_html, get_room_info, services,
|
||||
admin_command, escape_html, get_room_info,
|
||||
utils::{parse_active_local_user_id, parse_local_user_id},
|
||||
};
|
||||
|
||||
const AUTO_GEN_PASSWORD_LENGTH: usize = 25;
|
||||
|
||||
pub(super) async fn list(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
match services().users.list_local_users() {
|
||||
#[admin_command]
|
||||
pub(super) async fn list_users(&self) -> Result<RoomMessageEventContent> {
|
||||
match self.services.users.list_local_users() {
|
||||
Ok(users) => {
|
||||
let mut plain_msg = format!("Found {} local user account(s):\n```\n", users.len());
|
||||
plain_msg += users.join("\n").as_str();
|
||||
@@ -32,43 +33,51 @@ pub(super) async fn list(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn create(
|
||||
_body: Vec<&str>, username: String, password: Option<String>,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
pub(super) async fn create_user(&self, username: String, password: Option<String>) -> Result<RoomMessageEventContent> {
|
||||
// Validate user id
|
||||
let user_id = parse_local_user_id(&username)?;
|
||||
let user_id = parse_local_user_id(self.services, &username)?;
|
||||
|
||||
if services().users.exists(&user_id)? {
|
||||
if self.services.users.exists(&user_id)? {
|
||||
return Ok(RoomMessageEventContent::text_plain(format!("Userid {user_id} already exists")));
|
||||
}
|
||||
|
||||
if user_id.is_historical() {
|
||||
return Ok(RoomMessageEventContent::text_plain(format!(
|
||||
"User ID {user_id} does not conform to new Matrix identifier spec"
|
||||
)));
|
||||
}
|
||||
|
||||
let password = password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
|
||||
|
||||
// Create user
|
||||
services().users.create(&user_id, Some(password.as_str()))?;
|
||||
self.services
|
||||
.users
|
||||
.create(&user_id, Some(password.as_str()))?;
|
||||
|
||||
// Default to pretty displayname
|
||||
let mut displayname = user_id.localpart().to_owned();
|
||||
|
||||
// If `new_user_displayname_suffix` is set, registration will push whatever
|
||||
// content is set to the user's display name with a space before it
|
||||
if !services()
|
||||
if !self
|
||||
.services
|
||||
.globals
|
||||
.config
|
||||
.new_user_displayname_suffix
|
||||
.is_empty()
|
||||
{
|
||||
write!(displayname, " {}", services().globals.config.new_user_displayname_suffix)
|
||||
write!(displayname, " {}", self.services.globals.config.new_user_displayname_suffix)
|
||||
.expect("should be able to write to string buffer");
|
||||
}
|
||||
|
||||
services()
|
||||
self.services
|
||||
.users
|
||||
.set_displayname(&user_id, Some(displayname))
|
||||
.await?;
|
||||
|
||||
// Initial account data
|
||||
services().account_data.update(
|
||||
self.services.account_data.update(
|
||||
None,
|
||||
&user_id,
|
||||
ruma::events::GlobalAccountDataEventType::PushRules
|
||||
@@ -82,12 +91,13 @@ pub(super) async fn create(
|
||||
.expect("to json value always works"),
|
||||
)?;
|
||||
|
||||
if !services().globals.config.auto_join_rooms.is_empty() {
|
||||
for room in &services().globals.config.auto_join_rooms {
|
||||
if !services()
|
||||
if !self.services.globals.config.auto_join_rooms.is_empty() {
|
||||
for room in &self.services.globals.config.auto_join_rooms {
|
||||
if !self
|
||||
.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.server_in_room(services().globals.server_name(), room)?
|
||||
.server_in_room(self.services.globals.server_name(), room)?
|
||||
{
|
||||
warn!("Skipping room {room} to automatically join as we have never joined before.");
|
||||
continue;
|
||||
@@ -95,10 +105,11 @@ pub(super) async fn create(
|
||||
|
||||
if let Some(room_id_server_name) = room.server_name() {
|
||||
match join_room_by_id_helper(
|
||||
self.services,
|
||||
&user_id,
|
||||
room,
|
||||
Some("Automatically joining this room upon registration".to_owned()),
|
||||
&[room_id_server_name.to_owned(), services().globals.server_name().to_owned()],
|
||||
&[room_id_server_name.to_owned(), self.services.globals.server_name().to_owned()],
|
||||
None,
|
||||
)
|
||||
.await
|
||||
@@ -123,38 +134,38 @@ pub(super) async fn create(
|
||||
)))
|
||||
}
|
||||
|
||||
pub(super) async fn deactivate(
|
||||
_body: Vec<&str>, no_leave_rooms: bool, user_id: String,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
pub(super) async fn deactivate(&self, no_leave_rooms: bool, user_id: String) -> Result<RoomMessageEventContent> {
|
||||
// Validate user id
|
||||
let user_id = parse_local_user_id(&user_id)?;
|
||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||
|
||||
// don't deactivate the server service account
|
||||
if user_id == services().globals.server_user {
|
||||
if user_id == self.services.globals.server_user {
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Not allowed to deactivate the server service account.",
|
||||
));
|
||||
}
|
||||
|
||||
services().users.deactivate_account(&user_id)?;
|
||||
self.services.users.deactivate_account(&user_id)?;
|
||||
|
||||
if !no_leave_rooms {
|
||||
services()
|
||||
self.services
|
||||
.admin
|
||||
.send_message(RoomMessageEventContent::text_plain(format!(
|
||||
"Making {user_id} leave all rooms after deactivation..."
|
||||
)))
|
||||
.await;
|
||||
|
||||
let all_joined_rooms: Vec<OwnedRoomId> = services()
|
||||
let all_joined_rooms: Vec<OwnedRoomId> = self
|
||||
.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.rooms_joined(&user_id)
|
||||
.filter_map(Result::ok)
|
||||
.collect();
|
||||
update_displayname(user_id.clone(), None, all_joined_rooms.clone()).await?;
|
||||
update_avatar_url(user_id.clone(), None, None, all_joined_rooms).await?;
|
||||
leave_all_rooms(&user_id).await;
|
||||
update_displayname(self.services, user_id.clone(), None, all_joined_rooms.clone()).await?;
|
||||
update_avatar_url(self.services, user_id.clone(), None, None, all_joined_rooms).await?;
|
||||
leave_all_rooms(self.services, &user_id).await;
|
||||
}
|
||||
|
||||
Ok(RoomMessageEventContent::text_plain(format!(
|
||||
@@ -162,10 +173,11 @@ pub(super) async fn deactivate(
|
||||
)))
|
||||
}
|
||||
|
||||
pub(super) async fn reset_password(_body: Vec<&str>, username: String) -> Result<RoomMessageEventContent> {
|
||||
let user_id = parse_local_user_id(&username)?;
|
||||
#[admin_command]
|
||||
pub(super) async fn reset_password(&self, username: String) -> Result<RoomMessageEventContent> {
|
||||
let user_id = parse_local_user_id(self.services, &username)?;
|
||||
|
||||
if user_id == services().globals.server_user {
|
||||
if user_id == self.services.globals.server_user {
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Not allowed to set the password for the server account. Please use the emergency password config option.",
|
||||
));
|
||||
@@ -173,7 +185,8 @@ pub(super) async fn reset_password(_body: Vec<&str>, username: String) -> Result
|
||||
|
||||
let new_password = utils::random_string(AUTO_GEN_PASSWORD_LENGTH);
|
||||
|
||||
match services()
|
||||
match self
|
||||
.services
|
||||
.users
|
||||
.set_password(&user_id, Some(new_password.as_str()))
|
||||
{
|
||||
@@ -186,28 +199,29 @@ pub(super) async fn reset_password(_body: Vec<&str>, username: String) -> Result
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn deactivate_all(
|
||||
body: Vec<&str>, no_leave_rooms: bool, force: bool,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
if body.len() < 2 || !body[0].trim().starts_with("```") || body.last().unwrap_or(&"").trim() != "```" {
|
||||
#[admin_command]
|
||||
pub(super) async fn deactivate_all(&self, no_leave_rooms: bool, force: bool) -> Result<RoomMessageEventContent> {
|
||||
if self.body.len() < 2 || !self.body[0].trim().starts_with("```") || self.body.last().unwrap_or(&"").trim() != "```"
|
||||
{
|
||||
return Ok(RoomMessageEventContent::text_plain(
|
||||
"Expected code block in command body. Add --help for details.",
|
||||
));
|
||||
}
|
||||
|
||||
let usernames = body
|
||||
.clone()
|
||||
.drain(1..body.len().saturating_sub(1))
|
||||
let usernames = self
|
||||
.body
|
||||
.to_vec()
|
||||
.drain(1..self.body.len().saturating_sub(1))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let mut user_ids: Vec<OwnedUserId> = Vec::with_capacity(usernames.len());
|
||||
let mut admins = Vec::new();
|
||||
|
||||
for username in usernames {
|
||||
match parse_active_local_user_id(username) {
|
||||
match parse_active_local_user_id(self.services, username) {
|
||||
Ok(user_id) => {
|
||||
if services().users.is_admin(&user_id)? && !force {
|
||||
services()
|
||||
if self.services.users.is_admin(&user_id)? && !force {
|
||||
self.services
|
||||
.admin
|
||||
.send_message(RoomMessageEventContent::text_plain(format!(
|
||||
"{username} is an admin and --force is not set, skipping over"
|
||||
@@ -218,8 +232,8 @@ pub(super) async fn deactivate_all(
|
||||
}
|
||||
|
||||
// don't deactivate the server service account
|
||||
if user_id == services().globals.server_user {
|
||||
services()
|
||||
if user_id == self.services.globals.server_user {
|
||||
self.services
|
||||
.admin
|
||||
.send_message(RoomMessageEventContent::text_plain(format!(
|
||||
"{username} is the server service account, skipping over"
|
||||
@@ -231,7 +245,7 @@ pub(super) async fn deactivate_all(
|
||||
user_ids.push(user_id);
|
||||
},
|
||||
Err(e) => {
|
||||
services()
|
||||
self.services
|
||||
.admin
|
||||
.send_message(RoomMessageEventContent::text_plain(format!(
|
||||
"{username} is not a valid username, skipping over: {e}"
|
||||
@@ -245,24 +259,25 @@ pub(super) async fn deactivate_all(
|
||||
let mut deactivation_count: usize = 0;
|
||||
|
||||
for user_id in user_ids {
|
||||
match services().users.deactivate_account(&user_id) {
|
||||
match self.services.users.deactivate_account(&user_id) {
|
||||
Ok(()) => {
|
||||
deactivation_count = deactivation_count.saturating_add(1);
|
||||
if !no_leave_rooms {
|
||||
info!("Forcing user {user_id} to leave all rooms apart of deactivate-all");
|
||||
let all_joined_rooms: Vec<OwnedRoomId> = services()
|
||||
let all_joined_rooms: Vec<OwnedRoomId> = self
|
||||
.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.rooms_joined(&user_id)
|
||||
.filter_map(Result::ok)
|
||||
.collect();
|
||||
update_displayname(user_id.clone(), None, all_joined_rooms.clone()).await?;
|
||||
update_avatar_url(user_id.clone(), None, None, all_joined_rooms).await?;
|
||||
leave_all_rooms(&user_id).await;
|
||||
update_displayname(self.services, user_id.clone(), None, all_joined_rooms.clone()).await?;
|
||||
update_avatar_url(self.services, user_id.clone(), None, None, all_joined_rooms).await?;
|
||||
leave_all_rooms(self.services, &user_id).await;
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
services()
|
||||
self.services
|
||||
.admin
|
||||
.send_message(RoomMessageEventContent::text_plain(format!("Failed deactivating user: {e}")))
|
||||
.await;
|
||||
@@ -283,16 +298,18 @@ pub(super) async fn deactivate_all(
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Result<RoomMessageEventContent> {
|
||||
#[admin_command]
|
||||
pub(super) async fn list_joined_rooms(&self, user_id: String) -> Result<RoomMessageEventContent> {
|
||||
// Validate user id
|
||||
let user_id = parse_local_user_id(&user_id)?;
|
||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||
|
||||
let mut rooms: Vec<(OwnedRoomId, u64, String)> = services()
|
||||
let mut rooms: Vec<(OwnedRoomId, u64, String)> = self
|
||||
.services
|
||||
.rooms
|
||||
.state_cache
|
||||
.rooms_joined(&user_id)
|
||||
.filter_map(Result::ok)
|
||||
.map(|room_id| get_room_info(&room_id))
|
||||
.map(|room_id| get_room_info(self.services, &room_id))
|
||||
.collect();
|
||||
|
||||
if rooms.is_empty() {
|
||||
@@ -334,41 +351,55 @@ pub(super) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Resu
|
||||
Ok(RoomMessageEventContent::text_html(output_plain, output_html))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn force_join_room(
|
||||
_body: Vec<&str>, user_id: String, room_id: OwnedRoomOrAliasId,
|
||||
&self, user_id: String, room_id: OwnedRoomOrAliasId,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
let user_id = parse_local_user_id(&user_id)?;
|
||||
let room_id = services().rooms.alias.resolve(&room_id).await?;
|
||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
|
||||
|
||||
assert!(service::user_is_local(&user_id), "Parsed user_id must be a local user");
|
||||
join_room_by_id_helper(&user_id, &room_id, None, &[], None).await?;
|
||||
assert!(
|
||||
self.services.globals.user_is_local(&user_id),
|
||||
"Parsed user_id must be a local user"
|
||||
);
|
||||
join_room_by_id_helper(self.services, &user_id, &room_id, None, &[], None).await?;
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"{user_id} has been joined to {room_id}.",
|
||||
)))
|
||||
}
|
||||
|
||||
pub(super) async fn make_user_admin(_body: Vec<&str>, user_id: String) -> Result<RoomMessageEventContent> {
|
||||
let user_id = parse_local_user_id(&user_id)?;
|
||||
let displayname = services()
|
||||
#[admin_command]
|
||||
pub(super) async fn make_user_admin(&self, user_id: String) -> Result<RoomMessageEventContent> {
|
||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||
let displayname = self
|
||||
.services
|
||||
.users
|
||||
.displayname(&user_id)?
|
||||
.unwrap_or_else(|| user_id.to_string());
|
||||
|
||||
assert!(service::user_is_local(&user_id), "Parsed user_id must be a local user");
|
||||
service::admin::make_user_admin(&user_id, displayname).await?;
|
||||
assert!(
|
||||
self.services.globals.user_is_local(&user_id),
|
||||
"Parsed user_id must be a local user"
|
||||
);
|
||||
self.services
|
||||
.admin
|
||||
.make_user_admin(&user_id, displayname)
|
||||
.await?;
|
||||
|
||||
Ok(RoomMessageEventContent::notice_markdown(format!(
|
||||
"{user_id} has been granted admin privileges.",
|
||||
)))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn put_room_tag(
|
||||
_body: Vec<&str>, user_id: String, room_id: Box<RoomId>, tag: String,
|
||||
&self, user_id: String, room_id: Box<RoomId>, tag: String,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
let user_id = parse_active_local_user_id(&user_id)?;
|
||||
let user_id = parse_active_local_user_id(self.services, &user_id)?;
|
||||
|
||||
let event = services()
|
||||
let event = self
|
||||
.services
|
||||
.account_data
|
||||
.get(Some(&room_id), &user_id, RoomAccountDataEventType::Tag)?;
|
||||
|
||||
@@ -386,7 +417,7 @@ pub(super) async fn put_room_tag(
|
||||
.tags
|
||||
.insert(tag.clone().into(), TagInfo::new());
|
||||
|
||||
services().account_data.update(
|
||||
self.services.account_data.update(
|
||||
Some(&room_id),
|
||||
&user_id,
|
||||
RoomAccountDataEventType::Tag,
|
||||
@@ -398,12 +429,14 @@ pub(super) async fn put_room_tag(
|
||||
)))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn delete_room_tag(
|
||||
_body: Vec<&str>, user_id: String, room_id: Box<RoomId>, tag: String,
|
||||
&self, user_id: String, room_id: Box<RoomId>, tag: String,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
let user_id = parse_active_local_user_id(&user_id)?;
|
||||
let user_id = parse_active_local_user_id(self.services, &user_id)?;
|
||||
|
||||
let event = services()
|
||||
let event = self
|
||||
.services
|
||||
.account_data
|
||||
.get(Some(&room_id), &user_id, RoomAccountDataEventType::Tag)?;
|
||||
|
||||
@@ -418,7 +451,7 @@ pub(super) async fn delete_room_tag(
|
||||
|
||||
tags_event.content.tags.remove(&tag.clone().into());
|
||||
|
||||
services().account_data.update(
|
||||
self.services.account_data.update(
|
||||
Some(&room_id),
|
||||
&user_id,
|
||||
RoomAccountDataEventType::Tag,
|
||||
@@ -430,12 +463,12 @@ pub(super) async fn delete_room_tag(
|
||||
)))
|
||||
}
|
||||
|
||||
pub(super) async fn get_room_tags(
|
||||
_body: Vec<&str>, user_id: String, room_id: Box<RoomId>,
|
||||
) -> Result<RoomMessageEventContent> {
|
||||
let user_id = parse_active_local_user_id(&user_id)?;
|
||||
#[admin_command]
|
||||
pub(super) async fn get_room_tags(&self, user_id: String, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
|
||||
let user_id = parse_active_local_user_id(self.services, &user_id)?;
|
||||
|
||||
let event = services()
|
||||
let event = self
|
||||
.services
|
||||
.account_data
|
||||
.get(Some(&room_id), &user_id, RoomAccountDataEventType::Tag)?;
|
||||
|
||||
@@ -453,3 +486,62 @@ pub(super) async fn get_room_tags(
|
||||
tags_event.content.tags
|
||||
)))
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn redact_event(&self, event_id: Box<EventId>) -> Result<RoomMessageEventContent> {
|
||||
let Some(event) = self
|
||||
.services
|
||||
.rooms
|
||||
.timeline
|
||||
.get_non_outlier_pdu(&event_id)?
|
||||
else {
|
||||
return Ok(RoomMessageEventContent::text_plain("Event does not exist in our database."));
|
||||
};
|
||||
|
||||
if event.is_redacted() {
|
||||
return Ok(RoomMessageEventContent::text_plain("Event is already redacted."));
|
||||
}
|
||||
|
||||
let room_id = event.room_id;
|
||||
let sender_user = event.sender;
|
||||
|
||||
if !self.services.globals.user_is_local(&sender_user) {
|
||||
return Ok(RoomMessageEventContent::text_plain("This command only works on local users."));
|
||||
}
|
||||
|
||||
let reason = format!(
|
||||
"The administrator(s) of {} has redacted this user's message.",
|
||||
self.services.globals.server_name()
|
||||
);
|
||||
|
||||
let state_lock = self.services.rooms.state.mutex.lock(&room_id).await;
|
||||
|
||||
let redaction_event_id = self
|
||||
.services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
PduBuilder {
|
||||
event_type: TimelineEventType::RoomRedaction,
|
||||
content: to_raw_value(&RoomRedactionEventContent {
|
||||
redacts: Some(event.event_id.clone().into()),
|
||||
reason: Some(reason),
|
||||
})
|
||||
.expect("event is valid, we just created it"),
|
||||
unsigned: None,
|
||||
state_key: None,
|
||||
redacts: Some(event.event_id),
|
||||
timestamp: None,
|
||||
},
|
||||
&sender_user,
|
||||
&room_id,
|
||||
&state_lock,
|
||||
)
|
||||
.await?;
|
||||
|
||||
drop(state_lock);
|
||||
|
||||
Ok(RoomMessageEventContent::text_plain(format!(
|
||||
"Successfully redacted event. Redaction event ID: {redaction_event_id}"
|
||||
)))
|
||||
}
|
||||
|
||||
@@ -2,15 +2,16 @@
|
||||
|
||||
use clap::Subcommand;
|
||||
use conduit::Result;
|
||||
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomOrAliasId, RoomId};
|
||||
use ruma::{EventId, OwnedRoomOrAliasId, RoomId};
|
||||
|
||||
use self::commands::*;
|
||||
use crate::admin_command_dispatch;
|
||||
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
#[derive(Subcommand)]
|
||||
#[admin_command_dispatch]
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(super) enum UserCommand {
|
||||
/// - Create a new user
|
||||
Create {
|
||||
#[clap(alias = "create")]
|
||||
CreateUser {
|
||||
/// Username of the new user
|
||||
username: String,
|
||||
/// Password of the new user, if unspecified one is generated
|
||||
@@ -57,7 +58,8 @@ pub(super) enum UserCommand {
|
||||
},
|
||||
|
||||
/// - List local users in the database
|
||||
List,
|
||||
#[clap(alias = "list")]
|
||||
ListUsers,
|
||||
|
||||
/// - Lists all the rooms (local and remote) that the specified user is
|
||||
/// joined in
|
||||
@@ -101,49 +103,12 @@ pub(super) enum UserCommand {
|
||||
user_id: String,
|
||||
room_id: Box<RoomId>,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) async fn process(command: UserCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
|
||||
Ok(match command {
|
||||
UserCommand::List => list(body).await?,
|
||||
UserCommand::Create {
|
||||
username,
|
||||
password,
|
||||
} => create(body, username, password).await?,
|
||||
UserCommand::Deactivate {
|
||||
no_leave_rooms,
|
||||
user_id,
|
||||
} => deactivate(body, no_leave_rooms, user_id).await?,
|
||||
UserCommand::ResetPassword {
|
||||
username,
|
||||
} => reset_password(body, username).await?,
|
||||
UserCommand::DeactivateAll {
|
||||
no_leave_rooms,
|
||||
force,
|
||||
} => deactivate_all(body, no_leave_rooms, force).await?,
|
||||
UserCommand::ListJoinedRooms {
|
||||
user_id,
|
||||
} => list_joined_rooms(body, user_id).await?,
|
||||
UserCommand::ForceJoinRoom {
|
||||
user_id,
|
||||
room_id,
|
||||
} => force_join_room(body, user_id, room_id).await?,
|
||||
UserCommand::MakeUserAdmin {
|
||||
user_id,
|
||||
} => make_user_admin(body, user_id).await?,
|
||||
UserCommand::PutRoomTag {
|
||||
user_id,
|
||||
room_id,
|
||||
tag,
|
||||
} => put_room_tag(body, user_id, room_id, tag).await?,
|
||||
UserCommand::DeleteRoomTag {
|
||||
user_id,
|
||||
room_id,
|
||||
tag,
|
||||
} => delete_room_tag(body, user_id, room_id, tag).await?,
|
||||
UserCommand::GetRoomTags {
|
||||
user_id,
|
||||
room_id,
|
||||
} => get_room_tags(body, user_id, room_id).await?,
|
||||
})
|
||||
/// - Attempts to forcefully redact the specified event ID from the sender
|
||||
/// user
|
||||
///
|
||||
/// This is only valid for local users
|
||||
RedactEvent {
|
||||
event_id: Box<EventId>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
use conduit_core::{err, Err};
|
||||
use conduit_core::{err, Err, Result};
|
||||
use ruma::{OwnedRoomId, OwnedUserId, RoomId, UserId};
|
||||
use service::user_is_local;
|
||||
|
||||
use crate::{services, Result};
|
||||
use service::Services;
|
||||
|
||||
pub(crate) fn escape_html(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
@@ -10,17 +8,17 @@ pub(crate) fn escape_html(s: &str) -> String {
|
||||
.replace('>', ">")
|
||||
}
|
||||
|
||||
pub(crate) fn get_room_info(id: &RoomId) -> (OwnedRoomId, u64, String) {
|
||||
pub(crate) fn get_room_info(services: &Services, id: &RoomId) -> (OwnedRoomId, u64, String) {
|
||||
(
|
||||
id.into(),
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_joined_count(id)
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or(0),
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.get_name(id)
|
||||
@@ -31,16 +29,16 @@ pub(crate) fn get_room_info(id: &RoomId) -> (OwnedRoomId, u64, String) {
|
||||
}
|
||||
|
||||
/// Parses user ID
|
||||
pub(crate) fn parse_user_id(user_id: &str) -> Result<OwnedUserId> {
|
||||
UserId::parse_with_server_name(user_id.to_lowercase(), services().globals.server_name())
|
||||
pub(crate) fn parse_user_id(services: &Services, user_id: &str) -> Result<OwnedUserId> {
|
||||
UserId::parse_with_server_name(user_id.to_lowercase(), services.globals.server_name())
|
||||
.map_err(|e| err!("The supplied username is not a valid username: {e}"))
|
||||
}
|
||||
|
||||
/// Parses user ID as our local user
|
||||
pub(crate) fn parse_local_user_id(user_id: &str) -> Result<OwnedUserId> {
|
||||
let user_id = parse_user_id(user_id)?;
|
||||
pub(crate) fn parse_local_user_id(services: &Services, user_id: &str) -> Result<OwnedUserId> {
|
||||
let user_id = parse_user_id(services, user_id)?;
|
||||
|
||||
if !user_is_local(&user_id) {
|
||||
if !services.globals.user_is_local(&user_id) {
|
||||
return Err!("User {user_id:?} does not belong to our server.");
|
||||
}
|
||||
|
||||
@@ -48,14 +46,14 @@ pub(crate) fn parse_local_user_id(user_id: &str) -> Result<OwnedUserId> {
|
||||
}
|
||||
|
||||
/// Parses user ID that is an active (not guest or deactivated) local user
|
||||
pub(crate) fn parse_active_local_user_id(user_id: &str) -> Result<OwnedUserId> {
|
||||
let user_id = parse_local_user_id(user_id)?;
|
||||
pub(crate) fn parse_active_local_user_id(services: &Services, user_id: &str) -> Result<OwnedUserId> {
|
||||
let user_id = parse_local_user_id(services, user_id)?;
|
||||
|
||||
if !services().users.exists(&user_id)? {
|
||||
if !services.users.exists(&user_id)? {
|
||||
return Err!("User {user_id:?} does not exist on this server.");
|
||||
}
|
||||
|
||||
if services().users.is_deactivated(&user_id)? {
|
||||
if services.users.is_deactivated(&user_id)? {
|
||||
return Err!("User {user_id:?} is deactivated.");
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,9 @@ release_max_log_level = [
|
||||
"log/max_level_trace",
|
||||
"log/release_max_level_info",
|
||||
]
|
||||
zstd_compression = [
|
||||
"reqwest/zstd",
|
||||
]
|
||||
gzip_compression = [
|
||||
"reqwest/gzip",
|
||||
]
|
||||
@@ -47,7 +50,6 @@ hmac.workspace = true
|
||||
http.workspace = true
|
||||
http-body-util.workspace = true
|
||||
hyper.workspace = true
|
||||
image.workspace = true
|
||||
ipaddress.workspace = true
|
||||
jsonwebtoken.workspace = true
|
||||
log.workspace = true
|
||||
@@ -60,7 +62,6 @@ serde.workspace = true
|
||||
sha-1.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
webpage.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use std::fmt::Write;
|
||||
|
||||
use axum::extract::State;
|
||||
use axum_client_ip::InsecureClientIp;
|
||||
use conduit::debug_info;
|
||||
use conduit::{debug_info, error, info, utils, warn, Error, Result};
|
||||
use register::RegistrationKind;
|
||||
use ruma::{
|
||||
api::client::{
|
||||
@@ -17,15 +18,9 @@
|
||||
events::{room::message::RoomMessageEventContent, GlobalAccountDataEventType},
|
||||
push, OwnedRoomId, UserId,
|
||||
};
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
use super::{join_room_by_id_helper, DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH};
|
||||
use crate::{
|
||||
service::user_is_local,
|
||||
services,
|
||||
utils::{self},
|
||||
Error, Result, Ruma,
|
||||
};
|
||||
use crate::Ruma;
|
||||
|
||||
const RANDOM_USER_ID_LENGTH: usize = 10;
|
||||
|
||||
@@ -42,20 +37,21 @@
|
||||
/// invalid when trying to register
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "register_available")]
|
||||
pub(crate) async fn get_register_available_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<get_username_availability::v3::Request>,
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_username_availability::v3::Request>,
|
||||
) -> Result<get_username_availability::v3::Response> {
|
||||
// Validate user id
|
||||
let user_id = UserId::parse_with_server_name(body.username.to_lowercase(), services().globals.server_name())
|
||||
let user_id = UserId::parse_with_server_name(body.username.to_lowercase(), services.globals.server_name())
|
||||
.ok()
|
||||
.filter(|user_id| !user_id.is_historical() && user_is_local(user_id))
|
||||
.filter(|user_id| !user_id.is_historical() && services.globals.user_is_local(user_id))
|
||||
.ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
|
||||
|
||||
// Check if username is creative enough
|
||||
if services().users.exists(&user_id)? {
|
||||
if services.users.exists(&user_id)? {
|
||||
return Err(Error::BadRequest(ErrorKind::UserInUse, "Desired user ID is already taken."));
|
||||
}
|
||||
|
||||
if services()
|
||||
if services
|
||||
.globals
|
||||
.forbidden_usernames()
|
||||
.is_match(user_id.localpart())
|
||||
@@ -91,9 +87,9 @@ pub(crate) async fn get_register_available_route(
|
||||
#[allow(clippy::doc_markdown)]
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "register")]
|
||||
pub(crate) async fn register_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<register::v3::Request>,
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp, body: Ruma<register::v3::Request>,
|
||||
) -> Result<register::v3::Response> {
|
||||
if !services().globals.allow_registration() && body.appservice_info.is_none() {
|
||||
if !services.globals.allow_registration() && body.appservice_info.is_none() {
|
||||
info!(
|
||||
"Registration disabled and request not from known appservice, rejecting registration attempt for username \
|
||||
{:?}",
|
||||
@@ -105,8 +101,8 @@ pub(crate) async fn register_route(
|
||||
let is_guest = body.kind == RegistrationKind::Guest;
|
||||
|
||||
if is_guest
|
||||
&& (!services().globals.allow_guest_registration()
|
||||
|| (services().globals.allow_registration() && services().globals.config.registration_token.is_some()))
|
||||
&& (!services.globals.allow_guest_registration()
|
||||
|| (services.globals.allow_registration() && services.globals.config.registration_token.is_some()))
|
||||
{
|
||||
info!(
|
||||
"Guest registration disabled / registration enabled with token configured, rejecting guest registration \
|
||||
@@ -121,7 +117,7 @@ pub(crate) async fn register_route(
|
||||
|
||||
// forbid guests from registering if there is not a real admin user yet. give
|
||||
// generic user error.
|
||||
if is_guest && services().users.count()? < 2 {
|
||||
if is_guest && services.users.count()? < 2 {
|
||||
warn!(
|
||||
"Guest account attempted to register before a real admin user has been registered, rejecting \
|
||||
registration. Guest's initial device name: {:?}",
|
||||
@@ -133,16 +129,16 @@ pub(crate) async fn register_route(
|
||||
let user_id = match (&body.username, is_guest) {
|
||||
(Some(username), false) => {
|
||||
let proposed_user_id =
|
||||
UserId::parse_with_server_name(username.to_lowercase(), services().globals.server_name())
|
||||
UserId::parse_with_server_name(username.to_lowercase(), services.globals.server_name())
|
||||
.ok()
|
||||
.filter(|user_id| !user_id.is_historical() && user_is_local(user_id))
|
||||
.filter(|user_id| !user_id.is_historical() && services.globals.user_is_local(user_id))
|
||||
.ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
|
||||
|
||||
if services().users.exists(&proposed_user_id)? {
|
||||
if services.users.exists(&proposed_user_id)? {
|
||||
return Err(Error::BadRequest(ErrorKind::UserInUse, "Desired user ID is already taken."));
|
||||
}
|
||||
|
||||
if services()
|
||||
if services
|
||||
.globals
|
||||
.forbidden_usernames()
|
||||
.is_match(proposed_user_id.localpart())
|
||||
@@ -155,10 +151,10 @@ pub(crate) async fn register_route(
|
||||
_ => loop {
|
||||
let proposed_user_id = UserId::parse_with_server_name(
|
||||
utils::random_string(RANDOM_USER_ID_LENGTH).to_lowercase(),
|
||||
services().globals.server_name(),
|
||||
services.globals.server_name(),
|
||||
)
|
||||
.unwrap();
|
||||
if !services().users.exists(&proposed_user_id)? {
|
||||
if !services.users.exists(&proposed_user_id)? {
|
||||
break proposed_user_id;
|
||||
}
|
||||
},
|
||||
@@ -172,13 +168,13 @@ pub(crate) async fn register_route(
|
||||
} else {
|
||||
return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing appservice token."));
|
||||
}
|
||||
} else if services().appservice.is_exclusive_user_id(&user_id).await {
|
||||
} else if services.appservice.is_exclusive_user_id(&user_id).await {
|
||||
return Err(Error::BadRequest(ErrorKind::Exclusive, "User ID reserved by appservice."));
|
||||
}
|
||||
|
||||
// UIAA
|
||||
let mut uiaainfo;
|
||||
let skip_auth = if services().globals.config.registration_token.is_some() {
|
||||
let skip_auth = if services.globals.config.registration_token.is_some() {
|
||||
// Registration token required
|
||||
uiaainfo = UiaaInfo {
|
||||
flows: vec![AuthFlow {
|
||||
@@ -206,8 +202,8 @@ pub(crate) async fn register_route(
|
||||
|
||||
if !skip_auth {
|
||||
if let Some(auth) = &body.auth {
|
||||
let (worked, uiaainfo) = services().uiaa.try_auth(
|
||||
&UserId::parse_with_server_name("", services().globals.server_name()).expect("we know this is valid"),
|
||||
let (worked, uiaainfo) = services.uiaa.try_auth(
|
||||
&UserId::parse_with_server_name("", services.globals.server_name()).expect("we know this is valid"),
|
||||
"".into(),
|
||||
auth,
|
||||
&uiaainfo,
|
||||
@@ -218,8 +214,8 @@ pub(crate) async fn register_route(
|
||||
// Success!
|
||||
} else if let Some(json) = body.json_body {
|
||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||
services().uiaa.create(
|
||||
&UserId::parse_with_server_name("", services().globals.server_name()).expect("we know this is valid"),
|
||||
services.uiaa.create(
|
||||
&UserId::parse_with_server_name("", services.globals.server_name()).expect("we know this is valid"),
|
||||
"".into(),
|
||||
&uiaainfo,
|
||||
&json,
|
||||
@@ -237,25 +233,25 @@ pub(crate) async fn register_route(
|
||||
};
|
||||
|
||||
// Create user
|
||||
services().users.create(&user_id, password)?;
|
||||
services.users.create(&user_id, password)?;
|
||||
|
||||
// Default to pretty displayname
|
||||
let mut displayname = user_id.localpart().to_owned();
|
||||
|
||||
// If `new_user_displayname_suffix` is set, registration will push whatever
|
||||
// content is set to the user's display name with a space before it
|
||||
if !services().globals.new_user_displayname_suffix().is_empty() {
|
||||
write!(displayname, " {}", services().globals.config.new_user_displayname_suffix)
|
||||
if !services.globals.new_user_displayname_suffix().is_empty() && body.appservice_info.is_none() {
|
||||
write!(displayname, " {}", services.globals.config.new_user_displayname_suffix)
|
||||
.expect("should be able to write to string buffer");
|
||||
}
|
||||
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.set_displayname(&user_id, Some(displayname.clone()))
|
||||
.await?;
|
||||
|
||||
// Initial account data
|
||||
services().account_data.update(
|
||||
services.account_data.update(
|
||||
None,
|
||||
&user_id,
|
||||
GlobalAccountDataEventType::PushRules.to_string().into(),
|
||||
@@ -290,16 +286,20 @@ pub(crate) async fn register_route(
|
||||
let token = utils::random_string(TOKEN_LENGTH);
|
||||
|
||||
// Create device for this account
|
||||
services()
|
||||
.users
|
||||
.create_device(&user_id, &device_id, &token, body.initial_device_display_name.clone())?;
|
||||
services.users.create_device(
|
||||
&user_id,
|
||||
&device_id,
|
||||
&token,
|
||||
body.initial_device_display_name.clone(),
|
||||
Some(client.to_string()),
|
||||
)?;
|
||||
|
||||
debug_info!(%user_id, %device_id, "User account was created");
|
||||
|
||||
// log in conduit admin channel if a non-guest user registered
|
||||
if body.appservice_info.is_none() && !is_guest {
|
||||
info!("New user \"{user_id}\" registered on this server.");
|
||||
services()
|
||||
services
|
||||
.admin
|
||||
.send_message(RoomMessageEventContent::notice_plain(format!(
|
||||
"New user \"{user_id}\" registered on this server from IP {client}."
|
||||
@@ -308,7 +308,7 @@ pub(crate) async fn register_route(
|
||||
}
|
||||
|
||||
// log in conduit admin channel if a guest registered
|
||||
if body.appservice_info.is_none() && is_guest && services().globals.log_guest_registrations() {
|
||||
if body.appservice_info.is_none() && is_guest && services.globals.log_guest_registrations() {
|
||||
info!("New guest user \"{user_id}\" registered on this server.");
|
||||
|
||||
if let Some(device_display_name) = &body.initial_device_display_name {
|
||||
@@ -317,7 +317,7 @@ pub(crate) async fn register_route(
|
||||
.as_ref()
|
||||
.is_some_and(|device_display_name| !device_display_name.is_empty())
|
||||
{
|
||||
services()
|
||||
services
|
||||
.admin
|
||||
.send_message(RoomMessageEventContent::notice_plain(format!(
|
||||
"Guest user \"{user_id}\" with device display name `{device_display_name}` registered on this \
|
||||
@@ -325,7 +325,7 @@ pub(crate) async fn register_route(
|
||||
)))
|
||||
.await;
|
||||
} else {
|
||||
services()
|
||||
services
|
||||
.admin
|
||||
.send_message(RoomMessageEventContent::notice_plain(format!(
|
||||
"Guest user \"{user_id}\" with no device display name registered on this server from IP \
|
||||
@@ -334,7 +334,7 @@ pub(crate) async fn register_route(
|
||||
.await;
|
||||
}
|
||||
} else {
|
||||
services()
|
||||
services
|
||||
.admin
|
||||
.send_message(RoomMessageEventContent::notice_plain(format!(
|
||||
"Guest user \"{user_id}\" with no device display name registered on this server from IP {client}.",
|
||||
@@ -346,14 +346,12 @@ pub(crate) async fn register_route(
|
||||
// If this is the first real user, grant them admin privileges except for guest
|
||||
// users Note: the server user, @conduit:servername, is generated first
|
||||
if !is_guest {
|
||||
if let Some(admin_room) = service::admin::Service::get_admin_room()? {
|
||||
if services()
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_joined_count(&admin_room)?
|
||||
== Some(1)
|
||||
{
|
||||
service::admin::make_user_admin(&user_id, displayname).await?;
|
||||
if let Some(admin_room) = services.admin.get_admin_room()? {
|
||||
if services.rooms.state_cache.room_joined_count(&admin_room)? == Some(1) {
|
||||
services
|
||||
.admin
|
||||
.make_user_admin(&user_id, displayname)
|
||||
.await?;
|
||||
|
||||
warn!("Granting {user_id} admin privileges as the first user");
|
||||
}
|
||||
@@ -361,14 +359,14 @@ pub(crate) async fn register_route(
|
||||
}
|
||||
|
||||
if body.appservice_info.is_none()
|
||||
&& !services().globals.config.auto_join_rooms.is_empty()
|
||||
&& (services().globals.allow_guests_auto_join_rooms() || !is_guest)
|
||||
&& !services.globals.config.auto_join_rooms.is_empty()
|
||||
&& (services.globals.allow_guests_auto_join_rooms() || !is_guest)
|
||||
{
|
||||
for room in &services().globals.config.auto_join_rooms {
|
||||
if !services()
|
||||
for room in &services.globals.config.auto_join_rooms {
|
||||
if !services
|
||||
.rooms
|
||||
.state_cache
|
||||
.server_in_room(services().globals.server_name(), room)?
|
||||
.server_in_room(services.globals.server_name(), room)?
|
||||
{
|
||||
warn!("Skipping room {room} to automatically join as we have never joined before.");
|
||||
continue;
|
||||
@@ -376,10 +374,11 @@ pub(crate) async fn register_route(
|
||||
|
||||
if let Some(room_id_server_name) = room.server_name() {
|
||||
if let Err(e) = join_room_by_id_helper(
|
||||
&services,
|
||||
&user_id,
|
||||
room,
|
||||
Some("Automatically joining this room upon registration".to_owned()),
|
||||
&[room_id_server_name.to_owned(), services().globals.server_name().to_owned()],
|
||||
&[room_id_server_name.to_owned(), services.globals.server_name().to_owned()],
|
||||
None,
|
||||
)
|
||||
.await
|
||||
@@ -421,7 +420,8 @@ pub(crate) async fn register_route(
|
||||
/// - Triggers device list updates
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "change_password")]
|
||||
pub(crate) async fn change_password_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<change_password::v3::Request>,
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<change_password::v3::Request>,
|
||||
) -> Result<change_password::v3::Response> {
|
||||
// Authentication for this endpoint was made optional, but we need
|
||||
// authentication currently
|
||||
@@ -442,7 +442,7 @@ pub(crate) async fn change_password_route(
|
||||
};
|
||||
|
||||
if let Some(auth) = &body.auth {
|
||||
let (worked, uiaainfo) = services()
|
||||
let (worked, uiaainfo) = services
|
||||
.uiaa
|
||||
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
|
||||
if !worked {
|
||||
@@ -451,7 +451,7 @@ pub(crate) async fn change_password_route(
|
||||
// Success!
|
||||
} else if let Some(json) = body.json_body {
|
||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||
services()
|
||||
services
|
||||
.uiaa
|
||||
.create(sender_user, sender_device, &uiaainfo, &json)?;
|
||||
return Err(Error::Uiaa(uiaainfo));
|
||||
@@ -459,24 +459,24 @@ pub(crate) async fn change_password_route(
|
||||
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
|
||||
}
|
||||
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.set_password(sender_user, Some(&body.new_password))?;
|
||||
|
||||
if body.logout_devices {
|
||||
// Logout all devices except the current one
|
||||
for id in services()
|
||||
for id in services
|
||||
.users
|
||||
.all_device_ids(sender_user)
|
||||
.filter_map(Result::ok)
|
||||
.filter(|id| id != sender_device)
|
||||
{
|
||||
services().users.remove_device(sender_user, &id)?;
|
||||
services.users.remove_device(sender_user, &id)?;
|
||||
}
|
||||
}
|
||||
|
||||
info!("User {sender_user} changed their password.");
|
||||
services()
|
||||
services
|
||||
.admin
|
||||
.send_message(RoomMessageEventContent::notice_plain(format!(
|
||||
"User {sender_user} changed their password."
|
||||
@@ -491,14 +491,16 @@ pub(crate) async fn change_password_route(
|
||||
/// Get `user_id` of the sender user.
|
||||
///
|
||||
/// Note: Also works for Application Services
|
||||
pub(crate) async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoami::v3::Response> {
|
||||
pub(crate) async fn whoami_route(
|
||||
State(services): State<crate::State>, body: Ruma<whoami::v3::Request>,
|
||||
) -> Result<whoami::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let device_id = body.sender_device.clone();
|
||||
|
||||
Ok(whoami::v3::Response {
|
||||
user_id: sender_user.clone(),
|
||||
device_id,
|
||||
is_guest: services().users.is_deactivated(sender_user)? && body.appservice_info.is_none(),
|
||||
is_guest: services.users.is_deactivated(sender_user)? && body.appservice_info.is_none(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -515,7 +517,8 @@ pub(crate) async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoa
|
||||
/// - Removes ability to log in again
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "deactivate")]
|
||||
pub(crate) async fn deactivate_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<deactivate::v3::Request>,
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<deactivate::v3::Request>,
|
||||
) -> Result<deactivate::v3::Response> {
|
||||
// Authentication for this endpoint was made optional, but we need
|
||||
// authentication currently
|
||||
@@ -536,7 +539,7 @@ pub(crate) async fn deactivate_route(
|
||||
};
|
||||
|
||||
if let Some(auth) = &body.auth {
|
||||
let (worked, uiaainfo) = services()
|
||||
let (worked, uiaainfo) = services
|
||||
.uiaa
|
||||
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
|
||||
if !worked {
|
||||
@@ -545,7 +548,7 @@ pub(crate) async fn deactivate_route(
|
||||
// Success!
|
||||
} else if let Some(json) = body.json_body {
|
||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||
services()
|
||||
services
|
||||
.uiaa
|
||||
.create(sender_user, sender_device, &uiaainfo, &json)?;
|
||||
return Err(Error::Uiaa(uiaainfo));
|
||||
@@ -554,23 +557,23 @@ pub(crate) async fn deactivate_route(
|
||||
}
|
||||
|
||||
// Remove devices and mark account as deactivated
|
||||
services().users.deactivate_account(sender_user)?;
|
||||
services.users.deactivate_account(sender_user)?;
|
||||
|
||||
// Remove profile pictures and display name
|
||||
let all_joined_rooms: Vec<OwnedRoomId> = services()
|
||||
let all_joined_rooms: Vec<OwnedRoomId> = services
|
||||
.rooms
|
||||
.state_cache
|
||||
.rooms_joined(sender_user)
|
||||
.filter_map(Result::ok)
|
||||
.collect();
|
||||
super::update_displayname(sender_user.clone(), None, all_joined_rooms.clone()).await?;
|
||||
super::update_avatar_url(sender_user.clone(), None, None, all_joined_rooms).await?;
|
||||
super::update_displayname(&services, sender_user.clone(), None, all_joined_rooms.clone()).await?;
|
||||
super::update_avatar_url(&services, sender_user.clone(), None, None, all_joined_rooms).await?;
|
||||
|
||||
// Make the user leave all rooms before deactivation
|
||||
super::leave_all_rooms(sender_user).await;
|
||||
super::leave_all_rooms(&services, sender_user).await;
|
||||
|
||||
info!("User {sender_user} deactivated their account.");
|
||||
services()
|
||||
services
|
||||
.admin
|
||||
.send_message(RoomMessageEventContent::notice_plain(format!(
|
||||
"User {sender_user} deactivated their account."
|
||||
@@ -632,9 +635,9 @@ pub(crate) async fn request_3pid_management_token_via_msisdn_route(
|
||||
/// Currently does not have any ratelimiting, and this isn't very practical as
|
||||
/// there is only one registration token allowed.
|
||||
pub(crate) async fn check_registration_token_validity(
|
||||
body: Ruma<check_registration_token_validity::v1::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<check_registration_token_validity::v1::Request>,
|
||||
) -> Result<check_registration_token_validity::v1::Response> {
|
||||
let Some(reg_token) = services().globals.config.registration_token.clone() else {
|
||||
let Some(reg_token) = services.globals.config.registration_token.clone() else {
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::forbidden(),
|
||||
"Server does not allow token registration.",
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use axum::extract::State;
|
||||
use conduit::{debug, Error, Result};
|
||||
use rand::seq::SliceRandom;
|
||||
use ruma::{
|
||||
api::client::{
|
||||
@@ -6,21 +8,27 @@
|
||||
},
|
||||
OwnedServerName, RoomAliasId, RoomId,
|
||||
};
|
||||
use tracing::debug;
|
||||
use service::Services;
|
||||
|
||||
use crate::{service::server_is_ours, services, Error, Result, Ruma};
|
||||
use crate::Ruma;
|
||||
|
||||
/// # `PUT /_matrix/client/v3/directory/room/{roomAlias}`
|
||||
///
|
||||
/// Creates a new room alias on this server.
|
||||
pub(crate) async fn create_alias_route(body: Ruma<create_alias::v3::Request>) -> Result<create_alias::v3::Response> {
|
||||
pub(crate) async fn create_alias_route(
|
||||
State(services): State<crate::State>, body: Ruma<create_alias::v3::Request>,
|
||||
) -> Result<create_alias::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
service::rooms::alias::appservice_checks(&body.room_alias, &body.appservice_info).await?;
|
||||
services
|
||||
.rooms
|
||||
.alias
|
||||
.appservice_checks(&body.room_alias, &body.appservice_info)
|
||||
.await?;
|
||||
|
||||
// this isn't apart of alias_checks or delete alias route because we should
|
||||
// allow removing forbidden room aliases
|
||||
if services()
|
||||
if services
|
||||
.globals
|
||||
.forbidden_alias_names()
|
||||
.is_match(body.room_alias.alias())
|
||||
@@ -28,7 +36,7 @@ pub(crate) async fn create_alias_route(body: Ruma<create_alias::v3::Request>) ->
|
||||
return Err(Error::BadRequest(ErrorKind::forbidden(), "Room alias is forbidden."));
|
||||
}
|
||||
|
||||
if services()
|
||||
if services
|
||||
.rooms
|
||||
.alias
|
||||
.resolve_local_alias(&body.room_alias)?
|
||||
@@ -37,7 +45,7 @@ pub(crate) async fn create_alias_route(body: Ruma<create_alias::v3::Request>) ->
|
||||
return Err(Error::Conflict("Alias already exists."));
|
||||
}
|
||||
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.alias
|
||||
.set_alias(&body.room_alias, &body.room_id, sender_user)?;
|
||||
@@ -50,21 +58,18 @@ pub(crate) async fn create_alias_route(body: Ruma<create_alias::v3::Request>) ->
|
||||
/// Deletes a room alias from this server.
|
||||
///
|
||||
/// - TODO: Update canonical alias event
|
||||
pub(crate) async fn delete_alias_route(body: Ruma<delete_alias::v3::Request>) -> Result<delete_alias::v3::Response> {
|
||||
pub(crate) async fn delete_alias_route(
|
||||
State(services): State<crate::State>, body: Ruma<delete_alias::v3::Request>,
|
||||
) -> Result<delete_alias::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
service::rooms::alias::appservice_checks(&body.room_alias, &body.appservice_info).await?;
|
||||
|
||||
if services()
|
||||
services
|
||||
.rooms
|
||||
.alias
|
||||
.resolve_local_alias(&body.room_alias)?
|
||||
.is_none()
|
||||
{
|
||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Alias does not exist."));
|
||||
}
|
||||
.appservice_checks(&body.room_alias, &body.appservice_info)
|
||||
.await?;
|
||||
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.alias
|
||||
.remove_alias(&body.room_alias, sender_user)
|
||||
@@ -78,11 +83,13 @@ pub(crate) async fn delete_alias_route(body: Ruma<delete_alias::v3::Request>) ->
|
||||
/// # `GET /_matrix/client/v3/directory/room/{roomAlias}`
|
||||
///
|
||||
/// Resolve an alias locally or over federation.
|
||||
pub(crate) async fn get_alias_route(body: Ruma<get_alias::v3::Request>) -> Result<get_alias::v3::Response> {
|
||||
pub(crate) async fn get_alias_route(
|
||||
State(services): State<crate::State>, body: Ruma<get_alias::v3::Request>,
|
||||
) -> Result<get_alias::v3::Response> {
|
||||
let room_alias = body.body.room_alias;
|
||||
let servers = None;
|
||||
|
||||
let Ok((room_id, pre_servers)) = services()
|
||||
let Ok((room_id, pre_servers)) = services
|
||||
.rooms
|
||||
.alias
|
||||
.resolve_alias(&room_alias, servers.as_ref())
|
||||
@@ -91,17 +98,17 @@ pub(crate) async fn get_alias_route(body: Ruma<get_alias::v3::Request>) -> Resul
|
||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Room with alias not found."));
|
||||
};
|
||||
|
||||
let servers = room_available_servers(&room_id, &room_alias, &pre_servers);
|
||||
let servers = room_available_servers(&services, &room_id, &room_alias, &pre_servers);
|
||||
debug!(?room_alias, ?room_id, "available servers: {servers:?}");
|
||||
|
||||
Ok(get_alias::v3::Response::new(room_id, servers))
|
||||
}
|
||||
|
||||
fn room_available_servers(
|
||||
room_id: &RoomId, room_alias: &RoomAliasId, pre_servers: &Option<Vec<OwnedServerName>>,
|
||||
services: &Services, room_id: &RoomId, room_alias: &RoomAliasId, pre_servers: &Option<Vec<OwnedServerName>>,
|
||||
) -> Vec<OwnedServerName> {
|
||||
// find active servers in room state cache to suggest
|
||||
let mut servers: Vec<OwnedServerName> = services()
|
||||
let mut servers: Vec<OwnedServerName> = services
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_servers(room_id)
|
||||
@@ -124,10 +131,10 @@ fn room_available_servers(
|
||||
// prefer the room alias server first
|
||||
if let Some(server_index) = servers
|
||||
.iter()
|
||||
.position(|server_name| server_is_ours(server_name))
|
||||
.position(|server_name| services.globals.server_is_ours(server_name))
|
||||
{
|
||||
servers.swap_remove(server_index);
|
||||
servers.insert(0, services().globals.server_name().to_owned());
|
||||
servers.insert(0, services.globals.server_name().to_owned());
|
||||
} else if let Some(alias_server_index) = servers
|
||||
.iter()
|
||||
.position(|server| server == room_alias.server_name())
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use axum::extract::State;
|
||||
use ruma::{
|
||||
api::client::{
|
||||
backup::{
|
||||
@@ -11,16 +12,16 @@
|
||||
UInt,
|
||||
};
|
||||
|
||||
use crate::{services, Error, Result, Ruma};
|
||||
use crate::{Error, Result, Ruma};
|
||||
|
||||
/// # `POST /_matrix/client/r0/room_keys/version`
|
||||
///
|
||||
/// Creates a new backup.
|
||||
pub(crate) async fn create_backup_version_route(
|
||||
body: Ruma<create_backup_version::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<create_backup_version::v3::Request>,
|
||||
) -> Result<create_backup_version::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let version = services()
|
||||
let version = services
|
||||
.key_backups
|
||||
.create_backup(sender_user, &body.algorithm)?;
|
||||
|
||||
@@ -34,10 +35,10 @@ pub(crate) async fn create_backup_version_route(
|
||||
/// Update information about an existing backup. Only `auth_data` can be
|
||||
/// modified.
|
||||
pub(crate) async fn update_backup_version_route(
|
||||
body: Ruma<update_backup_version::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<update_backup_version::v3::Request>,
|
||||
) -> Result<update_backup_version::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.update_backup(sender_user, &body.version, &body.algorithm)?;
|
||||
|
||||
@@ -48,20 +49,20 @@ pub(crate) async fn update_backup_version_route(
|
||||
///
|
||||
/// Get information about the latest backup version.
|
||||
pub(crate) async fn get_latest_backup_info_route(
|
||||
body: Ruma<get_latest_backup_info::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_latest_backup_info::v3::Request>,
|
||||
) -> Result<get_latest_backup_info::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let (version, algorithm) = services()
|
||||
let (version, algorithm) = services
|
||||
.key_backups
|
||||
.get_latest_backup(sender_user)?
|
||||
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Key backup does not exist."))?;
|
||||
|
||||
Ok(get_latest_backup_info::v3::Response {
|
||||
algorithm,
|
||||
count: (UInt::try_from(services().key_backups.count_keys(sender_user, &version)?)
|
||||
count: (UInt::try_from(services.key_backups.count_keys(sender_user, &version)?)
|
||||
.expect("user backup keys count should not be that high")),
|
||||
etag: services().key_backups.get_etag(sender_user, &version)?,
|
||||
etag: services.key_backups.get_etag(sender_user, &version)?,
|
||||
version,
|
||||
})
|
||||
}
|
||||
@@ -70,10 +71,10 @@ pub(crate) async fn get_latest_backup_info_route(
|
||||
///
|
||||
/// Get information about an existing backup.
|
||||
pub(crate) async fn get_backup_info_route(
|
||||
body: Ruma<get_backup_info::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_backup_info::v3::Request>,
|
||||
) -> Result<get_backup_info::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let algorithm = services()
|
||||
let algorithm = services
|
||||
.key_backups
|
||||
.get_backup(sender_user, &body.version)?
|
||||
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Key backup does not exist."))?;
|
||||
@@ -81,14 +82,12 @@ pub(crate) async fn get_backup_info_route(
|
||||
Ok(get_backup_info::v3::Response {
|
||||
algorithm,
|
||||
count: (UInt::try_from(
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.count_keys(sender_user, &body.version)?,
|
||||
)
|
||||
.expect("user backup keys count should not be that high")),
|
||||
etag: services()
|
||||
.key_backups
|
||||
.get_etag(sender_user, &body.version)?,
|
||||
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||
version: body.version.clone(),
|
||||
})
|
||||
}
|
||||
@@ -100,11 +99,11 @@ pub(crate) async fn get_backup_info_route(
|
||||
/// - Deletes both information about the backup, as well as all key data related
|
||||
/// to the backup
|
||||
pub(crate) async fn delete_backup_version_route(
|
||||
body: Ruma<delete_backup_version::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<delete_backup_version::v3::Request>,
|
||||
) -> Result<delete_backup_version::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.delete_backup(sender_user, &body.version)?;
|
||||
|
||||
@@ -120,12 +119,12 @@ pub(crate) async fn delete_backup_version_route(
|
||||
/// - Adds the keys to the backup
|
||||
/// - Returns the new number of keys in this backup and the etag
|
||||
pub(crate) async fn add_backup_keys_route(
|
||||
body: Ruma<add_backup_keys::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<add_backup_keys::v3::Request>,
|
||||
) -> Result<add_backup_keys::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
if Some(&body.version)
|
||||
!= services()
|
||||
!= services
|
||||
.key_backups
|
||||
.get_latest_backup_version(sender_user)?
|
||||
.as_ref()
|
||||
@@ -138,7 +137,7 @@ pub(crate) async fn add_backup_keys_route(
|
||||
|
||||
for (room_id, room) in &body.rooms {
|
||||
for (session_id, key_data) in &room.sessions {
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.add_key(sender_user, &body.version, room_id, session_id, key_data)?;
|
||||
}
|
||||
@@ -146,14 +145,12 @@ pub(crate) async fn add_backup_keys_route(
|
||||
|
||||
Ok(add_backup_keys::v3::Response {
|
||||
count: (UInt::try_from(
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.count_keys(sender_user, &body.version)?,
|
||||
)
|
||||
.expect("user backup keys count should not be that high")),
|
||||
etag: services()
|
||||
.key_backups
|
||||
.get_etag(sender_user, &body.version)?,
|
||||
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -166,12 +163,12 @@ pub(crate) async fn add_backup_keys_route(
|
||||
/// - Adds the keys to the backup
|
||||
/// - Returns the new number of keys in this backup and the etag
|
||||
pub(crate) async fn add_backup_keys_for_room_route(
|
||||
body: Ruma<add_backup_keys_for_room::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<add_backup_keys_for_room::v3::Request>,
|
||||
) -> Result<add_backup_keys_for_room::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
if Some(&body.version)
|
||||
!= services()
|
||||
!= services
|
||||
.key_backups
|
||||
.get_latest_backup_version(sender_user)?
|
||||
.as_ref()
|
||||
@@ -183,21 +180,19 @@ pub(crate) async fn add_backup_keys_for_room_route(
|
||||
}
|
||||
|
||||
for (session_id, key_data) in &body.sessions {
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.add_key(sender_user, &body.version, &body.room_id, session_id, key_data)?;
|
||||
}
|
||||
|
||||
Ok(add_backup_keys_for_room::v3::Response {
|
||||
count: (UInt::try_from(
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.count_keys(sender_user, &body.version)?,
|
||||
)
|
||||
.expect("user backup keys count should not be that high")),
|
||||
etag: services()
|
||||
.key_backups
|
||||
.get_etag(sender_user, &body.version)?,
|
||||
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -210,12 +205,12 @@ pub(crate) async fn add_backup_keys_for_room_route(
|
||||
/// - Adds the keys to the backup
|
||||
/// - Returns the new number of keys in this backup and the etag
|
||||
pub(crate) async fn add_backup_keys_for_session_route(
|
||||
body: Ruma<add_backup_keys_for_session::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<add_backup_keys_for_session::v3::Request>,
|
||||
) -> Result<add_backup_keys_for_session::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
if Some(&body.version)
|
||||
!= services()
|
||||
!= services
|
||||
.key_backups
|
||||
.get_latest_backup_version(sender_user)?
|
||||
.as_ref()
|
||||
@@ -226,20 +221,18 @@ pub(crate) async fn add_backup_keys_for_session_route(
|
||||
));
|
||||
}
|
||||
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.add_key(sender_user, &body.version, &body.room_id, &body.session_id, &body.session_data)?;
|
||||
|
||||
Ok(add_backup_keys_for_session::v3::Response {
|
||||
count: (UInt::try_from(
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.count_keys(sender_user, &body.version)?,
|
||||
)
|
||||
.expect("user backup keys count should not be that high")),
|
||||
etag: services()
|
||||
.key_backups
|
||||
.get_etag(sender_user, &body.version)?,
|
||||
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -247,11 +240,11 @@ pub(crate) async fn add_backup_keys_for_session_route(
|
||||
///
|
||||
/// Retrieves all keys from the backup.
|
||||
pub(crate) async fn get_backup_keys_route(
|
||||
body: Ruma<get_backup_keys::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_backup_keys::v3::Request>,
|
||||
) -> Result<get_backup_keys::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let rooms = services().key_backups.get_all(sender_user, &body.version)?;
|
||||
let rooms = services.key_backups.get_all(sender_user, &body.version)?;
|
||||
|
||||
Ok(get_backup_keys::v3::Response {
|
||||
rooms,
|
||||
@@ -262,11 +255,11 @@ pub(crate) async fn get_backup_keys_route(
|
||||
///
|
||||
/// Retrieves all keys from the backup for a given room.
|
||||
pub(crate) async fn get_backup_keys_for_room_route(
|
||||
body: Ruma<get_backup_keys_for_room::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_backup_keys_for_room::v3::Request>,
|
||||
) -> Result<get_backup_keys_for_room::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let sessions = services()
|
||||
let sessions = services
|
||||
.key_backups
|
||||
.get_room(sender_user, &body.version, &body.room_id)?;
|
||||
|
||||
@@ -279,11 +272,11 @@ pub(crate) async fn get_backup_keys_for_room_route(
|
||||
///
|
||||
/// Retrieves a key from the backup.
|
||||
pub(crate) async fn get_backup_keys_for_session_route(
|
||||
body: Ruma<get_backup_keys_for_session::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_backup_keys_for_session::v3::Request>,
|
||||
) -> Result<get_backup_keys_for_session::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let key_data = services()
|
||||
let key_data = services
|
||||
.key_backups
|
||||
.get_session(sender_user, &body.version, &body.room_id, &body.session_id)?
|
||||
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Backup key not found for this user's session."))?;
|
||||
@@ -297,24 +290,22 @@ pub(crate) async fn get_backup_keys_for_session_route(
|
||||
///
|
||||
/// Delete the keys from the backup.
|
||||
pub(crate) async fn delete_backup_keys_route(
|
||||
body: Ruma<delete_backup_keys::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<delete_backup_keys::v3::Request>,
|
||||
) -> Result<delete_backup_keys::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.delete_all_keys(sender_user, &body.version)?;
|
||||
|
||||
Ok(delete_backup_keys::v3::Response {
|
||||
count: (UInt::try_from(
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.count_keys(sender_user, &body.version)?,
|
||||
)
|
||||
.expect("user backup keys count should not be that high")),
|
||||
etag: services()
|
||||
.key_backups
|
||||
.get_etag(sender_user, &body.version)?,
|
||||
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -322,24 +313,22 @@ pub(crate) async fn delete_backup_keys_route(
|
||||
///
|
||||
/// Delete the keys from the backup for a given room.
|
||||
pub(crate) async fn delete_backup_keys_for_room_route(
|
||||
body: Ruma<delete_backup_keys_for_room::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<delete_backup_keys_for_room::v3::Request>,
|
||||
) -> Result<delete_backup_keys_for_room::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.delete_room_keys(sender_user, &body.version, &body.room_id)?;
|
||||
|
||||
Ok(delete_backup_keys_for_room::v3::Response {
|
||||
count: (UInt::try_from(
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.count_keys(sender_user, &body.version)?,
|
||||
)
|
||||
.expect("user backup keys count should not be that high")),
|
||||
etag: services()
|
||||
.key_backups
|
||||
.get_etag(sender_user, &body.version)?,
|
||||
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -347,23 +336,21 @@ pub(crate) async fn delete_backup_keys_for_room_route(
|
||||
///
|
||||
/// Delete a key from the backup.
|
||||
pub(crate) async fn delete_backup_keys_for_session_route(
|
||||
body: Ruma<delete_backup_keys_for_session::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<delete_backup_keys_for_session::v3::Request>,
|
||||
) -> Result<delete_backup_keys_for_session::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.delete_room_key(sender_user, &body.version, &body.room_id, &body.session_id)?;
|
||||
|
||||
Ok(delete_backup_keys_for_session::v3::Response {
|
||||
count: (UInt::try_from(
|
||||
services()
|
||||
services
|
||||
.key_backups
|
||||
.count_keys(sender_user, &body.version)?,
|
||||
)
|
||||
.expect("user backup keys count should not be that high")),
|
||||
etag: services()
|
||||
.key_backups
|
||||
.get_etag(sender_user, &body.version)?,
|
||||
etag: services.key_backups.get_etag(sender_user, &body.version)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,29 +1,30 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use axum::extract::State;
|
||||
use ruma::api::client::discovery::get_capabilities::{
|
||||
self, Capabilities, RoomVersionStability, RoomVersionsCapability, ThirdPartyIdChangesCapability,
|
||||
};
|
||||
|
||||
use crate::{services, Result, Ruma};
|
||||
use crate::{Result, Ruma};
|
||||
|
||||
/// # `GET /_matrix/client/v3/capabilities`
|
||||
///
|
||||
/// Get information on the supported feature set and other relevent capabilities
|
||||
/// of this server.
|
||||
pub(crate) async fn get_capabilities_route(
|
||||
_body: Ruma<get_capabilities::v3::Request>,
|
||||
State(services): State<crate::State>, _body: Ruma<get_capabilities::v3::Request>,
|
||||
) -> Result<get_capabilities::v3::Response> {
|
||||
let mut available = BTreeMap::new();
|
||||
for room_version in &services().globals.unstable_room_versions {
|
||||
for room_version in &services.globals.unstable_room_versions {
|
||||
available.insert(room_version.clone(), RoomVersionStability::Unstable);
|
||||
}
|
||||
for room_version in &services().globals.stable_room_versions {
|
||||
for room_version in &services.globals.stable_room_versions {
|
||||
available.insert(room_version.clone(), RoomVersionStability::Stable);
|
||||
}
|
||||
|
||||
let mut capabilities = Capabilities::default();
|
||||
capabilities.room_versions = RoomVersionsCapability {
|
||||
default: services().globals.default_room_version(),
|
||||
default: services.globals.default_room_version(),
|
||||
available,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use axum::extract::State;
|
||||
use ruma::{
|
||||
api::client::{
|
||||
config::{get_global_account_data, get_room_account_data, set_global_account_data, set_room_account_data},
|
||||
@@ -10,15 +11,21 @@
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, value::RawValue as RawJsonValue};
|
||||
|
||||
use crate::{services, Error, Result, Ruma};
|
||||
use crate::{service::Services, Error, Result, Ruma};
|
||||
|
||||
/// # `PUT /_matrix/client/r0/user/{userId}/account_data/{type}`
|
||||
///
|
||||
/// Sets some account data for the sender user.
|
||||
pub(crate) async fn set_global_account_data_route(
|
||||
body: Ruma<set_global_account_data::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<set_global_account_data::v3::Request>,
|
||||
) -> Result<set_global_account_data::v3::Response> {
|
||||
set_account_data(None, &body.sender_user, &body.event_type.to_string(), body.data.json())?;
|
||||
set_account_data(
|
||||
&services,
|
||||
None,
|
||||
&body.sender_user,
|
||||
&body.event_type.to_string(),
|
||||
body.data.json(),
|
||||
)?;
|
||||
|
||||
Ok(set_global_account_data::v3::Response {})
|
||||
}
|
||||
@@ -27,9 +34,10 @@ pub(crate) async fn set_global_account_data_route(
|
||||
///
|
||||
/// Sets some room account data for the sender user.
|
||||
pub(crate) async fn set_room_account_data_route(
|
||||
body: Ruma<set_room_account_data::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<set_room_account_data::v3::Request>,
|
||||
) -> Result<set_room_account_data::v3::Response> {
|
||||
set_account_data(
|
||||
&services,
|
||||
Some(&body.room_id),
|
||||
&body.sender_user,
|
||||
&body.event_type.to_string(),
|
||||
@@ -43,11 +51,11 @@ pub(crate) async fn set_room_account_data_route(
|
||||
///
|
||||
/// Gets some account data for the sender user.
|
||||
pub(crate) async fn get_global_account_data_route(
|
||||
body: Ruma<get_global_account_data::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_global_account_data::v3::Request>,
|
||||
) -> Result<get_global_account_data::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let event: Box<RawJsonValue> = services()
|
||||
let event: Box<RawJsonValue> = services
|
||||
.account_data
|
||||
.get(None, sender_user, body.event_type.to_string().into())?
|
||||
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
|
||||
@@ -65,11 +73,11 @@ pub(crate) async fn get_global_account_data_route(
|
||||
///
|
||||
/// Gets some room account data for the sender user.
|
||||
pub(crate) async fn get_room_account_data_route(
|
||||
body: Ruma<get_room_account_data::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_room_account_data::v3::Request>,
|
||||
) -> Result<get_room_account_data::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let event: Box<RawJsonValue> = services()
|
||||
let event: Box<RawJsonValue> = services
|
||||
.account_data
|
||||
.get(Some(&body.room_id), sender_user, body.event_type.clone())?
|
||||
.ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
|
||||
@@ -84,14 +92,15 @@ pub(crate) async fn get_room_account_data_route(
|
||||
}
|
||||
|
||||
fn set_account_data(
|
||||
room_id: Option<&RoomId>, sender_user: &Option<OwnedUserId>, event_type: &str, data: &RawJsonValue,
|
||||
services: &Services, room_id: Option<&RoomId>, sender_user: &Option<OwnedUserId>, event_type: &str,
|
||||
data: &RawJsonValue,
|
||||
) -> Result<()> {
|
||||
let sender_user = sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let data: serde_json::Value =
|
||||
serde_json::from_str(data.get()).map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Data is invalid."))?;
|
||||
|
||||
services().account_data.update(
|
||||
services.account_data.update(
|
||||
room_id,
|
||||
sender_user,
|
||||
event_type.into(),
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use axum::extract::State;
|
||||
use ruma::{
|
||||
api::client::{context::get_context, error::ErrorKind, filter::LazyLoadOptions},
|
||||
events::StateEventType,
|
||||
};
|
||||
use tracing::error;
|
||||
|
||||
use crate::{services, Error, Result, Ruma};
|
||||
use crate::{Error, Result, Ruma};
|
||||
|
||||
/// # `GET /_matrix/client/r0/rooms/{roomId}/context`
|
||||
///
|
||||
@@ -14,26 +15,30 @@
|
||||
///
|
||||
/// - Only works if the user is joined (TODO: always allow, but only show events
|
||||
/// if the user was joined, depending on history_visibility)
|
||||
pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<get_context::v3::Response> {
|
||||
pub(crate) async fn get_context_route(
|
||||
State(services): State<crate::State>, body: Ruma<get_context::v3::Request>,
|
||||
) -> Result<get_context::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
|
||||
|
||||
// some clients, at least element, seem to require knowledge of redundant
|
||||
// members for "inline" profiles on the timeline to work properly
|
||||
let (lazy_load_enabled, lazy_load_send_redundant) = match &body.filter.lazy_load_options {
|
||||
LazyLoadOptions::Enabled {
|
||||
include_redundant_members,
|
||||
} => (true, *include_redundant_members),
|
||||
LazyLoadOptions::Disabled => (false, false),
|
||||
LazyLoadOptions::Disabled => (false, cfg!(feature = "element_hacks")),
|
||||
};
|
||||
|
||||
let mut lazy_loaded = HashSet::new();
|
||||
|
||||
let base_token = services()
|
||||
let base_token = services
|
||||
.rooms
|
||||
.timeline
|
||||
.get_pdu_count(&body.event_id)?
|
||||
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Base event id not found."))?;
|
||||
|
||||
let base_event = services()
|
||||
let base_event = services
|
||||
.rooms
|
||||
.timeline
|
||||
.get_pdu(&body.event_id)?
|
||||
@@ -41,7 +46,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
||||
|
||||
let room_id = base_event.room_id.clone();
|
||||
|
||||
if !services()
|
||||
if !services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.user_can_see_event(sender_user, &room_id, &body.event_id)?
|
||||
@@ -52,7 +57,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
||||
));
|
||||
}
|
||||
|
||||
if !services().rooms.lazy_loading.lazy_load_was_sent_before(
|
||||
if !services.rooms.lazy_loading.lazy_load_was_sent_before(
|
||||
sender_user,
|
||||
sender_device,
|
||||
&room_id,
|
||||
@@ -67,14 +72,14 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
||||
|
||||
let base_event = base_event.to_room_event();
|
||||
|
||||
let events_before: Vec<_> = services()
|
||||
let events_before: Vec<_> = services
|
||||
.rooms
|
||||
.timeline
|
||||
.pdus_until(sender_user, &room_id, base_token)?
|
||||
.take(limit / 2)
|
||||
.filter_map(Result::ok) // Remove buggy events
|
||||
.filter(|(_, pdu)| {
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.user_can_see_event(sender_user, &room_id, &pdu.event_id)
|
||||
@@ -83,7 +88,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
||||
.collect();
|
||||
|
||||
for (_, event) in &events_before {
|
||||
if !services().rooms.lazy_loading.lazy_load_was_sent_before(
|
||||
if !services.rooms.lazy_loading.lazy_load_was_sent_before(
|
||||
sender_user,
|
||||
sender_device,
|
||||
&room_id,
|
||||
@@ -103,14 +108,14 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
||||
.map(|(_, pdu)| pdu.to_room_event())
|
||||
.collect();
|
||||
|
||||
let events_after: Vec<_> = services()
|
||||
let events_after: Vec<_> = services
|
||||
.rooms
|
||||
.timeline
|
||||
.pdus_after(sender_user, &room_id, base_token)?
|
||||
.take(limit / 2)
|
||||
.filter_map(Result::ok) // Remove buggy events
|
||||
.filter(|(_, pdu)| {
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.user_can_see_event(sender_user, &room_id, &pdu.event_id)
|
||||
@@ -119,7 +124,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
||||
.collect();
|
||||
|
||||
for (_, event) in &events_after {
|
||||
if !services().rooms.lazy_loading.lazy_load_was_sent_before(
|
||||
if !services.rooms.lazy_loading.lazy_load_was_sent_before(
|
||||
sender_user,
|
||||
sender_device,
|
||||
&room_id,
|
||||
@@ -130,7 +135,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
||||
}
|
||||
}
|
||||
|
||||
let shortstatehash = services()
|
||||
let shortstatehash = services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.pdu_shortstatehash(
|
||||
@@ -139,7 +144,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
||||
.map_or(&*body.event_id, |(_, e)| &*e.event_id),
|
||||
)?
|
||||
.map_or(
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.state
|
||||
.get_room_shortstatehash(&room_id)?
|
||||
@@ -147,7 +152,7 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
||||
|hash| hash,
|
||||
);
|
||||
|
||||
let state_ids = services()
|
||||
let state_ids = services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.state_full_ids(shortstatehash)
|
||||
@@ -165,20 +170,20 @@ pub(crate) async fn get_context_route(body: Ruma<get_context::v3::Request>) -> R
|
||||
let mut state = Vec::with_capacity(state_ids.len());
|
||||
|
||||
for (shortstatekey, id) in state_ids {
|
||||
let (event_type, state_key) = services()
|
||||
let (event_type, state_key) = services
|
||||
.rooms
|
||||
.short
|
||||
.get_statekey_from_short(shortstatekey)?;
|
||||
|
||||
if event_type != StateEventType::RoomMember {
|
||||
let Some(pdu) = services().rooms.timeline.get_pdu(&id)? else {
|
||||
let Some(pdu) = services.rooms.timeline.get_pdu(&id)? else {
|
||||
error!("Pdu in state not found: {}", id);
|
||||
continue;
|
||||
};
|
||||
|
||||
state.push(pdu.to_state_event());
|
||||
} else if !lazy_load_enabled || lazy_loaded.contains(&state_key) {
|
||||
let Some(pdu) = services().rooms.timeline.get_pdu(&id)? else {
|
||||
let Some(pdu) = services.rooms.timeline.get_pdu(&id)? else {
|
||||
error!("Pdu in state not found: {}", id);
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use axum::extract::State;
|
||||
use ruma::api::client::{
|
||||
device::{self, delete_device, delete_devices, get_device, get_devices, update_device},
|
||||
error::ErrorKind,
|
||||
@@ -5,15 +6,17 @@
|
||||
};
|
||||
|
||||
use super::SESSION_ID_LENGTH;
|
||||
use crate::{services, utils, Error, Result, Ruma};
|
||||
use crate::{utils, Error, Result, Ruma};
|
||||
|
||||
/// # `GET /_matrix/client/r0/devices`
|
||||
///
|
||||
/// Get metadata on all devices of the sender user.
|
||||
pub(crate) async fn get_devices_route(body: Ruma<get_devices::v3::Request>) -> Result<get_devices::v3::Response> {
|
||||
pub(crate) async fn get_devices_route(
|
||||
State(services): State<crate::State>, body: Ruma<get_devices::v3::Request>,
|
||||
) -> Result<get_devices::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let devices: Vec<device::Device> = services()
|
||||
let devices: Vec<device::Device> = services
|
||||
.users
|
||||
.all_devices_metadata(sender_user)
|
||||
.filter_map(Result::ok) // Filter out buggy devices
|
||||
@@ -27,10 +30,12 @@ pub(crate) async fn get_devices_route(body: Ruma<get_devices::v3::Request>) -> R
|
||||
/// # `GET /_matrix/client/r0/devices/{deviceId}`
|
||||
///
|
||||
/// Get metadata on a single device of the sender user.
|
||||
pub(crate) async fn get_device_route(body: Ruma<get_device::v3::Request>) -> Result<get_device::v3::Response> {
|
||||
pub(crate) async fn get_device_route(
|
||||
State(services): State<crate::State>, body: Ruma<get_device::v3::Request>,
|
||||
) -> Result<get_device::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let device = services()
|
||||
let device = services
|
||||
.users
|
||||
.get_device_metadata(sender_user, &body.body.device_id)?
|
||||
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Device not found."))?;
|
||||
@@ -43,17 +48,19 @@ pub(crate) async fn get_device_route(body: Ruma<get_device::v3::Request>) -> Res
|
||||
/// # `PUT /_matrix/client/r0/devices/{deviceId}`
|
||||
///
|
||||
/// Updates the metadata on a given device of the sender user.
|
||||
pub(crate) async fn update_device_route(body: Ruma<update_device::v3::Request>) -> Result<update_device::v3::Response> {
|
||||
pub(crate) async fn update_device_route(
|
||||
State(services): State<crate::State>, body: Ruma<update_device::v3::Request>,
|
||||
) -> Result<update_device::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let mut device = services()
|
||||
let mut device = services
|
||||
.users
|
||||
.get_device_metadata(sender_user, &body.device_id)?
|
||||
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Device not found."))?;
|
||||
|
||||
device.display_name.clone_from(&body.display_name);
|
||||
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.update_device_metadata(sender_user, &body.device_id, &device)?;
|
||||
|
||||
@@ -70,7 +77,9 @@ pub(crate) async fn update_device_route(body: Ruma<update_device::v3::Request>)
|
||||
/// last seen ts)
|
||||
/// - Forgets to-device events
|
||||
/// - Triggers device list updates
|
||||
pub(crate) async fn delete_device_route(body: Ruma<delete_device::v3::Request>) -> Result<delete_device::v3::Response> {
|
||||
pub(crate) async fn delete_device_route(
|
||||
State(services): State<crate::State>, body: Ruma<delete_device::v3::Request>,
|
||||
) -> Result<delete_device::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
|
||||
|
||||
@@ -86,7 +95,7 @@ pub(crate) async fn delete_device_route(body: Ruma<delete_device::v3::Request>)
|
||||
};
|
||||
|
||||
if let Some(auth) = &body.auth {
|
||||
let (worked, uiaainfo) = services()
|
||||
let (worked, uiaainfo) = services
|
||||
.uiaa
|
||||
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
|
||||
if !worked {
|
||||
@@ -95,7 +104,7 @@ pub(crate) async fn delete_device_route(body: Ruma<delete_device::v3::Request>)
|
||||
// Success!
|
||||
} else if let Some(json) = body.json_body {
|
||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||
services()
|
||||
services
|
||||
.uiaa
|
||||
.create(sender_user, sender_device, &uiaainfo, &json)?;
|
||||
return Err(Error::Uiaa(uiaainfo));
|
||||
@@ -103,9 +112,7 @@ pub(crate) async fn delete_device_route(body: Ruma<delete_device::v3::Request>)
|
||||
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
|
||||
}
|
||||
|
||||
services()
|
||||
.users
|
||||
.remove_device(sender_user, &body.device_id)?;
|
||||
services.users.remove_device(sender_user, &body.device_id)?;
|
||||
|
||||
Ok(delete_device::v3::Response {})
|
||||
}
|
||||
@@ -123,7 +130,7 @@ pub(crate) async fn delete_device_route(body: Ruma<delete_device::v3::Request>)
|
||||
/// - Forgets to-device events
|
||||
/// - Triggers device list updates
|
||||
pub(crate) async fn delete_devices_route(
|
||||
body: Ruma<delete_devices::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<delete_devices::v3::Request>,
|
||||
) -> Result<delete_devices::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
|
||||
@@ -140,7 +147,7 @@ pub(crate) async fn delete_devices_route(
|
||||
};
|
||||
|
||||
if let Some(auth) = &body.auth {
|
||||
let (worked, uiaainfo) = services()
|
||||
let (worked, uiaainfo) = services
|
||||
.uiaa
|
||||
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
|
||||
if !worked {
|
||||
@@ -149,7 +156,7 @@ pub(crate) async fn delete_devices_route(
|
||||
// Success!
|
||||
} else if let Some(json) = body.json_body {
|
||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||
services()
|
||||
services
|
||||
.uiaa
|
||||
.create(sender_user, sender_device, &uiaainfo, &json)?;
|
||||
return Err(Error::Uiaa(uiaainfo));
|
||||
@@ -158,7 +165,7 @@ pub(crate) async fn delete_devices_route(
|
||||
}
|
||||
|
||||
for device_id in &body.devices {
|
||||
services().users.remove_device(sender_user, device_id)?;
|
||||
services.users.remove_device(sender_user, device_id)?;
|
||||
}
|
||||
|
||||
Ok(delete_devices::v3::Response {})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use axum::extract::State;
|
||||
use axum_client_ip::InsecureClientIp;
|
||||
use conduit::{err, info, warn, Error, Result};
|
||||
use ruma::{
|
||||
@@ -19,8 +20,9 @@
|
||||
},
|
||||
uint, RoomId, ServerName, UInt, UserId,
|
||||
};
|
||||
use service::Services;
|
||||
|
||||
use crate::{service::server_is_ours, services, Ruma};
|
||||
use crate::Ruma;
|
||||
|
||||
/// # `POST /_matrix/client/v3/publicRooms`
|
||||
///
|
||||
@@ -29,10 +31,11 @@
|
||||
/// - Rooms are ordered by the number of joined members
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "publicrooms")]
|
||||
pub(crate) async fn get_public_rooms_filtered_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<get_public_rooms_filtered::v3::Request>,
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_public_rooms_filtered::v3::Request>,
|
||||
) -> Result<get_public_rooms_filtered::v3::Response> {
|
||||
if let Some(server) = &body.server {
|
||||
if services()
|
||||
if services
|
||||
.globals
|
||||
.forbidden_remote_room_directory_server_names()
|
||||
.contains(server)
|
||||
@@ -45,6 +48,7 @@ pub(crate) async fn get_public_rooms_filtered_route(
|
||||
}
|
||||
|
||||
let response = get_public_rooms_filtered_helper(
|
||||
&services,
|
||||
body.server.as_deref(),
|
||||
body.limit,
|
||||
body.since.as_deref(),
|
||||
@@ -67,10 +71,11 @@ pub(crate) async fn get_public_rooms_filtered_route(
|
||||
/// - Rooms are ordered by the number of joined members
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "publicrooms")]
|
||||
pub(crate) async fn get_public_rooms_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<get_public_rooms::v3::Request>,
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_public_rooms::v3::Request>,
|
||||
) -> Result<get_public_rooms::v3::Response> {
|
||||
if let Some(server) = &body.server {
|
||||
if services()
|
||||
if services
|
||||
.globals
|
||||
.forbidden_remote_room_directory_server_names()
|
||||
.contains(server)
|
||||
@@ -83,6 +88,7 @@ pub(crate) async fn get_public_rooms_route(
|
||||
}
|
||||
|
||||
let response = get_public_rooms_filtered_helper(
|
||||
&services,
|
||||
body.server.as_deref(),
|
||||
body.limit,
|
||||
body.since.as_deref(),
|
||||
@@ -108,16 +114,17 @@ pub(crate) async fn get_public_rooms_route(
|
||||
/// Sets the visibility of a given room in the room directory.
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "room_directory")]
|
||||
pub(crate) async fn set_room_visibility_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<set_room_visibility::v3::Request>,
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<set_room_visibility::v3::Request>,
|
||||
) -> Result<set_room_visibility::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
if !services().rooms.metadata.exists(&body.room_id)? {
|
||||
if !services.rooms.metadata.exists(&body.room_id)? {
|
||||
// Return 404 if the room doesn't exist
|
||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Room not found"));
|
||||
}
|
||||
|
||||
if !user_can_publish_room(sender_user, &body.room_id)? {
|
||||
if !user_can_publish_room(&services, sender_user, &body.room_id)? {
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::forbidden(),
|
||||
"User is not allowed to publish this room",
|
||||
@@ -126,7 +133,7 @@ pub(crate) async fn set_room_visibility_route(
|
||||
|
||||
match &body.visibility {
|
||||
room::Visibility::Public => {
|
||||
if services().globals.config.lockdown_public_room_directory && !services().users.is_admin(sender_user)? {
|
||||
if services.globals.config.lockdown_public_room_directory && !services.users.is_admin(sender_user)? {
|
||||
info!(
|
||||
"Non-admin user {sender_user} tried to publish {0} to the room directory while \
|
||||
\"lockdown_public_room_directory\" is enabled",
|
||||
@@ -139,10 +146,10 @@ pub(crate) async fn set_room_visibility_route(
|
||||
));
|
||||
}
|
||||
|
||||
services().rooms.directory.set_public(&body.room_id)?;
|
||||
services.rooms.directory.set_public(&body.room_id)?;
|
||||
info!("{sender_user} made {0} public", body.room_id);
|
||||
},
|
||||
room::Visibility::Private => services().rooms.directory.set_not_public(&body.room_id)?,
|
||||
room::Visibility::Private => services.rooms.directory.set_not_public(&body.room_id)?,
|
||||
_ => {
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::InvalidParam,
|
||||
@@ -158,15 +165,15 @@ pub(crate) async fn set_room_visibility_route(
|
||||
///
|
||||
/// Gets the visibility of a given room in the room directory.
|
||||
pub(crate) async fn get_room_visibility_route(
|
||||
body: Ruma<get_room_visibility::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_room_visibility::v3::Request>,
|
||||
) -> Result<get_room_visibility::v3::Response> {
|
||||
if !services().rooms.metadata.exists(&body.room_id)? {
|
||||
if !services.rooms.metadata.exists(&body.room_id)? {
|
||||
// Return 404 if the room doesn't exist
|
||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Room not found"));
|
||||
}
|
||||
|
||||
Ok(get_room_visibility::v3::Response {
|
||||
visibility: if services().rooms.directory.is_public_room(&body.room_id)? {
|
||||
visibility: if services.rooms.directory.is_public_room(&body.room_id)? {
|
||||
room::Visibility::Public
|
||||
} else {
|
||||
room::Visibility::Private
|
||||
@@ -175,10 +182,11 @@ pub(crate) async fn get_room_visibility_route(
|
||||
}
|
||||
|
||||
pub(crate) async fn get_public_rooms_filtered_helper(
|
||||
server: Option<&ServerName>, limit: Option<UInt>, since: Option<&str>, filter: &Filter, _network: &RoomNetwork,
|
||||
services: &Services, server: Option<&ServerName>, limit: Option<UInt>, since: Option<&str>, filter: &Filter,
|
||||
_network: &RoomNetwork,
|
||||
) -> Result<get_public_rooms_filtered::v3::Response> {
|
||||
if let Some(other_server) = server.filter(|server_name| !server_is_ours(server_name)) {
|
||||
let response = services()
|
||||
if let Some(other_server) = server.filter(|server_name| !services.globals.server_is_ours(server_name)) {
|
||||
let response = services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
other_server,
|
||||
@@ -224,7 +232,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
|
||||
}
|
||||
}
|
||||
|
||||
let mut all_rooms: Vec<_> = services()
|
||||
let mut all_rooms: Vec<_> = services
|
||||
.rooms
|
||||
.directory
|
||||
.public_rooms()
|
||||
@@ -232,12 +240,12 @@ pub(crate) async fn get_public_rooms_filtered_helper(
|
||||
let room_id = room_id?;
|
||||
|
||||
let chunk = PublicRoomsChunk {
|
||||
canonical_alias: services()
|
||||
canonical_alias: services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.get_canonical_alias(&room_id)?,
|
||||
name: services().rooms.state_accessor.get_name(&room_id)?,
|
||||
num_joined_members: services()
|
||||
name: services.rooms.state_accessor.get_name(&room_id)?,
|
||||
num_joined_members: services
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_joined_count(&room_id)?
|
||||
@@ -247,24 +255,24 @@ pub(crate) async fn get_public_rooms_filtered_helper(
|
||||
})
|
||||
.try_into()
|
||||
.expect("user count should not be that big"),
|
||||
topic: services()
|
||||
topic: services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.get_room_topic(&room_id)
|
||||
.unwrap_or(None),
|
||||
world_readable: services().rooms.state_accessor.is_world_readable(&room_id)?,
|
||||
guest_can_join: services()
|
||||
world_readable: services.rooms.state_accessor.is_world_readable(&room_id)?,
|
||||
guest_can_join: services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.guest_can_join(&room_id)?,
|
||||
avatar_url: services()
|
||||
avatar_url: services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.get_avatar(&room_id)?
|
||||
.into_option()
|
||||
.unwrap_or_default()
|
||||
.url,
|
||||
join_rule: services()
|
||||
join_rule: services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.room_state_get(&room_id, &StateEventType::RoomJoinRules, "")?
|
||||
@@ -282,7 +290,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
|
||||
.transpose()?
|
||||
.flatten()
|
||||
.ok_or_else(|| Error::bad_database("Missing room join rule event for room."))?,
|
||||
room_type: services()
|
||||
room_type: services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.get_room_type(&room_id)?,
|
||||
@@ -361,12 +369,11 @@ pub(crate) async fn get_public_rooms_filtered_helper(
|
||||
|
||||
/// Check whether the user can publish to the room directory via power levels of
|
||||
/// room history visibility event or room creator
|
||||
fn user_can_publish_room(user_id: &UserId, room_id: &RoomId) -> Result<bool> {
|
||||
if let Some(event) =
|
||||
services()
|
||||
.rooms
|
||||
.state_accessor
|
||||
.room_state_get(room_id, &StateEventType::RoomPowerLevels, "")?
|
||||
fn user_can_publish_room(services: &Services, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
|
||||
if let Some(event) = services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.room_state_get(room_id, &StateEventType::RoomPowerLevels, "")?
|
||||
{
|
||||
serde_json::from_str(event.content.get())
|
||||
.map_err(|_| Error::bad_database("Invalid event content for m.room.power_levels"))
|
||||
@@ -374,7 +381,7 @@ fn user_can_publish_room(user_id: &UserId, room_id: &RoomId) -> Result<bool> {
|
||||
RoomPowerLevels::from(content).user_can_send_state(user_id, StateEventType::RoomHistoryVisibility)
|
||||
})
|
||||
} else if let Some(event) =
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.room_state_get(room_id, &StateEventType::RoomCreate, "")?
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
use axum::extract::State;
|
||||
use ruma::api::client::{
|
||||
error::ErrorKind,
|
||||
filter::{create_filter, get_filter},
|
||||
};
|
||||
|
||||
use crate::{services, Error, Result, Ruma};
|
||||
use crate::{Error, Result, Ruma};
|
||||
|
||||
/// # `GET /_matrix/client/r0/user/{userId}/filter/{filterId}`
|
||||
///
|
||||
/// Loads a filter that was previously created.
|
||||
///
|
||||
/// - A user can only access their own filters
|
||||
pub(crate) async fn get_filter_route(body: Ruma<get_filter::v3::Request>) -> Result<get_filter::v3::Response> {
|
||||
pub(crate) async fn get_filter_route(
|
||||
State(services): State<crate::State>, body: Ruma<get_filter::v3::Request>,
|
||||
) -> Result<get_filter::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let Some(filter) = services().users.get_filter(sender_user, &body.filter_id)? else {
|
||||
let Some(filter) = services.users.get_filter(sender_user, &body.filter_id)? else {
|
||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Filter not found."));
|
||||
};
|
||||
|
||||
@@ -22,9 +25,11 @@ pub(crate) async fn get_filter_route(body: Ruma<get_filter::v3::Request>) -> Res
|
||||
/// # `PUT /_matrix/client/r0/user/{userId}/filter`
|
||||
///
|
||||
/// Creates a new filter to be used by other endpoints.
|
||||
pub(crate) async fn create_filter_route(body: Ruma<create_filter::v3::Request>) -> Result<create_filter::v3::Response> {
|
||||
pub(crate) async fn create_filter_route(
|
||||
State(services): State<crate::State>, body: Ruma<create_filter::v3::Request>,
|
||||
) -> Result<create_filter::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
Ok(create_filter::v3::Response::new(
|
||||
services().users.create_filter(sender_user, &body.filter)?,
|
||||
services.users.create_filter(sender_user, &body.filter)?,
|
||||
))
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
use conduit::{utils, utils::math::continue_exponential_backoff_secs, Error, Result};
|
||||
use axum::extract::State;
|
||||
use conduit::{utils, utils::math::continue_exponential_backoff_secs, Err, Error, Result};
|
||||
use futures_util::{stream::FuturesUnordered, StreamExt};
|
||||
use ruma::{
|
||||
api::{
|
||||
@@ -18,11 +19,9 @@
|
||||
DeviceKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId,
|
||||
};
|
||||
use serde_json::json;
|
||||
use service::user_is_local;
|
||||
use tracing::debug;
|
||||
|
||||
use super::SESSION_ID_LENGTH;
|
||||
use crate::{services, Ruma};
|
||||
use crate::{service::Services, Ruma};
|
||||
|
||||
/// # `POST /_matrix/client/r0/keys/upload`
|
||||
///
|
||||
@@ -31,12 +30,14 @@
|
||||
/// - Adds one time keys
|
||||
/// - If there are no device keys yet: Adds device keys (TODO: merge with
|
||||
/// existing keys?)
|
||||
pub(crate) async fn upload_keys_route(body: Ruma<upload_keys::v3::Request>) -> Result<upload_keys::v3::Response> {
|
||||
pub(crate) async fn upload_keys_route(
|
||||
State(services): State<crate::State>, body: Ruma<upload_keys::v3::Request>,
|
||||
) -> Result<upload_keys::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
|
||||
|
||||
for (key_key, key_value) in &body.one_time_keys {
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.add_one_time_key(sender_user, sender_device, key_key, key_value)?;
|
||||
}
|
||||
@@ -44,19 +45,19 @@ pub(crate) async fn upload_keys_route(body: Ruma<upload_keys::v3::Request>) -> R
|
||||
if let Some(device_keys) = &body.device_keys {
|
||||
// TODO: merge this and the existing event?
|
||||
// This check is needed to assure that signatures are kept
|
||||
if services()
|
||||
if services
|
||||
.users
|
||||
.get_device_keys(sender_user, sender_device)?
|
||||
.is_none()
|
||||
{
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.add_device_keys(sender_user, sender_device, device_keys)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(upload_keys::v3::Response {
|
||||
one_time_key_counts: services()
|
||||
one_time_key_counts: services
|
||||
.users
|
||||
.count_one_time_keys(sender_user, sender_device)?,
|
||||
})
|
||||
@@ -70,10 +71,13 @@ pub(crate) async fn upload_keys_route(body: Ruma<upload_keys::v3::Request>) -> R
|
||||
/// - Gets master keys, self-signing keys, user signing keys and device keys.
|
||||
/// - The master and self-signing keys contain signatures that the user is
|
||||
/// allowed to see
|
||||
pub(crate) async fn get_keys_route(body: Ruma<get_keys::v3::Request>) -> Result<get_keys::v3::Response> {
|
||||
pub(crate) async fn get_keys_route(
|
||||
State(services): State<crate::State>, body: Ruma<get_keys::v3::Request>,
|
||||
) -> Result<get_keys::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
get_keys_helper(
|
||||
&services,
|
||||
Some(sender_user),
|
||||
&body.device_keys,
|
||||
|u| u == sender_user,
|
||||
@@ -85,8 +89,10 @@ pub(crate) async fn get_keys_route(body: Ruma<get_keys::v3::Request>) -> Result<
|
||||
/// # `POST /_matrix/client/r0/keys/claim`
|
||||
///
|
||||
/// Claims one-time keys
|
||||
pub(crate) async fn claim_keys_route(body: Ruma<claim_keys::v3::Request>) -> Result<claim_keys::v3::Response> {
|
||||
claim_keys_helper(&body.one_time_keys).await
|
||||
pub(crate) async fn claim_keys_route(
|
||||
State(services): State<crate::State>, body: Ruma<claim_keys::v3::Request>,
|
||||
) -> Result<claim_keys::v3::Response> {
|
||||
claim_keys_helper(&services, &body.one_time_keys).await
|
||||
}
|
||||
|
||||
/// # `POST /_matrix/client/r0/keys/device_signing/upload`
|
||||
@@ -95,7 +101,7 @@ pub(crate) async fn claim_keys_route(body: Ruma<claim_keys::v3::Request>) -> Res
|
||||
///
|
||||
/// - Requires UIAA to verify password
|
||||
pub(crate) async fn upload_signing_keys_route(
|
||||
body: Ruma<upload_signing_keys::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<upload_signing_keys::v3::Request>,
|
||||
) -> Result<upload_signing_keys::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
|
||||
@@ -112,7 +118,7 @@ pub(crate) async fn upload_signing_keys_route(
|
||||
};
|
||||
|
||||
if let Some(auth) = &body.auth {
|
||||
let (worked, uiaainfo) = services()
|
||||
let (worked, uiaainfo) = services
|
||||
.uiaa
|
||||
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
|
||||
if !worked {
|
||||
@@ -121,7 +127,7 @@ pub(crate) async fn upload_signing_keys_route(
|
||||
// Success!
|
||||
} else if let Some(json) = body.json_body {
|
||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||
services()
|
||||
services
|
||||
.uiaa
|
||||
.create(sender_user, sender_device, &uiaainfo, &json)?;
|
||||
return Err(Error::Uiaa(uiaainfo));
|
||||
@@ -130,7 +136,7 @@ pub(crate) async fn upload_signing_keys_route(
|
||||
}
|
||||
|
||||
if let Some(master_key) = &body.master_key {
|
||||
services().users.add_cross_signing_keys(
|
||||
services.users.add_cross_signing_keys(
|
||||
sender_user,
|
||||
master_key,
|
||||
&body.self_signing_key,
|
||||
@@ -146,7 +152,7 @@ pub(crate) async fn upload_signing_keys_route(
|
||||
///
|
||||
/// Uploads end-to-end key signatures from the sender user.
|
||||
pub(crate) async fn upload_signatures_route(
|
||||
body: Ruma<upload_signatures::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<upload_signatures::v3::Request>,
|
||||
) -> Result<upload_signatures::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
@@ -173,7 +179,7 @@ pub(crate) async fn upload_signatures_route(
|
||||
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Invalid signature value."))?
|
||||
.to_owned(),
|
||||
);
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.sign_key(user_id, key_id, signature, sender_user)?;
|
||||
}
|
||||
@@ -192,14 +198,14 @@ pub(crate) async fn upload_signatures_route(
|
||||
///
|
||||
/// - TODO: left users
|
||||
pub(crate) async fn get_key_changes_route(
|
||||
body: Ruma<get_key_changes::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_key_changes::v3::Request>,
|
||||
) -> Result<get_key_changes::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let mut device_list_updates = HashSet::new();
|
||||
|
||||
device_list_updates.extend(
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.keys_changed(
|
||||
sender_user.as_str(),
|
||||
@@ -215,14 +221,14 @@ pub(crate) async fn get_key_changes_route(
|
||||
.filter_map(Result::ok),
|
||||
);
|
||||
|
||||
for room_id in services()
|
||||
for room_id in services
|
||||
.rooms
|
||||
.state_cache
|
||||
.rooms_joined(sender_user)
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
device_list_updates.extend(
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.keys_changed(
|
||||
room_id.as_ref(),
|
||||
@@ -245,8 +251,8 @@ pub(crate) async fn get_key_changes_route(
|
||||
}
|
||||
|
||||
pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool + Send>(
|
||||
sender_user: Option<&UserId>, device_keys_input: &BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>, allowed_signatures: F,
|
||||
include_display_names: bool,
|
||||
services: &Services, sender_user: Option<&UserId>, device_keys_input: &BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>,
|
||||
allowed_signatures: F, include_display_names: bool,
|
||||
) -> Result<get_keys::v3::Response> {
|
||||
let mut master_keys = BTreeMap::new();
|
||||
let mut self_signing_keys = BTreeMap::new();
|
||||
@@ -258,7 +264,7 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool + Send>(
|
||||
for (user_id, device_ids) in device_keys_input {
|
||||
let user_id: &UserId = user_id;
|
||||
|
||||
if !user_is_local(user_id) {
|
||||
if !services.globals.user_is_local(user_id) {
|
||||
get_over_federation
|
||||
.entry(user_id.server_name())
|
||||
.or_insert_with(Vec::new)
|
||||
@@ -268,10 +274,10 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool + Send>(
|
||||
|
||||
if device_ids.is_empty() {
|
||||
let mut container = BTreeMap::new();
|
||||
for device_id in services().users.all_device_ids(user_id) {
|
||||
for device_id in services.users.all_device_ids(user_id) {
|
||||
let device_id = device_id?;
|
||||
if let Some(mut keys) = services().users.get_device_keys(user_id, &device_id)? {
|
||||
let metadata = services()
|
||||
if let Some(mut keys) = services.users.get_device_keys(user_id, &device_id)? {
|
||||
let metadata = services
|
||||
.users
|
||||
.get_device_metadata(user_id, &device_id)?
|
||||
.ok_or_else(|| Error::bad_database("all_device_keys contained nonexistent device."))?;
|
||||
@@ -286,8 +292,8 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool + Send>(
|
||||
} else {
|
||||
for device_id in device_ids {
|
||||
let mut container = BTreeMap::new();
|
||||
if let Some(mut keys) = services().users.get_device_keys(user_id, device_id)? {
|
||||
let metadata = services()
|
||||
if let Some(mut keys) = services.users.get_device_keys(user_id, device_id)? {
|
||||
let metadata = services
|
||||
.users
|
||||
.get_device_metadata(user_id, device_id)?
|
||||
.ok_or(Error::BadRequest(
|
||||
@@ -303,21 +309,21 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool + Send>(
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(master_key) = services()
|
||||
if let Some(master_key) = services
|
||||
.users
|
||||
.get_master_key(sender_user, user_id, &allowed_signatures)?
|
||||
{
|
||||
master_keys.insert(user_id.to_owned(), master_key);
|
||||
}
|
||||
if let Some(self_signing_key) =
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.get_self_signing_key(sender_user, user_id, &allowed_signatures)?
|
||||
{
|
||||
self_signing_keys.insert(user_id.to_owned(), self_signing_key);
|
||||
}
|
||||
if Some(user_id) == sender_user {
|
||||
if let Some(user_signing_key) = services().users.get_user_signing_key(user_id)? {
|
||||
if let Some(user_signing_key) = services.users.get_user_signing_key(user_id)? {
|
||||
user_signing_keys.insert(user_id.to_owned(), user_signing_key);
|
||||
}
|
||||
}
|
||||
@@ -326,7 +332,7 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool + Send>(
|
||||
let mut failures = BTreeMap::new();
|
||||
|
||||
let back_off = |id| async {
|
||||
match services()
|
||||
match services
|
||||
.globals
|
||||
.bad_query_ratelimiter
|
||||
.write()
|
||||
@@ -345,7 +351,7 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool + Send>(
|
||||
let mut futures: FuturesUnordered<_> = get_over_federation
|
||||
.into_iter()
|
||||
.map(|(server, vec)| async move {
|
||||
if let Some((time, tries)) = services()
|
||||
if let Some((time, tries)) = services
|
||||
.globals
|
||||
.bad_query_ratelimiter
|
||||
.read()
|
||||
@@ -356,8 +362,7 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool + Send>(
|
||||
const MIN: u64 = 5 * 60;
|
||||
const MAX: u64 = 60 * 60 * 24;
|
||||
if continue_exponential_backoff_secs(MIN, MAX, time.elapsed(), *tries) {
|
||||
debug!("Backing off query from {server:?}");
|
||||
return (server, Err(Error::BadServerResponse("bad query, still backing off")));
|
||||
return (server, Err!(BadServerResponse("bad query from {server:?}, still backing off")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -369,7 +374,7 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool + Send>(
|
||||
let request = federation::keys::get_keys::v1::Request {
|
||||
device_keys: device_keys_input_fed,
|
||||
};
|
||||
let response = services()
|
||||
let response = services
|
||||
.sending
|
||||
.send_federation_request(server, request)
|
||||
.await;
|
||||
@@ -381,19 +386,19 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool + Send>(
|
||||
while let Some((server, response)) = futures.next().await {
|
||||
if let Ok(Ok(response)) = response {
|
||||
for (user, masterkey) in response.master_keys {
|
||||
let (master_key_id, mut master_key) = services().users.parse_master_key(&user, &masterkey)?;
|
||||
let (master_key_id, mut master_key) = services.users.parse_master_key(&user, &masterkey)?;
|
||||
|
||||
if let Some(our_master_key) =
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.get_key(&master_key_id, sender_user, &user, &allowed_signatures)?
|
||||
{
|
||||
let (_, our_master_key) = services().users.parse_master_key(&user, &our_master_key)?;
|
||||
let (_, our_master_key) = services.users.parse_master_key(&user, &our_master_key)?;
|
||||
master_key.signatures.extend(our_master_key.signatures);
|
||||
}
|
||||
let json = serde_json::to_value(master_key).expect("to_value always works");
|
||||
let raw = serde_json::from_value(json).expect("Raw::from_value always works");
|
||||
services().users.add_cross_signing_keys(
|
||||
services.users.add_cross_signing_keys(
|
||||
&user, &raw, &None, &None,
|
||||
false, /* Dont notify. A notification would trigger another key request resulting in an
|
||||
* endless loop */
|
||||
@@ -444,14 +449,14 @@ fn add_unsigned_device_display_name(
|
||||
}
|
||||
|
||||
pub(crate) async fn claim_keys_helper(
|
||||
one_time_keys_input: &BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, DeviceKeyAlgorithm>>,
|
||||
services: &Services, one_time_keys_input: &BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, DeviceKeyAlgorithm>>,
|
||||
) -> Result<claim_keys::v3::Response> {
|
||||
let mut one_time_keys = BTreeMap::new();
|
||||
|
||||
let mut get_over_federation = BTreeMap::new();
|
||||
|
||||
for (user_id, map) in one_time_keys_input {
|
||||
if !user_is_local(user_id) {
|
||||
if !services.globals.user_is_local(user_id) {
|
||||
get_over_federation
|
||||
.entry(user_id.server_name())
|
||||
.or_insert_with(Vec::new)
|
||||
@@ -460,7 +465,7 @@ pub(crate) async fn claim_keys_helper(
|
||||
|
||||
let mut container = BTreeMap::new();
|
||||
for (device_id, key_algorithm) in map {
|
||||
if let Some(one_time_keys) = services()
|
||||
if let Some(one_time_keys) = services
|
||||
.users
|
||||
.take_one_time_key(user_id, device_id, key_algorithm)?
|
||||
{
|
||||
@@ -483,7 +488,7 @@ pub(crate) async fn claim_keys_helper(
|
||||
}
|
||||
(
|
||||
server,
|
||||
services()
|
||||
services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
server,
|
||||
|
||||
@@ -1,127 +1,37 @@
|
||||
#![allow(deprecated)]
|
||||
|
||||
use std::{io::Cursor, sync::Arc, time::Duration};
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::State;
|
||||
use axum_client_ip::InsecureClientIp;
|
||||
use conduit::{debug, error, utils::math::ruma_from_usize, warn};
|
||||
use image::io::Reader as ImgReader;
|
||||
use ipaddress::IPAddress;
|
||||
use reqwest::Url;
|
||||
use ruma::api::client::{
|
||||
error::{ErrorKind, RetryAfter},
|
||||
media::{
|
||||
create_content, get_content, get_content_as_filename, get_content_thumbnail, get_media_config,
|
||||
get_media_preview,
|
||||
},
|
||||
use conduit::{
|
||||
err,
|
||||
utils::{self, content_disposition::make_content_disposition, math::ruma_from_usize},
|
||||
Err, Result,
|
||||
};
|
||||
use webpage::HTML;
|
||||
|
||||
use crate::{
|
||||
debug_warn,
|
||||
service::{
|
||||
media::{FileMeta, UrlPreviewData},
|
||||
server_is_ours,
|
||||
use conduit_service::{
|
||||
media::{Dim, FileMeta, CACHE_CONTROL_IMMUTABLE, CORP_CROSS_ORIGIN, MXC_LENGTH},
|
||||
Services,
|
||||
};
|
||||
use ruma::{
|
||||
api::client::{
|
||||
authenticated_media::{
|
||||
get_content, get_content_as_filename, get_content_thumbnail, get_media_config, get_media_preview,
|
||||
},
|
||||
media::create_content,
|
||||
},
|
||||
services,
|
||||
utils::{
|
||||
self,
|
||||
content_disposition::{content_disposition_type, make_content_disposition, sanitise_filename},
|
||||
},
|
||||
Error, Result, Ruma, RumaResponse,
|
||||
Mxc, UserId,
|
||||
};
|
||||
|
||||
/// generated MXC ID (`media-id`) length
|
||||
const MXC_LENGTH: usize = 32;
|
||||
use crate::Ruma;
|
||||
|
||||
/// Cache control for immutable objects
|
||||
const CACHE_CONTROL_IMMUTABLE: &str = "public,max-age=31536000,immutable";
|
||||
|
||||
const CORP_CROSS_ORIGIN: &str = "cross-origin";
|
||||
|
||||
/// # `GET /_matrix/media/v3/config`
|
||||
///
|
||||
/// Returns max upload size.
|
||||
/// # `GET /_matrix/client/v1/media/config`
|
||||
pub(crate) async fn get_media_config_route(
|
||||
_body: Ruma<get_media_config::v3::Request>,
|
||||
) -> Result<get_media_config::v3::Response> {
|
||||
Ok(get_media_config::v3::Response {
|
||||
upload_size: ruma_from_usize(services().globals.config.max_request_size),
|
||||
State(services): State<crate::State>, _body: Ruma<get_media_config::v1::Request>,
|
||||
) -> Result<get_media_config::v1::Response> {
|
||||
Ok(get_media_config::v1::Response {
|
||||
upload_size: ruma_from_usize(services.globals.config.max_request_size),
|
||||
})
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v1/config`
|
||||
///
|
||||
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
|
||||
/// clients may call. conduwuit adds these for compatibility purposes.
|
||||
/// See <https://spec.matrix.org/legacy/legacy/#id27>
|
||||
///
|
||||
/// Returns max upload size.
|
||||
pub(crate) async fn get_media_config_v1_route(
|
||||
body: Ruma<get_media_config::v3::Request>,
|
||||
) -> Result<RumaResponse<get_media_config::v3::Response>> {
|
||||
get_media_config_route(body).await.map(RumaResponse)
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v3/preview_url`
|
||||
///
|
||||
/// Returns URL preview.
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "url_preview")]
|
||||
pub(crate) async fn get_media_preview_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<get_media_preview::v3::Request>,
|
||||
) -> Result<get_media_preview::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let url = &body.url;
|
||||
if !url_preview_allowed(url) {
|
||||
warn!(%sender_user, "URL is not allowed to be previewed: {url}");
|
||||
return Err(Error::BadRequest(ErrorKind::forbidden(), "URL is not allowed to be previewed"));
|
||||
}
|
||||
|
||||
match get_url_preview(url).await {
|
||||
Ok(preview) => {
|
||||
let res = serde_json::value::to_raw_value(&preview).map_err(|e| {
|
||||
error!(%sender_user, "Failed to convert UrlPreviewData into a serde json value: {e}");
|
||||
Error::BadRequest(
|
||||
ErrorKind::LimitExceeded {
|
||||
retry_after: Some(RetryAfter::Delay(Duration::from_secs(5))),
|
||||
},
|
||||
"Failed to generate a URL preview, try again later.",
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(get_media_preview::v3::Response::from_raw_value(res))
|
||||
},
|
||||
Err(e) => {
|
||||
warn!(%sender_user, "Failed to generate a URL preview: {e}");
|
||||
|
||||
// there doesn't seem to be an agreed-upon error code in the spec.
|
||||
// the only response codes in the preview_url spec page are 200 and 429.
|
||||
Err(Error::BadRequest(
|
||||
ErrorKind::LimitExceeded {
|
||||
retry_after: Some(RetryAfter::Delay(Duration::from_secs(5))),
|
||||
},
|
||||
"Failed to generate a URL preview, try again later.",
|
||||
))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v1/preview_url`
|
||||
///
|
||||
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
|
||||
/// clients may call. conduwuit adds these for compatibility purposes.
|
||||
/// See <https://spec.matrix.org/legacy/legacy/#id27>
|
||||
///
|
||||
/// Returns URL preview.
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "url_preview")]
|
||||
pub(crate) async fn get_media_preview_v1_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<get_media_preview::v3::Request>,
|
||||
) -> Result<RumaResponse<get_media_preview::v3::Response>> {
|
||||
get_media_preview_route(InsecureClientIp(client), body)
|
||||
.await
|
||||
.map(RumaResponse)
|
||||
}
|
||||
|
||||
/// # `POST /_matrix/media/v3/upload`
|
||||
///
|
||||
/// Permanently save media in the server.
|
||||
@@ -130,646 +40,224 @@ pub(crate) async fn get_media_preview_v1_route(
|
||||
/// - Media will be saved in the media/ directory
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_upload")]
|
||||
pub(crate) async fn create_content_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<create_content::v3::Request>,
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<create_content::v3::Request>,
|
||||
) -> Result<create_content::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let mxc = format!(
|
||||
"mxc://{}/{}",
|
||||
services().globals.server_name(),
|
||||
utils::random_string(MXC_LENGTH)
|
||||
);
|
||||
let filename = body.filename.as_deref();
|
||||
let content_type = body.content_type.as_deref();
|
||||
let content_disposition = make_content_disposition(None, content_type, filename);
|
||||
let mxc = Mxc {
|
||||
server_name: services.globals.server_name(),
|
||||
media_id: &utils::random_string(MXC_LENGTH),
|
||||
};
|
||||
|
||||
services()
|
||||
services
|
||||
.media
|
||||
.create(
|
||||
Some(sender_user.clone()),
|
||||
&mxc,
|
||||
body.filename
|
||||
.as_ref()
|
||||
.map(|filename| {
|
||||
format!(
|
||||
"{}; filename={}",
|
||||
content_disposition_type(&body.content_type),
|
||||
sanitise_filename(filename.to_owned())
|
||||
)
|
||||
})
|
||||
.as_deref(),
|
||||
body.content_type.as_deref(),
|
||||
&body.file,
|
||||
)
|
||||
.await?;
|
||||
.create(&mxc, Some(user), Some(&content_disposition), content_type, &body.file)
|
||||
.await
|
||||
.map(|()| create_content::v3::Response {
|
||||
content_uri: mxc.to_string().into(),
|
||||
blurhash: None,
|
||||
})
|
||||
}
|
||||
|
||||
Ok(create_content::v3::Response {
|
||||
content_uri: mxc.into(),
|
||||
blurhash: None,
|
||||
/// # `GET /_matrix/client/v1/media/thumbnail/{serverName}/{mediaId}`
|
||||
///
|
||||
/// Load media thumbnail from our server or over federation.
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_thumbnail_get")]
|
||||
pub(crate) async fn get_content_thumbnail_route(
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_content_thumbnail::v1::Request>,
|
||||
) -> Result<get_content_thumbnail::v1::Response> {
|
||||
let user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let dim = Dim::from_ruma(body.width, body.height, body.method.clone())?;
|
||||
let mxc = Mxc {
|
||||
server_name: &body.server_name,
|
||||
media_id: &body.media_id,
|
||||
};
|
||||
|
||||
let FileMeta {
|
||||
content,
|
||||
content_type,
|
||||
content_disposition,
|
||||
} = fetch_thumbnail(&services, &mxc, user, body.timeout_ms, &dim).await?;
|
||||
|
||||
Ok(get_content_thumbnail::v1::Response {
|
||||
file: content.expect("entire file contents"),
|
||||
content_type: content_type.map(Into::into),
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
|
||||
content_disposition,
|
||||
})
|
||||
}
|
||||
|
||||
/// # `POST /_matrix/media/v1/upload`
|
||||
///
|
||||
/// Permanently save media in the server.
|
||||
///
|
||||
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
|
||||
/// clients may call. conduwuit adds these for compatibility purposes.
|
||||
/// See <https://spec.matrix.org/legacy/legacy/#id27>
|
||||
///
|
||||
/// - Some metadata will be saved in the database
|
||||
/// - Media will be saved in the media/ directory
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_upload")]
|
||||
pub(crate) async fn create_content_v1_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<create_content::v3::Request>,
|
||||
) -> Result<RumaResponse<create_content::v3::Response>> {
|
||||
create_content_route(InsecureClientIp(client), body)
|
||||
.await
|
||||
.map(RumaResponse)
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}`
|
||||
/// # `GET /_matrix/client/v1/media/download/{serverName}/{mediaId}`
|
||||
///
|
||||
/// Load media from our server or over federation.
|
||||
///
|
||||
/// - Only allows federation if `allow_remote` is true
|
||||
/// - Only redirects if `allow_redirect` is true
|
||||
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
|
||||
/// seconds
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_get")]
|
||||
pub(crate) async fn get_content_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<get_content::v3::Request>,
|
||||
) -> Result<get_content::v3::Response> {
|
||||
let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_content::v1::Request>,
|
||||
) -> Result<get_content::v1::Response> {
|
||||
let user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
if let Some(FileMeta {
|
||||
let mxc = Mxc {
|
||||
server_name: &body.server_name,
|
||||
media_id: &body.media_id,
|
||||
};
|
||||
|
||||
let FileMeta {
|
||||
content,
|
||||
content_type,
|
||||
content_disposition,
|
||||
}) = services().media.get(&mxc).await?
|
||||
{
|
||||
let content_disposition = Some(make_content_disposition(&content_type, content_disposition, None));
|
||||
let file = content.expect("content");
|
||||
} = fetch_file(&services, &mxc, user, body.timeout_ms, None).await?;
|
||||
|
||||
Ok(get_content::v3::Response {
|
||||
file,
|
||||
content_type,
|
||||
content_disposition,
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
|
||||
})
|
||||
} else if !server_is_ours(&body.server_name) && body.allow_remote {
|
||||
let response = get_remote_content(
|
||||
&mxc,
|
||||
&body.server_name,
|
||||
body.media_id.clone(),
|
||||
body.allow_redirect,
|
||||
body.timeout_ms,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
debug_warn!("Fetching media `{}` failed: {:?}", mxc, e);
|
||||
Error::BadRequest(ErrorKind::NotFound, "Remote media error.")
|
||||
})?;
|
||||
|
||||
let content_disposition = Some(make_content_disposition(
|
||||
&response.content_type,
|
||||
response.content_disposition,
|
||||
None,
|
||||
));
|
||||
|
||||
Ok(get_content::v3::Response {
|
||||
file: response.file,
|
||||
content_type: response.content_type,
|
||||
content_disposition,
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.to_owned()),
|
||||
})
|
||||
} else {
|
||||
Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."))
|
||||
}
|
||||
Ok(get_content::v1::Response {
|
||||
file: content.expect("entire file contents"),
|
||||
content_type: content_type.map(Into::into),
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
|
||||
content_disposition,
|
||||
})
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v1/download/{serverName}/{mediaId}`
|
||||
/// # `GET /_matrix/client/v1/media/download/{serverName}/{mediaId}/{fileName}`
|
||||
///
|
||||
/// Load media from our server or over federation.
|
||||
///
|
||||
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
|
||||
/// clients may call. conduwuit adds these for compatibility purposes.
|
||||
/// See <https://spec.matrix.org/legacy/legacy/#id27>
|
||||
///
|
||||
/// - Only allows federation if `allow_remote` is true
|
||||
/// - Only redirects if `allow_redirect` is true
|
||||
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
|
||||
/// seconds
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_get")]
|
||||
pub(crate) async fn get_content_v1_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<get_content::v3::Request>,
|
||||
) -> Result<RumaResponse<get_content::v3::Response>> {
|
||||
get_content_route(InsecureClientIp(client), body)
|
||||
.await
|
||||
.map(RumaResponse)
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}/{fileName}`
|
||||
///
|
||||
/// Load media from our server or over federation, permitting desired filename.
|
||||
///
|
||||
/// - Only allows federation if `allow_remote` is true
|
||||
/// - Only redirects if `allow_redirect` is true
|
||||
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
|
||||
/// seconds
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_get")]
|
||||
/// Load media from our server or over federation as fileName.
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_get_af")]
|
||||
pub(crate) async fn get_content_as_filename_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<get_content_as_filename::v3::Request>,
|
||||
) -> Result<get_content_as_filename::v3::Response> {
|
||||
let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_content_as_filename::v1::Request>,
|
||||
) -> Result<get_content_as_filename::v1::Response> {
|
||||
let user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
if let Some(FileMeta {
|
||||
let mxc = Mxc {
|
||||
server_name: &body.server_name,
|
||||
media_id: &body.media_id,
|
||||
};
|
||||
|
||||
let FileMeta {
|
||||
content,
|
||||
content_type,
|
||||
content_disposition,
|
||||
}) = services().media.get(&mxc).await?
|
||||
{
|
||||
let content_disposition = Some(make_content_disposition(
|
||||
&content_type,
|
||||
content_disposition,
|
||||
Some(body.filename.clone()),
|
||||
));
|
||||
} = fetch_file(&services, &mxc, user, body.timeout_ms, Some(&body.filename)).await?;
|
||||
|
||||
let file = content.expect("content");
|
||||
Ok(get_content_as_filename::v3::Response {
|
||||
file,
|
||||
content_type,
|
||||
content_disposition,
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
|
||||
})
|
||||
} else if !server_is_ours(&body.server_name) && body.allow_remote {
|
||||
match get_remote_content(
|
||||
&mxc,
|
||||
&body.server_name,
|
||||
body.media_id.clone(),
|
||||
body.allow_redirect,
|
||||
body.timeout_ms,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(remote_content_response) => {
|
||||
let content_disposition = Some(make_content_disposition(
|
||||
&remote_content_response.content_type,
|
||||
remote_content_response.content_disposition,
|
||||
None,
|
||||
));
|
||||
Ok(get_content_as_filename::v1::Response {
|
||||
file: content.expect("entire file contents"),
|
||||
content_type: content_type.map(Into::into),
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
|
||||
content_disposition,
|
||||
})
|
||||
}
|
||||
|
||||
Ok(get_content_as_filename::v3::Response {
|
||||
content_disposition,
|
||||
content_type: remote_content_response.content_type,
|
||||
file: remote_content_response.file,
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
|
||||
})
|
||||
},
|
||||
Err(e) => {
|
||||
debug_warn!("Fetching media `{}` failed: {:?}", mxc, e);
|
||||
Err(Error::BadRequest(ErrorKind::NotFound, "Remote media error."))
|
||||
},
|
||||
}
|
||||
} else {
|
||||
Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."))
|
||||
/// # `GET /_matrix/client/v1/media/preview_url`
|
||||
///
|
||||
/// Returns URL preview.
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "url_preview")]
|
||||
pub(crate) async fn get_media_preview_route(
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_media_preview::v1::Request>,
|
||||
) -> Result<get_media_preview::v1::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let url = &body.url;
|
||||
if !services.media.url_preview_allowed(url) {
|
||||
return Err!(Request(Forbidden(
|
||||
debug_warn!(%sender_user, %url, "URL is not allowed to be previewed")
|
||||
)));
|
||||
}
|
||||
|
||||
let preview = services.media.get_url_preview(url).await.map_err(|error| {
|
||||
err!(Request(Unknown(
|
||||
debug_error!(%sender_user, %url, ?error, "Failed to fetch URL preview.")
|
||||
)))
|
||||
})?;
|
||||
|
||||
serde_json::value::to_raw_value(&preview)
|
||||
.map(get_media_preview::v1::Response::from_raw_value)
|
||||
.map_err(|error| {
|
||||
err!(Request(Unknown(
|
||||
debug_error!(%sender_user, %url, ?error, "Failed to parse URL preview.")
|
||||
)))
|
||||
})
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v1/download/{serverName}/{mediaId}/{fileName}`
|
||||
///
|
||||
/// Load media from our server or over federation, permitting desired filename.
|
||||
///
|
||||
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
|
||||
/// clients may call. conduwuit adds these for compatibility purposes.
|
||||
/// See <https://spec.matrix.org/legacy/legacy/#id27>
|
||||
///
|
||||
/// - Only allows federation if `allow_remote` is true
|
||||
/// - Only redirects if `allow_redirect` is true
|
||||
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
|
||||
/// seconds
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_get")]
|
||||
pub(crate) async fn get_content_as_filename_v1_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<get_content_as_filename::v3::Request>,
|
||||
) -> Result<RumaResponse<get_content_as_filename::v3::Response>> {
|
||||
get_content_as_filename_route(InsecureClientIp(client), body)
|
||||
.await
|
||||
.map(RumaResponse)
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v3/thumbnail/{serverName}/{mediaId}`
|
||||
///
|
||||
/// Load media thumbnail from our server or over federation.
|
||||
///
|
||||
/// - Only allows federation if `allow_remote` is true
|
||||
/// - Only redirects if `allow_redirect` is true
|
||||
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
|
||||
/// seconds
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_thumbnail_get")]
|
||||
pub(crate) async fn get_content_thumbnail_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<get_content_thumbnail::v3::Request>,
|
||||
) -> Result<get_content_thumbnail::v3::Response> {
|
||||
let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
|
||||
|
||||
if let Some(FileMeta {
|
||||
async fn fetch_thumbnail(
|
||||
services: &Services, mxc: &Mxc<'_>, user: &UserId, timeout_ms: Duration, dim: &Dim,
|
||||
) -> Result<FileMeta> {
|
||||
let FileMeta {
|
||||
content,
|
||||
content_type,
|
||||
content_disposition,
|
||||
}) = services()
|
||||
.media
|
||||
.get_thumbnail(
|
||||
&mxc,
|
||||
body.width
|
||||
.try_into()
|
||||
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Width is invalid."))?,
|
||||
body.height
|
||||
.try_into()
|
||||
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Height is invalid."))?,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
let content_disposition = Some(make_content_disposition(&content_type, content_disposition, None));
|
||||
let file = content.expect("content");
|
||||
|
||||
Ok(get_content_thumbnail::v3::Response {
|
||||
file,
|
||||
content_type,
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
|
||||
content_disposition,
|
||||
})
|
||||
} else if !server_is_ours(&body.server_name) && body.allow_remote {
|
||||
if services()
|
||||
.globals
|
||||
.prevent_media_downloads_from()
|
||||
.contains(&body.server_name)
|
||||
{
|
||||
// we'll lie to the client and say the blocked server's media was not found and
|
||||
// log. the client has no way of telling anyways so this is a security bonus.
|
||||
debug_warn!("Received request for media `{}` on blocklisted server", mxc);
|
||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."));
|
||||
}
|
||||
|
||||
match services()
|
||||
.sending
|
||||
.send_federation_request(
|
||||
&body.server_name,
|
||||
get_content_thumbnail::v3::Request {
|
||||
allow_remote: body.allow_remote,
|
||||
height: body.height,
|
||||
width: body.width,
|
||||
method: body.method.clone(),
|
||||
server_name: body.server_name.clone(),
|
||||
media_id: body.media_id.clone(),
|
||||
timeout_ms: body.timeout_ms,
|
||||
allow_redirect: body.allow_redirect,
|
||||
animated: body.animated,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(get_thumbnail_response) => {
|
||||
services()
|
||||
.media
|
||||
.upload_thumbnail(
|
||||
None,
|
||||
&mxc,
|
||||
None,
|
||||
get_thumbnail_response.content_type.as_deref(),
|
||||
body.width.try_into().expect("all UInts are valid u32s"),
|
||||
body.height.try_into().expect("all UInts are valid u32s"),
|
||||
&get_thumbnail_response.file,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let content_disposition = Some(make_content_disposition(
|
||||
&get_thumbnail_response.content_type,
|
||||
get_thumbnail_response.content_disposition,
|
||||
None,
|
||||
));
|
||||
|
||||
Ok(get_content_thumbnail::v3::Response {
|
||||
file: get_thumbnail_response.file,
|
||||
content_type: get_thumbnail_response.content_type,
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.to_owned()),
|
||||
content_disposition,
|
||||
})
|
||||
},
|
||||
Err(e) => {
|
||||
debug_warn!("Fetching media `{}` failed: {:?}", mxc, e);
|
||||
Err(Error::BadRequest(ErrorKind::NotFound, "Remote media error."))
|
||||
},
|
||||
}
|
||||
} else {
|
||||
Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."))
|
||||
}
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v1/thumbnail/{serverName}/{mediaId}`
|
||||
///
|
||||
/// Load media thumbnail from our server or over federation.
|
||||
///
|
||||
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
|
||||
/// clients may call. conduwuit adds these for compatibility purposes.
|
||||
/// See <https://spec.matrix.org/legacy/legacy/#id27>
|
||||
///
|
||||
/// - Only allows federation if `allow_remote` is true
|
||||
/// - Only redirects if `allow_redirect` is true
|
||||
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
|
||||
/// seconds
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_thumbnail_get")]
|
||||
pub(crate) async fn get_content_thumbnail_v1_route(
|
||||
InsecureClientIp(client): InsecureClientIp, body: Ruma<get_content_thumbnail::v3::Request>,
|
||||
) -> Result<RumaResponse<get_content_thumbnail::v3::Response>> {
|
||||
get_content_thumbnail_route(InsecureClientIp(client), body)
|
||||
.await
|
||||
.map(RumaResponse)
|
||||
}
|
||||
|
||||
async fn get_remote_content(
|
||||
mxc: &str, server_name: &ruma::ServerName, media_id: String, allow_redirect: bool, timeout_ms: Duration,
|
||||
) -> Result<get_content::v3::Response, Error> {
|
||||
if services()
|
||||
.globals
|
||||
.prevent_media_downloads_from()
|
||||
.contains(&server_name.to_owned())
|
||||
{
|
||||
// we'll lie to the client and say the blocked server's media was not found and
|
||||
// log. the client has no way of telling anyways so this is a security bonus.
|
||||
debug_warn!("Received request for media `{mxc}` on blocklisted server");
|
||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."));
|
||||
}
|
||||
|
||||
let content_response = services()
|
||||
.sending
|
||||
.send_federation_request(
|
||||
server_name,
|
||||
get_content::v3::Request {
|
||||
allow_remote: true,
|
||||
server_name: server_name.to_owned(),
|
||||
media_id,
|
||||
timeout_ms,
|
||||
allow_redirect,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
} = fetch_thumbnail_meta(services, mxc, user, timeout_ms, dim).await?;
|
||||
|
||||
let content_disposition = Some(make_content_disposition(
|
||||
&content_response.content_type,
|
||||
content_response.content_disposition,
|
||||
content_disposition.as_ref(),
|
||||
content_type.as_deref(),
|
||||
None,
|
||||
));
|
||||
|
||||
services()
|
||||
.media
|
||||
.create(
|
||||
None,
|
||||
mxc,
|
||||
content_disposition.as_deref(),
|
||||
content_response.content_type.as_deref(),
|
||||
&content_response.file,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(get_content::v3::Response {
|
||||
file: content_response.file,
|
||||
content_type: content_response.content_type,
|
||||
Ok(FileMeta {
|
||||
content,
|
||||
content_type,
|
||||
content_disposition,
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.to_owned()),
|
||||
})
|
||||
}
|
||||
|
||||
async fn download_image(client: &reqwest::Client, url: &str) -> Result<UrlPreviewData> {
|
||||
let image = client.get(url).send().await?.bytes().await?;
|
||||
let mxc = format!(
|
||||
"mxc://{}/{}",
|
||||
services().globals.server_name(),
|
||||
utils::random_string(MXC_LENGTH)
|
||||
);
|
||||
async fn fetch_file(
|
||||
services: &Services, mxc: &Mxc<'_>, user: &UserId, timeout_ms: Duration, filename: Option<&str>,
|
||||
) -> Result<FileMeta> {
|
||||
let FileMeta {
|
||||
content,
|
||||
content_type,
|
||||
content_disposition,
|
||||
} = fetch_file_meta(services, mxc, user, timeout_ms).await?;
|
||||
|
||||
services()
|
||||
let content_disposition = Some(make_content_disposition(
|
||||
content_disposition.as_ref(),
|
||||
content_type.as_deref(),
|
||||
filename,
|
||||
));
|
||||
|
||||
Ok(FileMeta {
|
||||
content,
|
||||
content_type,
|
||||
content_disposition,
|
||||
})
|
||||
}
|
||||
|
||||
async fn fetch_thumbnail_meta(
|
||||
services: &Services, mxc: &Mxc<'_>, user: &UserId, timeout_ms: Duration, dim: &Dim,
|
||||
) -> Result<FileMeta> {
|
||||
if let Some(filemeta) = services.media.get_thumbnail(mxc, dim).await? {
|
||||
return Ok(filemeta);
|
||||
}
|
||||
|
||||
if services.globals.server_is_ours(mxc.server_name) {
|
||||
return Err!(Request(NotFound("Local thumbnail not found.")));
|
||||
}
|
||||
|
||||
services
|
||||
.media
|
||||
.create(None, &mxc, None, None, &image)
|
||||
.await?;
|
||||
|
||||
let (width, height) = match ImgReader::new(Cursor::new(&image)).with_guessed_format() {
|
||||
Err(_) => (None, None),
|
||||
Ok(reader) => match reader.into_dimensions() {
|
||||
Err(_) => (None, None),
|
||||
Ok((width, height)) => (Some(width), Some(height)),
|
||||
},
|
||||
};
|
||||
|
||||
Ok(UrlPreviewData {
|
||||
image: Some(mxc),
|
||||
image_size: Some(image.len()),
|
||||
image_width: width,
|
||||
image_height: height,
|
||||
..Default::default()
|
||||
})
|
||||
.fetch_remote_thumbnail(mxc, Some(user), None, timeout_ms, dim)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn download_html(client: &reqwest::Client, url: &str) -> Result<UrlPreviewData> {
|
||||
let mut response = client.get(url).send().await?;
|
||||
|
||||
let mut bytes: Vec<u8> = Vec::new();
|
||||
while let Some(chunk) = response.chunk().await? {
|
||||
bytes.extend_from_slice(&chunk);
|
||||
if bytes.len() > services().globals.url_preview_max_spider_size() {
|
||||
debug!(
|
||||
"Response body from URL {} exceeds url_preview_max_spider_size ({}), not processing the rest of the \
|
||||
response body and assuming our necessary data is in this range.",
|
||||
url,
|
||||
services().globals.url_preview_max_spider_size()
|
||||
);
|
||||
break;
|
||||
}
|
||||
async fn fetch_file_meta(services: &Services, mxc: &Mxc<'_>, user: &UserId, timeout_ms: Duration) -> Result<FileMeta> {
|
||||
if let Some(filemeta) = services.media.get(mxc).await? {
|
||||
return Ok(filemeta);
|
||||
}
|
||||
let body = String::from_utf8_lossy(&bytes);
|
||||
let Ok(html) = HTML::from_string(body.to_string(), Some(url.to_owned())) else {
|
||||
return Err(Error::BadRequest(ErrorKind::Unknown, "Failed to parse HTML"));
|
||||
};
|
||||
|
||||
let mut data = match html.opengraph.images.first() {
|
||||
None => UrlPreviewData::default(),
|
||||
Some(obj) => download_image(client, &obj.url).await?,
|
||||
};
|
||||
if services.globals.server_is_ours(mxc.server_name) {
|
||||
return Err!(Request(NotFound("Local media not found.")));
|
||||
}
|
||||
|
||||
let props = html.opengraph.properties;
|
||||
|
||||
/* use OpenGraph title/description, but fall back to HTML if not available */
|
||||
data.title = props.get("title").cloned().or(html.title);
|
||||
data.description = props.get("description").cloned().or(html.description);
|
||||
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
async fn request_url_preview(url: &str) -> Result<UrlPreviewData> {
|
||||
if let Ok(ip) = IPAddress::parse(url) {
|
||||
if !services().globals.valid_cidr_range(&ip) {
|
||||
return Err(Error::BadServerResponse("Requesting from this address is forbidden"));
|
||||
}
|
||||
}
|
||||
|
||||
let client = &services().globals.client.url_preview;
|
||||
let response = client.head(url).send().await?;
|
||||
|
||||
if let Some(remote_addr) = response.remote_addr() {
|
||||
if let Ok(ip) = IPAddress::parse(remote_addr.ip().to_string()) {
|
||||
if !services().globals.valid_cidr_range(&ip) {
|
||||
return Err(Error::BadServerResponse("Requesting from this address is forbidden"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(content_type) = response
|
||||
.headers()
|
||||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.and_then(|x| x.to_str().ok())
|
||||
else {
|
||||
return Err(Error::BadRequest(ErrorKind::Unknown, "Unknown Content-Type"));
|
||||
};
|
||||
let data = match content_type {
|
||||
html if html.starts_with("text/html") => download_html(client, url).await?,
|
||||
img if img.starts_with("image/") => download_image(client, url).await?,
|
||||
_ => return Err(Error::BadRequest(ErrorKind::Unknown, "Unsupported Content-Type")),
|
||||
};
|
||||
|
||||
services().media.set_url_preview(url, &data).await?;
|
||||
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
async fn get_url_preview(url: &str) -> Result<UrlPreviewData> {
|
||||
if let Some(preview) = services().media.get_url_preview(url).await {
|
||||
return Ok(preview);
|
||||
}
|
||||
|
||||
// ensure that only one request is made per URL
|
||||
let mutex_request = Arc::clone(
|
||||
services()
|
||||
.media
|
||||
.url_preview_mutex
|
||||
.write()
|
||||
.await
|
||||
.entry(url.to_owned())
|
||||
.or_default(),
|
||||
);
|
||||
let _request_lock = mutex_request.lock().await;
|
||||
|
||||
match services().media.get_url_preview(url).await {
|
||||
Some(preview) => Ok(preview),
|
||||
None => request_url_preview(url).await,
|
||||
}
|
||||
}
|
||||
|
||||
fn url_preview_allowed(url_str: &str) -> bool {
|
||||
let url: Url = match Url::parse(url_str) {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
warn!("Failed to parse URL from a str: {}", e);
|
||||
return false;
|
||||
},
|
||||
};
|
||||
|
||||
if ["http", "https"]
|
||||
.iter()
|
||||
.all(|&scheme| scheme != url.scheme().to_lowercase())
|
||||
{
|
||||
debug!("Ignoring non-HTTP/HTTPS URL to preview: {}", url);
|
||||
return false;
|
||||
}
|
||||
|
||||
let host = match url.host_str() {
|
||||
None => {
|
||||
debug!("Ignoring URL preview for a URL that does not have a host (?): {}", url);
|
||||
return false;
|
||||
},
|
||||
Some(h) => h.to_owned(),
|
||||
};
|
||||
|
||||
let allowlist_domain_contains = services().globals.url_preview_domain_contains_allowlist();
|
||||
let allowlist_domain_explicit = services().globals.url_preview_domain_explicit_allowlist();
|
||||
let denylist_domain_explicit = services().globals.url_preview_domain_explicit_denylist();
|
||||
let allowlist_url_contains = services().globals.url_preview_url_contains_allowlist();
|
||||
|
||||
if allowlist_domain_contains.contains(&"*".to_owned())
|
||||
|| allowlist_domain_explicit.contains(&"*".to_owned())
|
||||
|| allowlist_url_contains.contains(&"*".to_owned())
|
||||
{
|
||||
debug!("Config key contains * which is allowing all URL previews. Allowing URL {}", url);
|
||||
return true;
|
||||
}
|
||||
|
||||
if !host.is_empty() {
|
||||
if denylist_domain_explicit.contains(&host) {
|
||||
debug!(
|
||||
"Host {} is not allowed by url_preview_domain_explicit_denylist (check 1/4)",
|
||||
&host
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
if allowlist_domain_explicit.contains(&host) {
|
||||
debug!("Host {} is allowed by url_preview_domain_explicit_allowlist (check 2/4)", &host);
|
||||
return true;
|
||||
}
|
||||
|
||||
if allowlist_domain_contains
|
||||
.iter()
|
||||
.any(|domain_s| domain_s.contains(&host.clone()))
|
||||
{
|
||||
debug!("Host {} is allowed by url_preview_domain_contains_allowlist (check 3/4)", &host);
|
||||
return true;
|
||||
}
|
||||
|
||||
if allowlist_url_contains
|
||||
.iter()
|
||||
.any(|url_s| url.to_string().contains(&url_s.to_string()))
|
||||
{
|
||||
debug!("URL {} is allowed by url_preview_url_contains_allowlist (check 4/4)", &host);
|
||||
return true;
|
||||
}
|
||||
|
||||
// check root domain if available and if user has root domain checks
|
||||
if services().globals.url_preview_check_root_domain() {
|
||||
debug!("Checking root domain");
|
||||
match host.split_once('.') {
|
||||
None => return false,
|
||||
Some((_, root_domain)) => {
|
||||
if denylist_domain_explicit.contains(&root_domain.to_owned()) {
|
||||
debug!(
|
||||
"Root domain {} is not allowed by url_preview_domain_explicit_denylist (check 1/3)",
|
||||
&root_domain
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
if allowlist_domain_explicit.contains(&root_domain.to_owned()) {
|
||||
debug!(
|
||||
"Root domain {} is allowed by url_preview_domain_explicit_allowlist (check 2/3)",
|
||||
&root_domain
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
if allowlist_domain_contains
|
||||
.iter()
|
||||
.any(|domain_s| domain_s.contains(&root_domain.to_owned()))
|
||||
{
|
||||
debug!(
|
||||
"Root domain {} is allowed by url_preview_domain_contains_allowlist (check 3/3)",
|
||||
&root_domain
|
||||
);
|
||||
return true;
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
services
|
||||
.media
|
||||
.fetch_remote_content(mxc, Some(user), None, timeout_ms)
|
||||
.await
|
||||
}
|
||||
|
||||
343
src/api/client/media_legacy.rs
Normal file
343
src/api/client/media_legacy.rs
Normal file
@@ -0,0 +1,343 @@
|
||||
#![allow(deprecated)]
|
||||
|
||||
use axum::extract::State;
|
||||
use axum_client_ip::InsecureClientIp;
|
||||
use conduit::{
|
||||
err,
|
||||
utils::{content_disposition::make_content_disposition, math::ruma_from_usize},
|
||||
Err, Result,
|
||||
};
|
||||
use conduit_service::media::{Dim, FileMeta, CACHE_CONTROL_IMMUTABLE, CORP_CROSS_ORIGIN};
|
||||
use ruma::{
|
||||
api::client::media::{
|
||||
create_content, get_content, get_content_as_filename, get_content_thumbnail, get_media_config,
|
||||
get_media_preview,
|
||||
},
|
||||
Mxc,
|
||||
};
|
||||
|
||||
use crate::{client::create_content_route, Ruma, RumaResponse};
|
||||
|
||||
/// # `GET /_matrix/media/v3/config`
|
||||
///
|
||||
/// Returns max upload size.
|
||||
pub(crate) async fn get_media_config_legacy_route(
|
||||
State(services): State<crate::State>, _body: Ruma<get_media_config::v3::Request>,
|
||||
) -> Result<get_media_config::v3::Response> {
|
||||
Ok(get_media_config::v3::Response {
|
||||
upload_size: ruma_from_usize(services.globals.config.max_request_size),
|
||||
})
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v1/config`
|
||||
///
|
||||
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
|
||||
/// clients may call. conduwuit adds these for compatibility purposes.
|
||||
/// See <https://spec.matrix.org/legacy/legacy/#id27>
|
||||
///
|
||||
/// Returns max upload size.
|
||||
pub(crate) async fn get_media_config_legacy_legacy_route(
|
||||
State(services): State<crate::State>, body: Ruma<get_media_config::v3::Request>,
|
||||
) -> Result<RumaResponse<get_media_config::v3::Response>> {
|
||||
get_media_config_legacy_route(State(services), body)
|
||||
.await
|
||||
.map(RumaResponse)
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v3/preview_url`
|
||||
///
|
||||
/// Returns URL preview.
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "url_preview_legacy")]
|
||||
pub(crate) async fn get_media_preview_legacy_route(
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_media_preview::v3::Request>,
|
||||
) -> Result<get_media_preview::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let url = &body.url;
|
||||
if !services.media.url_preview_allowed(url) {
|
||||
return Err!(Request(Forbidden(
|
||||
debug_warn!(%sender_user, %url, "URL is not allowed to be previewed")
|
||||
)));
|
||||
}
|
||||
|
||||
let preview = services.media.get_url_preview(url).await.map_err(|e| {
|
||||
err!(Request(Unknown(
|
||||
debug_error!(%sender_user, %url, "Failed to fetch a URL preview: {e}")
|
||||
)))
|
||||
})?;
|
||||
|
||||
let res = serde_json::value::to_raw_value(&preview).map_err(|e| {
|
||||
err!(Request(Unknown(
|
||||
debug_error!(%sender_user, %url, "Failed to parse a URL preview: {e}")
|
||||
)))
|
||||
})?;
|
||||
|
||||
Ok(get_media_preview::v3::Response::from_raw_value(res))
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v1/preview_url`
|
||||
///
|
||||
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
|
||||
/// clients may call. conduwuit adds these for compatibility purposes.
|
||||
/// See <https://spec.matrix.org/legacy/legacy/#id27>
|
||||
///
|
||||
/// Returns URL preview.
|
||||
pub(crate) async fn get_media_preview_legacy_legacy_route(
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_media_preview::v3::Request>,
|
||||
) -> Result<RumaResponse<get_media_preview::v3::Response>> {
|
||||
get_media_preview_legacy_route(State(services), InsecureClientIp(client), body)
|
||||
.await
|
||||
.map(RumaResponse)
|
||||
}
|
||||
|
||||
/// # `POST /_matrix/media/v1/upload`
|
||||
///
|
||||
/// Permanently save media in the server.
|
||||
///
|
||||
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
|
||||
/// clients may call. conduwuit adds these for compatibility purposes.
|
||||
/// See <https://spec.matrix.org/legacy/legacy/#id27>
|
||||
///
|
||||
/// - Some metadata will be saved in the database
|
||||
/// - Media will be saved in the media/ directory
|
||||
pub(crate) async fn create_content_legacy_route(
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<create_content::v3::Request>,
|
||||
) -> Result<RumaResponse<create_content::v3::Response>> {
|
||||
create_content_route(State(services), InsecureClientIp(client), body)
|
||||
.await
|
||||
.map(RumaResponse)
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}`
|
||||
///
|
||||
/// Load media from our server or over federation.
|
||||
///
|
||||
/// - Only allows federation if `allow_remote` is true
|
||||
/// - Only redirects if `allow_redirect` is true
|
||||
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
|
||||
/// seconds
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_get_legacy")]
|
||||
pub(crate) async fn get_content_legacy_route(
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_content::v3::Request>,
|
||||
) -> Result<get_content::v3::Response> {
|
||||
let mxc = Mxc {
|
||||
server_name: &body.server_name,
|
||||
media_id: &body.media_id,
|
||||
};
|
||||
|
||||
if let Some(FileMeta {
|
||||
content,
|
||||
content_type,
|
||||
content_disposition,
|
||||
}) = services.media.get(&mxc).await?
|
||||
{
|
||||
let content_disposition = make_content_disposition(content_disposition.as_ref(), content_type.as_deref(), None);
|
||||
|
||||
Ok(get_content::v3::Response {
|
||||
file: content.expect("entire file contents"),
|
||||
content_type: content_type.map(Into::into),
|
||||
content_disposition: Some(content_disposition),
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
|
||||
})
|
||||
} else if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
|
||||
let response = services
|
||||
.media
|
||||
.fetch_remote_content_legacy(&mxc, body.allow_redirect, body.timeout_ms)
|
||||
.await
|
||||
.map_err(|e| err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}")))))?;
|
||||
|
||||
let content_disposition =
|
||||
make_content_disposition(response.content_disposition.as_ref(), response.content_type.as_deref(), None);
|
||||
|
||||
Ok(get_content::v3::Response {
|
||||
file: response.file,
|
||||
content_type: response.content_type,
|
||||
content_disposition: Some(content_disposition),
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
|
||||
})
|
||||
} else {
|
||||
Err!(Request(NotFound("Media not found.")))
|
||||
}
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v1/download/{serverName}/{mediaId}`
|
||||
///
|
||||
/// Load media from our server or over federation.
|
||||
///
|
||||
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
|
||||
/// clients may call. conduwuit adds these for compatibility purposes.
|
||||
/// See <https://spec.matrix.org/legacy/legacy/#id27>
|
||||
///
|
||||
/// - Only allows federation if `allow_remote` is true
|
||||
/// - Only redirects if `allow_redirect` is true
|
||||
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
|
||||
/// seconds
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_get_legacy")]
|
||||
pub(crate) async fn get_content_legacy_legacy_route(
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_content::v3::Request>,
|
||||
) -> Result<RumaResponse<get_content::v3::Response>> {
|
||||
get_content_legacy_route(State(services), InsecureClientIp(client), body)
|
||||
.await
|
||||
.map(RumaResponse)
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}/{fileName}`
|
||||
///
|
||||
/// Load media from our server or over federation, permitting desired filename.
|
||||
///
|
||||
/// - Only allows federation if `allow_remote` is true
|
||||
/// - Only redirects if `allow_redirect` is true
|
||||
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
|
||||
/// seconds
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_get_legacy")]
|
||||
pub(crate) async fn get_content_as_filename_legacy_route(
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_content_as_filename::v3::Request>,
|
||||
) -> Result<get_content_as_filename::v3::Response> {
|
||||
let mxc = Mxc {
|
||||
server_name: &body.server_name,
|
||||
media_id: &body.media_id,
|
||||
};
|
||||
|
||||
if let Some(FileMeta {
|
||||
content,
|
||||
content_type,
|
||||
content_disposition,
|
||||
}) = services.media.get(&mxc).await?
|
||||
{
|
||||
let content_disposition =
|
||||
make_content_disposition(content_disposition.as_ref(), content_type.as_deref(), Some(&body.filename));
|
||||
|
||||
Ok(get_content_as_filename::v3::Response {
|
||||
file: content.expect("entire file contents"),
|
||||
content_type: content_type.map(Into::into),
|
||||
content_disposition: Some(content_disposition),
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
|
||||
})
|
||||
} else if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
|
||||
let response = services
|
||||
.media
|
||||
.fetch_remote_content_legacy(&mxc, body.allow_redirect, body.timeout_ms)
|
||||
.await
|
||||
.map_err(|e| err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}")))))?;
|
||||
|
||||
let content_disposition =
|
||||
make_content_disposition(response.content_disposition.as_ref(), response.content_type.as_deref(), None);
|
||||
|
||||
Ok(get_content_as_filename::v3::Response {
|
||||
content_disposition: Some(content_disposition),
|
||||
content_type: response.content_type,
|
||||
file: response.file,
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
|
||||
})
|
||||
} else {
|
||||
Err!(Request(NotFound("Media not found.")))
|
||||
}
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v1/download/{serverName}/{mediaId}/{fileName}`
|
||||
///
|
||||
/// Load media from our server or over federation, permitting desired filename.
|
||||
///
|
||||
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
|
||||
/// clients may call. conduwuit adds these for compatibility purposes.
|
||||
/// See <https://spec.matrix.org/legacy/legacy/#id27>
|
||||
///
|
||||
/// - Only allows federation if `allow_remote` is true
|
||||
/// - Only redirects if `allow_redirect` is true
|
||||
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
|
||||
/// seconds
|
||||
pub(crate) async fn get_content_as_filename_legacy_legacy_route(
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_content_as_filename::v3::Request>,
|
||||
) -> Result<RumaResponse<get_content_as_filename::v3::Response>> {
|
||||
get_content_as_filename_legacy_route(State(services), InsecureClientIp(client), body)
|
||||
.await
|
||||
.map(RumaResponse)
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v3/thumbnail/{serverName}/{mediaId}`
|
||||
///
|
||||
/// Load media thumbnail from our server or over federation.
|
||||
///
|
||||
/// - Only allows federation if `allow_remote` is true
|
||||
/// - Only redirects if `allow_redirect` is true
|
||||
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
|
||||
/// seconds
|
||||
#[tracing::instrument(skip_all, fields(%client), name = "media_thumbnail_get_legacy")]
|
||||
pub(crate) async fn get_content_thumbnail_legacy_route(
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_content_thumbnail::v3::Request>,
|
||||
) -> Result<get_content_thumbnail::v3::Response> {
|
||||
let mxc = Mxc {
|
||||
server_name: &body.server_name,
|
||||
media_id: &body.media_id,
|
||||
};
|
||||
|
||||
let dim = Dim::from_ruma(body.width, body.height, body.method.clone())?;
|
||||
if let Some(FileMeta {
|
||||
content,
|
||||
content_type,
|
||||
content_disposition,
|
||||
}) = services.media.get_thumbnail(&mxc, &dim).await?
|
||||
{
|
||||
let content_disposition = make_content_disposition(content_disposition.as_ref(), content_type.as_deref(), None);
|
||||
|
||||
Ok(get_content_thumbnail::v3::Response {
|
||||
file: content.expect("entire file contents"),
|
||||
content_type: content_type.map(Into::into),
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
|
||||
content_disposition: Some(content_disposition),
|
||||
})
|
||||
} else if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
|
||||
let response = services
|
||||
.media
|
||||
.fetch_remote_thumbnail_legacy(&body)
|
||||
.await
|
||||
.map_err(|e| err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}")))))?;
|
||||
|
||||
let content_disposition =
|
||||
make_content_disposition(response.content_disposition.as_ref(), response.content_type.as_deref(), None);
|
||||
|
||||
Ok(get_content_thumbnail::v3::Response {
|
||||
file: response.file,
|
||||
content_type: response.content_type,
|
||||
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
|
||||
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
|
||||
content_disposition: Some(content_disposition),
|
||||
})
|
||||
} else {
|
||||
Err!(Request(NotFound("Media not found.")))
|
||||
}
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/media/v1/thumbnail/{serverName}/{mediaId}`
|
||||
///
|
||||
/// Load media thumbnail from our server or over federation.
|
||||
///
|
||||
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
|
||||
/// clients may call. conduwuit adds these for compatibility purposes.
|
||||
/// See <https://spec.matrix.org/legacy/legacy/#id27>
|
||||
///
|
||||
/// - Only allows federation if `allow_remote` is true
|
||||
/// - Only redirects if `allow_redirect` is true
|
||||
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
|
||||
/// seconds
|
||||
pub(crate) async fn get_content_thumbnail_legacy_legacy_route(
|
||||
State(services): State<crate::State>, InsecureClientIp(client): InsecureClientIp,
|
||||
body: Ruma<get_content_thumbnail::v3::Request>,
|
||||
) -> Result<RumaResponse<get_content_thumbnail::v3::Response>> {
|
||||
get_content_thumbnail_legacy_route(State(services), InsecureClientIp(client), body)
|
||||
.await
|
||||
.map(RumaResponse)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,6 @@
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use axum::extract::State;
|
||||
use conduit::PduCount;
|
||||
use ruma::{
|
||||
api::client::{
|
||||
@@ -12,7 +13,10 @@
|
||||
};
|
||||
use serde_json::{from_str, Value};
|
||||
|
||||
use crate::{service::pdu::PduBuilder, services, utils, Error, PduEvent, Result, Ruma};
|
||||
use crate::{
|
||||
service::{pdu::PduBuilder, Services},
|
||||
utils, Error, PduEvent, Result, Ruma,
|
||||
};
|
||||
|
||||
/// # `PUT /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId}`
|
||||
///
|
||||
@@ -24,21 +28,19 @@
|
||||
/// - Tries to send the event into the room, auth rules will determine if it is
|
||||
/// allowed
|
||||
pub(crate) async fn send_message_event_route(
|
||||
body: Ruma<send_message_event::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<send_message_event::v3::Request>,
|
||||
) -> Result<send_message_event::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let sender_device = body.sender_device.as_deref();
|
||||
|
||||
let state_lock = services().rooms.state.mutex.lock(&body.room_id).await;
|
||||
let state_lock = services.rooms.state.mutex.lock(&body.room_id).await;
|
||||
|
||||
// Forbid m.room.encrypted if encryption is disabled
|
||||
if MessageLikeEventType::RoomEncrypted == body.event_type && !services().globals.allow_encryption() {
|
||||
if MessageLikeEventType::RoomEncrypted == body.event_type && !services.globals.allow_encryption() {
|
||||
return Err(Error::BadRequest(ErrorKind::forbidden(), "Encryption has been disabled"));
|
||||
}
|
||||
|
||||
if body.event_type == MessageLikeEventType::CallInvite
|
||||
&& services().rooms.directory.is_public_room(&body.room_id)?
|
||||
{
|
||||
if body.event_type == MessageLikeEventType::CallInvite && services.rooms.directory.is_public_room(&body.room_id)? {
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::forbidden(),
|
||||
"Room call invites are not allowed in public rooms",
|
||||
@@ -46,7 +48,7 @@ pub(crate) async fn send_message_event_route(
|
||||
}
|
||||
|
||||
// Check if this is a new transaction id
|
||||
if let Some(response) = services()
|
||||
if let Some(response) = services
|
||||
.transaction_ids
|
||||
.existing_txnid(sender_user, sender_device, &body.txn_id)?
|
||||
{
|
||||
@@ -71,7 +73,7 @@ pub(crate) async fn send_message_event_route(
|
||||
let mut unsigned = BTreeMap::new();
|
||||
unsigned.insert("transaction_id".to_owned(), body.txn_id.to_string().into());
|
||||
|
||||
let event_id = services()
|
||||
let event_id = services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -82,6 +84,11 @@ pub(crate) async fn send_message_event_route(
|
||||
unsigned: Some(unsigned),
|
||||
state_key: None,
|
||||
redacts: None,
|
||||
timestamp: if body.appservice_info.is_some() {
|
||||
body.timestamp
|
||||
} else {
|
||||
None
|
||||
},
|
||||
},
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
@@ -89,7 +96,7 @@ pub(crate) async fn send_message_event_route(
|
||||
)
|
||||
.await?;
|
||||
|
||||
services()
|
||||
services
|
||||
.transaction_ids
|
||||
.add_txnid(sender_user, sender_device, &body.txn_id, event_id.as_bytes())?;
|
||||
|
||||
@@ -105,7 +112,7 @@ pub(crate) async fn send_message_event_route(
|
||||
/// - Only works if the user is joined (TODO: always allow, but only show events
|
||||
/// where the user was joined, depending on `history_visibility`)
|
||||
pub(crate) async fn get_message_events_route(
|
||||
body: Ruma<get_message_events::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_message_events::v3::Request>,
|
||||
) -> Result<get_message_events::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
|
||||
@@ -123,7 +130,7 @@ pub(crate) async fn get_message_events_route(
|
||||
.as_ref()
|
||||
.and_then(|t| PduCount::try_from_string(t).ok());
|
||||
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.lazy_loading
|
||||
.lazy_load_confirm_delivery(sender_user, sender_device, &body.room_id, from)
|
||||
@@ -139,12 +146,12 @@ pub(crate) async fn get_message_events_route(
|
||||
|
||||
match body.dir {
|
||||
ruma::api::Direction::Forward => {
|
||||
let events_after: Vec<_> = services()
|
||||
let events_after: Vec<_> = services
|
||||
.rooms
|
||||
.timeline
|
||||
.pdus_after(sender_user, &body.room_id, from)?
|
||||
.filter_map(Result::ok) // Filter out buggy events
|
||||
.filter(|(_, pdu)| { contains_url_filter(pdu, &body.filter) && visibility_filter(pdu, sender_user, &body.room_id)
|
||||
.filter(|(_, pdu)| { contains_url_filter(pdu, &body.filter) && visibility_filter(&services, pdu, sender_user, &body.room_id)
|
||||
|
||||
})
|
||||
.take_while(|&(k, _)| Some(k) != to) // Stop at `to`
|
||||
@@ -157,7 +164,7 @@ pub(crate) async fn get_message_events_route(
|
||||
* https://github.com/vector-im/element-web/issues/21034
|
||||
*/
|
||||
if !cfg!(feature = "element_hacks")
|
||||
&& !services().rooms.lazy_loading.lazy_load_was_sent_before(
|
||||
&& !services.rooms.lazy_loading.lazy_load_was_sent_before(
|
||||
sender_user,
|
||||
sender_device,
|
||||
&body.room_id,
|
||||
@@ -181,17 +188,17 @@ pub(crate) async fn get_message_events_route(
|
||||
resp.chunk = events_after;
|
||||
},
|
||||
ruma::api::Direction::Backward => {
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.backfill_if_required(&body.room_id, from)
|
||||
.await?;
|
||||
let events_before: Vec<_> = services()
|
||||
let events_before: Vec<_> = services
|
||||
.rooms
|
||||
.timeline
|
||||
.pdus_until(sender_user, &body.room_id, from)?
|
||||
.filter_map(Result::ok) // Filter out buggy events
|
||||
.filter(|(_, pdu)| {contains_url_filter(pdu, &body.filter) && visibility_filter(pdu, sender_user, &body.room_id)})
|
||||
.filter(|(_, pdu)| {contains_url_filter(pdu, &body.filter) && visibility_filter(&services, pdu, sender_user, &body.room_id)})
|
||||
.take_while(|&(k, _)| Some(k) != to) // Stop at `to`
|
||||
.take(limit)
|
||||
.collect();
|
||||
@@ -202,7 +209,7 @@ pub(crate) async fn get_message_events_route(
|
||||
* https://github.com/vector-im/element-web/issues/21034
|
||||
*/
|
||||
if !cfg!(feature = "element_hacks")
|
||||
&& !services().rooms.lazy_loading.lazy_load_was_sent_before(
|
||||
&& !services.rooms.lazy_loading.lazy_load_was_sent_before(
|
||||
sender_user,
|
||||
sender_device,
|
||||
&body.room_id,
|
||||
@@ -229,11 +236,12 @@ pub(crate) async fn get_message_events_route(
|
||||
|
||||
resp.state = Vec::new();
|
||||
for ll_id in &lazy_loaded {
|
||||
if let Some(member_event) = services().rooms.state_accessor.room_state_get(
|
||||
&body.room_id,
|
||||
&StateEventType::RoomMember,
|
||||
ll_id.as_str(),
|
||||
)? {
|
||||
if let Some(member_event) =
|
||||
services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.room_state_get(&body.room_id, &StateEventType::RoomMember, ll_id.as_str())?
|
||||
{
|
||||
resp.state.push(member_event.to_state_event());
|
||||
}
|
||||
}
|
||||
@@ -241,7 +249,7 @@ pub(crate) async fn get_message_events_route(
|
||||
// remove the feature check when we are sure clients like element can handle it
|
||||
if !cfg!(feature = "element_hacks") {
|
||||
if let Some(next_token) = next_token {
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.lazy_loading
|
||||
.lazy_load_mark_sent(sender_user, sender_device, &body.room_id, lazy_loaded, next_token)
|
||||
@@ -252,8 +260,8 @@ pub(crate) async fn get_message_events_route(
|
||||
Ok(resp)
|
||||
}
|
||||
|
||||
fn visibility_filter(pdu: &PduEvent, user_id: &UserId, room_id: &RoomId) -> bool {
|
||||
services()
|
||||
fn visibility_filter(services: &Services, pdu: &PduEvent, user_id: &UserId, room_id: &RoomId) -> bool {
|
||||
services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.user_can_see_event(user_id, room_id, &pdu.event_id)
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
pub(super) mod filter;
|
||||
pub(super) mod keys;
|
||||
pub(super) mod media;
|
||||
pub(super) mod media_legacy;
|
||||
pub(super) mod membership;
|
||||
pub(super) mod message;
|
||||
pub(super) mod openid;
|
||||
@@ -46,6 +47,7 @@
|
||||
pub(super) use filter::*;
|
||||
pub(super) use keys::*;
|
||||
pub(super) use media::*;
|
||||
pub(super) use media_legacy::*;
|
||||
pub(super) use membership::*;
|
||||
pub use membership::{join_room_by_id_helper, leave_all_rooms, leave_room, validate_and_add_event_id};
|
||||
pub(super) use message::*;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::State;
|
||||
use conduit::utils;
|
||||
use ruma::{
|
||||
api::client::{account, error::ErrorKind},
|
||||
@@ -7,7 +8,7 @@
|
||||
};
|
||||
|
||||
use super::TOKEN_LENGTH;
|
||||
use crate::{services, Error, Result, Ruma};
|
||||
use crate::{Error, Result, Ruma};
|
||||
|
||||
/// # `POST /_matrix/client/v3/user/{userId}/openid/request_token`
|
||||
///
|
||||
@@ -15,7 +16,7 @@
|
||||
///
|
||||
/// - The token generated is only valid for the OpenID API
|
||||
pub(crate) async fn create_openid_token_route(
|
||||
body: Ruma<account::request_openid_token::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<account::request_openid_token::v3::Request>,
|
||||
) -> Result<account::request_openid_token::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
@@ -28,14 +29,14 @@ pub(crate) async fn create_openid_token_route(
|
||||
|
||||
let access_token = utils::random_string(TOKEN_LENGTH);
|
||||
|
||||
let expires_in = services()
|
||||
let expires_in = services
|
||||
.users
|
||||
.create_openid_token(&body.user_id, &access_token)?;
|
||||
|
||||
Ok(account::request_openid_token::v3::Response {
|
||||
access_token,
|
||||
token_type: TokenType::Bearer,
|
||||
matrix_server_name: services().globals.config.server_name.clone(),
|
||||
matrix_server_name: services.globals.config.server_name.clone(),
|
||||
expires_in: Duration::from_secs(expires_in),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,22 +1,32 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::State;
|
||||
use ruma::api::client::{
|
||||
error::ErrorKind,
|
||||
presence::{get_presence, set_presence},
|
||||
};
|
||||
|
||||
use crate::{services, Error, Result, Ruma};
|
||||
use crate::{Error, Result, Ruma};
|
||||
|
||||
/// # `PUT /_matrix/client/r0/presence/{userId}/status`
|
||||
///
|
||||
/// Sets the presence state of the sender user.
|
||||
pub(crate) async fn set_presence_route(body: Ruma<set_presence::v3::Request>) -> Result<set_presence::v3::Response> {
|
||||
if !services().globals.allow_local_presence() {
|
||||
pub(crate) async fn set_presence_route(
|
||||
State(services): State<crate::State>, body: Ruma<set_presence::v3::Request>,
|
||||
) -> Result<set_presence::v3::Response> {
|
||||
if !services.globals.allow_local_presence() {
|
||||
return Err(Error::BadRequest(ErrorKind::forbidden(), "Presence is disabled on this server"));
|
||||
}
|
||||
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
services()
|
||||
if sender_user != &body.user_id && body.appservice_info.is_none() {
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::InvalidParam,
|
||||
"Not allowed to set presence of other users",
|
||||
));
|
||||
}
|
||||
|
||||
services
|
||||
.presence
|
||||
.set_presence(sender_user, &body.presence, None, None, body.status_msg.clone())?;
|
||||
|
||||
@@ -28,8 +38,10 @@ pub(crate) async fn set_presence_route(body: Ruma<set_presence::v3::Request>) ->
|
||||
/// Gets the presence state of the given user.
|
||||
///
|
||||
/// - Only works if you share a room with the user
|
||||
pub(crate) async fn get_presence_route(body: Ruma<get_presence::v3::Request>) -> Result<get_presence::v3::Response> {
|
||||
if !services().globals.allow_local_presence() {
|
||||
pub(crate) async fn get_presence_route(
|
||||
State(services): State<crate::State>, body: Ruma<get_presence::v3::Request>,
|
||||
) -> Result<get_presence::v3::Response> {
|
||||
if !services.globals.allow_local_presence() {
|
||||
return Err(Error::BadRequest(ErrorKind::forbidden(), "Presence is disabled on this server"));
|
||||
}
|
||||
|
||||
@@ -37,12 +49,12 @@ pub(crate) async fn get_presence_route(body: Ruma<get_presence::v3::Request>) ->
|
||||
|
||||
let mut presence_event = None;
|
||||
|
||||
for _room_id in services()
|
||||
for _room_id in services
|
||||
.rooms
|
||||
.user
|
||||
.get_shared_rooms(vec![sender_user.clone(), body.user_id.clone()])?
|
||||
{
|
||||
if let Some(presence) = services().presence.get_presence(&body.user_id)? {
|
||||
if let Some(presence) = services.presence.get_presence(&body.user_id)? {
|
||||
presence_event = Some(presence);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use axum::extract::State;
|
||||
use conduit::{pdu::PduBuilder, warn, Error, Result};
|
||||
use ruma::{
|
||||
api::{
|
||||
client::{
|
||||
@@ -11,12 +13,9 @@
|
||||
OwnedMxcUri, OwnedRoomId, OwnedUserId,
|
||||
};
|
||||
use serde_json::value::to_raw_value;
|
||||
use tracing::warn;
|
||||
use service::Services;
|
||||
|
||||
use crate::{
|
||||
service::{pdu::PduBuilder, user_is_local},
|
||||
services, Error, Result, Ruma,
|
||||
};
|
||||
use crate::Ruma;
|
||||
|
||||
/// # `PUT /_matrix/client/r0/profile/{userId}/displayname`
|
||||
///
|
||||
@@ -24,21 +23,21 @@
|
||||
///
|
||||
/// - Also makes sure other users receive the update using presence EDUs
|
||||
pub(crate) async fn set_displayname_route(
|
||||
body: Ruma<set_display_name::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<set_display_name::v3::Request>,
|
||||
) -> Result<set_display_name::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let all_joined_rooms: Vec<OwnedRoomId> = services()
|
||||
let all_joined_rooms: Vec<OwnedRoomId> = services
|
||||
.rooms
|
||||
.state_cache
|
||||
.rooms_joined(sender_user)
|
||||
.filter_map(Result::ok)
|
||||
.collect();
|
||||
|
||||
update_displayname(sender_user.clone(), body.displayname.clone(), all_joined_rooms).await?;
|
||||
update_displayname(&services, sender_user.clone(), body.displayname.clone(), all_joined_rooms).await?;
|
||||
|
||||
if services().globals.allow_local_presence() {
|
||||
if services.globals.allow_local_presence() {
|
||||
// Presence update
|
||||
services()
|
||||
services
|
||||
.presence
|
||||
.ping_presence(sender_user, &PresenceState::Online)?;
|
||||
}
|
||||
@@ -53,11 +52,11 @@ pub(crate) async fn set_displayname_route(
|
||||
/// - If user is on another server and we do not have a local copy already fetch
|
||||
/// displayname over federation
|
||||
pub(crate) async fn get_displayname_route(
|
||||
body: Ruma<get_display_name::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_display_name::v3::Request>,
|
||||
) -> Result<get_display_name::v3::Response> {
|
||||
if !user_is_local(&body.user_id) {
|
||||
if !services.globals.user_is_local(&body.user_id) {
|
||||
// Create and update our local copy of the user
|
||||
if let Ok(response) = services()
|
||||
if let Ok(response) = services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
body.user_id.server_name(),
|
||||
@@ -68,19 +67,19 @@ pub(crate) async fn get_displayname_route(
|
||||
)
|
||||
.await
|
||||
{
|
||||
if !services().users.exists(&body.user_id)? {
|
||||
services().users.create(&body.user_id, None)?;
|
||||
if !services.users.exists(&body.user_id)? {
|
||||
services.users.create(&body.user_id, None)?;
|
||||
}
|
||||
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.set_displayname(&body.user_id, response.displayname.clone())
|
||||
.await?;
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.set_avatar_url(&body.user_id, response.avatar_url.clone())
|
||||
.await?;
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.set_blurhash(&body.user_id, response.blurhash.clone())
|
||||
.await?;
|
||||
@@ -91,14 +90,14 @@ pub(crate) async fn get_displayname_route(
|
||||
}
|
||||
}
|
||||
|
||||
if !services().users.exists(&body.user_id)? {
|
||||
if !services.users.exists(&body.user_id)? {
|
||||
// Return 404 if this user doesn't exist and we couldn't fetch it over
|
||||
// federation
|
||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Profile was not found."));
|
||||
}
|
||||
|
||||
Ok(get_display_name::v3::Response {
|
||||
displayname: services().users.displayname(&body.user_id)?,
|
||||
displayname: services.users.displayname(&body.user_id)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -108,10 +107,10 @@ pub(crate) async fn get_displayname_route(
|
||||
///
|
||||
/// - Also makes sure other users receive the update using presence EDUs
|
||||
pub(crate) async fn set_avatar_url_route(
|
||||
body: Ruma<set_avatar_url::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<set_avatar_url::v3::Request>,
|
||||
) -> Result<set_avatar_url::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let all_joined_rooms: Vec<OwnedRoomId> = services()
|
||||
let all_joined_rooms: Vec<OwnedRoomId> = services
|
||||
.rooms
|
||||
.state_cache
|
||||
.rooms_joined(sender_user)
|
||||
@@ -119,6 +118,7 @@ pub(crate) async fn set_avatar_url_route(
|
||||
.collect();
|
||||
|
||||
update_avatar_url(
|
||||
&services,
|
||||
sender_user.clone(),
|
||||
body.avatar_url.clone(),
|
||||
body.blurhash.clone(),
|
||||
@@ -126,9 +126,9 @@ pub(crate) async fn set_avatar_url_route(
|
||||
)
|
||||
.await?;
|
||||
|
||||
if services().globals.allow_local_presence() {
|
||||
if services.globals.allow_local_presence() {
|
||||
// Presence update
|
||||
services()
|
||||
services
|
||||
.presence
|
||||
.ping_presence(sender_user, &PresenceState::Online)?;
|
||||
}
|
||||
@@ -143,11 +143,11 @@ pub(crate) async fn set_avatar_url_route(
|
||||
/// - If user is on another server and we do not have a local copy already fetch
|
||||
/// `avatar_url` and blurhash over federation
|
||||
pub(crate) async fn get_avatar_url_route(
|
||||
body: Ruma<get_avatar_url::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_avatar_url::v3::Request>,
|
||||
) -> Result<get_avatar_url::v3::Response> {
|
||||
if !user_is_local(&body.user_id) {
|
||||
if !services.globals.user_is_local(&body.user_id) {
|
||||
// Create and update our local copy of the user
|
||||
if let Ok(response) = services()
|
||||
if let Ok(response) = services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
body.user_id.server_name(),
|
||||
@@ -158,19 +158,19 @@ pub(crate) async fn get_avatar_url_route(
|
||||
)
|
||||
.await
|
||||
{
|
||||
if !services().users.exists(&body.user_id)? {
|
||||
services().users.create(&body.user_id, None)?;
|
||||
if !services.users.exists(&body.user_id)? {
|
||||
services.users.create(&body.user_id, None)?;
|
||||
}
|
||||
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.set_displayname(&body.user_id, response.displayname.clone())
|
||||
.await?;
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.set_avatar_url(&body.user_id, response.avatar_url.clone())
|
||||
.await?;
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.set_blurhash(&body.user_id, response.blurhash.clone())
|
||||
.await?;
|
||||
@@ -182,15 +182,15 @@ pub(crate) async fn get_avatar_url_route(
|
||||
}
|
||||
}
|
||||
|
||||
if !services().users.exists(&body.user_id)? {
|
||||
if !services.users.exists(&body.user_id)? {
|
||||
// Return 404 if this user doesn't exist and we couldn't fetch it over
|
||||
// federation
|
||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Profile was not found."));
|
||||
}
|
||||
|
||||
Ok(get_avatar_url::v3::Response {
|
||||
avatar_url: services().users.avatar_url(&body.user_id)?,
|
||||
blurhash: services().users.blurhash(&body.user_id)?,
|
||||
avatar_url: services.users.avatar_url(&body.user_id)?,
|
||||
blurhash: services.users.blurhash(&body.user_id)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -200,10 +200,12 @@ pub(crate) async fn get_avatar_url_route(
|
||||
///
|
||||
/// - If user is on another server and we do not have a local copy already,
|
||||
/// fetch profile over federation.
|
||||
pub(crate) async fn get_profile_route(body: Ruma<get_profile::v3::Request>) -> Result<get_profile::v3::Response> {
|
||||
if !user_is_local(&body.user_id) {
|
||||
pub(crate) async fn get_profile_route(
|
||||
State(services): State<crate::State>, body: Ruma<get_profile::v3::Request>,
|
||||
) -> Result<get_profile::v3::Response> {
|
||||
if !services.globals.user_is_local(&body.user_id) {
|
||||
// Create and update our local copy of the user
|
||||
if let Ok(response) = services()
|
||||
if let Ok(response) = services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
body.user_id.server_name(),
|
||||
@@ -214,19 +216,19 @@ pub(crate) async fn get_profile_route(body: Ruma<get_profile::v3::Request>) -> R
|
||||
)
|
||||
.await
|
||||
{
|
||||
if !services().users.exists(&body.user_id)? {
|
||||
services().users.create(&body.user_id, None)?;
|
||||
if !services.users.exists(&body.user_id)? {
|
||||
services.users.create(&body.user_id, None)?;
|
||||
}
|
||||
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.set_displayname(&body.user_id, response.displayname.clone())
|
||||
.await?;
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.set_avatar_url(&body.user_id, response.avatar_url.clone())
|
||||
.await?;
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.set_blurhash(&body.user_id, response.blurhash.clone())
|
||||
.await?;
|
||||
@@ -239,23 +241,29 @@ pub(crate) async fn get_profile_route(body: Ruma<get_profile::v3::Request>) -> R
|
||||
}
|
||||
}
|
||||
|
||||
if !services().users.exists(&body.user_id)? {
|
||||
if !services.users.exists(&body.user_id)? {
|
||||
// Return 404 if this user doesn't exist and we couldn't fetch it over
|
||||
// federation
|
||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Profile was not found."));
|
||||
}
|
||||
|
||||
Ok(get_profile::v3::Response {
|
||||
avatar_url: services().users.avatar_url(&body.user_id)?,
|
||||
blurhash: services().users.blurhash(&body.user_id)?,
|
||||
displayname: services().users.displayname(&body.user_id)?,
|
||||
avatar_url: services.users.avatar_url(&body.user_id)?,
|
||||
blurhash: services.users.blurhash(&body.user_id)?,
|
||||
displayname: services.users.displayname(&body.user_id)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn update_displayname(
|
||||
user_id: OwnedUserId, displayname: Option<String>, all_joined_rooms: Vec<OwnedRoomId>,
|
||||
services: &Services, user_id: OwnedUserId, displayname: Option<String>, all_joined_rooms: Vec<OwnedRoomId>,
|
||||
) -> Result<()> {
|
||||
services()
|
||||
let current_display_name = services.users.displayname(&user_id).unwrap_or_default();
|
||||
|
||||
if displayname == current_display_name {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
services
|
||||
.users
|
||||
.set_displayname(&user_id, displayname.clone())
|
||||
.await?;
|
||||
@@ -271,7 +279,7 @@ pub async fn update_displayname(
|
||||
displayname: displayname.clone(),
|
||||
join_authorized_via_users_server: None,
|
||||
..serde_json::from_str(
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.room_state_get(room_id, &StateEventType::RoomMember, user_id.as_str())?
|
||||
@@ -287,6 +295,7 @@ pub async fn update_displayname(
|
||||
unsigned: None,
|
||||
state_key: Some(user_id.to_string()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
room_id,
|
||||
))
|
||||
@@ -294,19 +303,27 @@ pub async fn update_displayname(
|
||||
.filter_map(Result::ok)
|
||||
.collect();
|
||||
|
||||
update_all_rooms(all_joined_rooms, user_id).await;
|
||||
update_all_rooms(services, all_joined_rooms, user_id).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn update_avatar_url(
|
||||
user_id: OwnedUserId, avatar_url: Option<OwnedMxcUri>, blurhash: Option<String>, all_joined_rooms: Vec<OwnedRoomId>,
|
||||
services: &Services, user_id: OwnedUserId, avatar_url: Option<OwnedMxcUri>, blurhash: Option<String>,
|
||||
all_joined_rooms: Vec<OwnedRoomId>,
|
||||
) -> Result<()> {
|
||||
services()
|
||||
let current_avatar_url = services.users.avatar_url(&user_id).unwrap_or_default();
|
||||
let current_blurhash = services.users.blurhash(&user_id).unwrap_or_default();
|
||||
|
||||
if current_avatar_url == avatar_url && current_blurhash == blurhash {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
services
|
||||
.users
|
||||
.set_avatar_url(&user_id, avatar_url.clone())
|
||||
.await?;
|
||||
services()
|
||||
services
|
||||
.users
|
||||
.set_blurhash(&user_id, blurhash.clone())
|
||||
.await?;
|
||||
@@ -323,7 +340,7 @@ pub async fn update_avatar_url(
|
||||
blurhash: blurhash.clone(),
|
||||
join_authorized_via_users_server: None,
|
||||
..serde_json::from_str(
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.room_state_get(room_id, &StateEventType::RoomMember, user_id.as_str())?
|
||||
@@ -339,6 +356,7 @@ pub async fn update_avatar_url(
|
||||
unsigned: None,
|
||||
state_key: Some(user_id.to_string()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
room_id,
|
||||
))
|
||||
@@ -346,15 +364,17 @@ pub async fn update_avatar_url(
|
||||
.filter_map(Result::ok)
|
||||
.collect();
|
||||
|
||||
update_all_rooms(all_joined_rooms, user_id).await;
|
||||
update_all_rooms(services, all_joined_rooms, user_id).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn update_all_rooms(all_joined_rooms: Vec<(PduBuilder, &OwnedRoomId)>, user_id: OwnedUserId) {
|
||||
pub async fn update_all_rooms(
|
||||
services: &Services, all_joined_rooms: Vec<(PduBuilder, &OwnedRoomId)>, user_id: OwnedUserId,
|
||||
) {
|
||||
for (pdu_builder, room_id) in all_joined_rooms {
|
||||
let state_lock = services().rooms.state.mutex.lock(room_id).await;
|
||||
if let Err(e) = services()
|
||||
let state_lock = services.rooms.state.mutex.lock(room_id).await;
|
||||
if let Err(e) = services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(pdu_builder, &user_id, room_id, &state_lock)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use axum::extract::State;
|
||||
use conduit::err;
|
||||
use ruma::{
|
||||
api::client::{
|
||||
error::ErrorKind,
|
||||
@@ -6,59 +8,76 @@
|
||||
set_pusher, set_pushrule, set_pushrule_actions, set_pushrule_enabled, RuleScope,
|
||||
},
|
||||
},
|
||||
events::{push_rules::PushRulesEvent, GlobalAccountDataEventType},
|
||||
events::{
|
||||
push_rules::{PushRulesEvent, PushRulesEventContent},
|
||||
GlobalAccountDataEventType,
|
||||
},
|
||||
push::{InsertPushRuleError, RemovePushRuleError, Ruleset},
|
||||
CanonicalJsonObject,
|
||||
};
|
||||
use service::Services;
|
||||
|
||||
use crate::{services, Error, Result, Ruma};
|
||||
use crate::{Error, Result, Ruma};
|
||||
|
||||
/// # `GET /_matrix/client/r0/pushrules/`
|
||||
///
|
||||
/// Retrieves the push rules event for this user.
|
||||
pub(crate) async fn get_pushrules_all_route(
|
||||
body: Ruma<get_pushrules_all::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_pushrules_all::v3::Request>,
|
||||
) -> Result<get_pushrules_all::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let event =
|
||||
services()
|
||||
let global_ruleset: Ruleset;
|
||||
|
||||
let Ok(event) =
|
||||
services
|
||||
.account_data
|
||||
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())?;
|
||||
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())
|
||||
else {
|
||||
// push rules event doesn't exist, create it and return default
|
||||
return recreate_push_rules_and_return(&services, sender_user);
|
||||
};
|
||||
|
||||
if let Some(event) = event {
|
||||
let account_data = serde_json::from_str::<PushRulesEvent>(event.get())
|
||||
.map_err(|_| Error::bad_database("Invalid account data event in db."))?
|
||||
.content;
|
||||
let value = serde_json::from_str::<CanonicalJsonObject>(event.get())
|
||||
.map_err(|e| err!(Database(warn!("Invalid push rules account data event in database: {e}"))))?;
|
||||
|
||||
Ok(get_pushrules_all::v3::Response {
|
||||
global: account_data.global,
|
||||
})
|
||||
let Some(content_value) = value.get("content") else {
|
||||
// user somehow has a push rule event with no content key, recreate it and
|
||||
// return server default silently
|
||||
return recreate_push_rules_and_return(&services, sender_user);
|
||||
};
|
||||
|
||||
if content_value.to_string().is_empty() {
|
||||
// user somehow has a push rule event with empty content, recreate it and return
|
||||
// server default silently
|
||||
return recreate_push_rules_and_return(&services, sender_user);
|
||||
}
|
||||
|
||||
let account_data_content = serde_json::from_value::<PushRulesEventContent>(content_value.clone().into())
|
||||
.map_err(|e| err!(Database(warn!("Invalid push rules account data event in database: {e}"))))?;
|
||||
|
||||
global_ruleset = account_data_content.global;
|
||||
} else {
|
||||
services().account_data.update(
|
||||
None,
|
||||
sender_user,
|
||||
GlobalAccountDataEventType::PushRules.to_string().into(),
|
||||
&serde_json::to_value(PushRulesEvent {
|
||||
content: ruma::events::push_rules::PushRulesEventContent {
|
||||
global: Ruleset::server_default(sender_user),
|
||||
},
|
||||
})
|
||||
.expect("to json always works"),
|
||||
)?;
|
||||
|
||||
Ok(get_pushrules_all::v3::Response {
|
||||
global: Ruleset::server_default(sender_user),
|
||||
})
|
||||
// user somehow has non-existent push rule event. recreate it and return server
|
||||
// default silently
|
||||
return recreate_push_rules_and_return(&services, sender_user);
|
||||
}
|
||||
|
||||
Ok(get_pushrules_all::v3::Response {
|
||||
global: global_ruleset,
|
||||
})
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
|
||||
///
|
||||
/// Retrieves a single specified push rule for this user.
|
||||
pub(crate) async fn get_pushrule_route(body: Ruma<get_pushrule::v3::Request>) -> Result<get_pushrule::v3::Response> {
|
||||
pub(crate) async fn get_pushrule_route(
|
||||
State(services): State<crate::State>, body: Ruma<get_pushrule::v3::Request>,
|
||||
) -> Result<get_pushrule::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let event = services()
|
||||
let event = services
|
||||
.account_data
|
||||
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())?
|
||||
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?;
|
||||
@@ -84,7 +103,9 @@ pub(crate) async fn get_pushrule_route(body: Ruma<get_pushrule::v3::Request>) ->
|
||||
/// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
|
||||
///
|
||||
/// Creates a single specified push rule for this user.
|
||||
pub(crate) async fn set_pushrule_route(body: Ruma<set_pushrule::v3::Request>) -> Result<set_pushrule::v3::Response> {
|
||||
pub(crate) async fn set_pushrule_route(
|
||||
State(services): State<crate::State>, body: Ruma<set_pushrule::v3::Request>,
|
||||
) -> Result<set_pushrule::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let body = body.body;
|
||||
|
||||
@@ -95,7 +116,7 @@ pub(crate) async fn set_pushrule_route(body: Ruma<set_pushrule::v3::Request>) ->
|
||||
));
|
||||
}
|
||||
|
||||
let event = services()
|
||||
let event = services
|
||||
.account_data
|
||||
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())?
|
||||
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?;
|
||||
@@ -134,7 +155,7 @@ pub(crate) async fn set_pushrule_route(body: Ruma<set_pushrule::v3::Request>) ->
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
services().account_data.update(
|
||||
services.account_data.update(
|
||||
None,
|
||||
sender_user,
|
||||
GlobalAccountDataEventType::PushRules.to_string().into(),
|
||||
@@ -148,7 +169,7 @@ pub(crate) async fn set_pushrule_route(body: Ruma<set_pushrule::v3::Request>) ->
|
||||
///
|
||||
/// Gets the actions of a single specified push rule for this user.
|
||||
pub(crate) async fn get_pushrule_actions_route(
|
||||
body: Ruma<get_pushrule_actions::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_pushrule_actions::v3::Request>,
|
||||
) -> Result<get_pushrule_actions::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
@@ -159,7 +180,7 @@ pub(crate) async fn get_pushrule_actions_route(
|
||||
));
|
||||
}
|
||||
|
||||
let event = services()
|
||||
let event = services
|
||||
.account_data
|
||||
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())?
|
||||
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?;
|
||||
@@ -183,7 +204,7 @@ pub(crate) async fn get_pushrule_actions_route(
|
||||
///
|
||||
/// Sets the actions of a single specified push rule for this user.
|
||||
pub(crate) async fn set_pushrule_actions_route(
|
||||
body: Ruma<set_pushrule_actions::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<set_pushrule_actions::v3::Request>,
|
||||
) -> Result<set_pushrule_actions::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
@@ -194,7 +215,7 @@ pub(crate) async fn set_pushrule_actions_route(
|
||||
));
|
||||
}
|
||||
|
||||
let event = services()
|
||||
let event = services
|
||||
.account_data
|
||||
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())?
|
||||
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?;
|
||||
@@ -211,7 +232,7 @@ pub(crate) async fn set_pushrule_actions_route(
|
||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Push rule not found."));
|
||||
}
|
||||
|
||||
services().account_data.update(
|
||||
services.account_data.update(
|
||||
None,
|
||||
sender_user,
|
||||
GlobalAccountDataEventType::PushRules.to_string().into(),
|
||||
@@ -225,7 +246,7 @@ pub(crate) async fn set_pushrule_actions_route(
|
||||
///
|
||||
/// Gets the enabled status of a single specified push rule for this user.
|
||||
pub(crate) async fn get_pushrule_enabled_route(
|
||||
body: Ruma<get_pushrule_enabled::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_pushrule_enabled::v3::Request>,
|
||||
) -> Result<get_pushrule_enabled::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
@@ -236,7 +257,7 @@ pub(crate) async fn get_pushrule_enabled_route(
|
||||
));
|
||||
}
|
||||
|
||||
let event = services()
|
||||
let event = services
|
||||
.account_data
|
||||
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())?
|
||||
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?;
|
||||
@@ -259,7 +280,7 @@ pub(crate) async fn get_pushrule_enabled_route(
|
||||
///
|
||||
/// Sets the enabled status of a single specified push rule for this user.
|
||||
pub(crate) async fn set_pushrule_enabled_route(
|
||||
body: Ruma<set_pushrule_enabled::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<set_pushrule_enabled::v3::Request>,
|
||||
) -> Result<set_pushrule_enabled::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
@@ -270,7 +291,7 @@ pub(crate) async fn set_pushrule_enabled_route(
|
||||
));
|
||||
}
|
||||
|
||||
let event = services()
|
||||
let event = services
|
||||
.account_data
|
||||
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())?
|
||||
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?;
|
||||
@@ -287,7 +308,7 @@ pub(crate) async fn set_pushrule_enabled_route(
|
||||
return Err(Error::BadRequest(ErrorKind::NotFound, "Push rule not found."));
|
||||
}
|
||||
|
||||
services().account_data.update(
|
||||
services.account_data.update(
|
||||
None,
|
||||
sender_user,
|
||||
GlobalAccountDataEventType::PushRules.to_string().into(),
|
||||
@@ -301,7 +322,7 @@ pub(crate) async fn set_pushrule_enabled_route(
|
||||
///
|
||||
/// Deletes a single specified push rule for this user.
|
||||
pub(crate) async fn delete_pushrule_route(
|
||||
body: Ruma<delete_pushrule::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<delete_pushrule::v3::Request>,
|
||||
) -> Result<delete_pushrule::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
@@ -312,7 +333,7 @@ pub(crate) async fn delete_pushrule_route(
|
||||
));
|
||||
}
|
||||
|
||||
let event = services()
|
||||
let event = services
|
||||
.account_data
|
||||
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())?
|
||||
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?;
|
||||
@@ -336,7 +357,7 @@ pub(crate) async fn delete_pushrule_route(
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
services().account_data.update(
|
||||
services.account_data.update(
|
||||
None,
|
||||
sender_user,
|
||||
GlobalAccountDataEventType::PushRules.to_string().into(),
|
||||
@@ -349,11 +370,13 @@ pub(crate) async fn delete_pushrule_route(
|
||||
/// # `GET /_matrix/client/r0/pushers`
|
||||
///
|
||||
/// Gets all currently active pushers for the sender user.
|
||||
pub(crate) async fn get_pushers_route(body: Ruma<get_pushers::v3::Request>) -> Result<get_pushers::v3::Response> {
|
||||
pub(crate) async fn get_pushers_route(
|
||||
State(services): State<crate::State>, body: Ruma<get_pushers::v3::Request>,
|
||||
) -> Result<get_pushers::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
Ok(get_pushers::v3::Response {
|
||||
pushers: services().pusher.get_pushers(sender_user)?,
|
||||
pushers: services.pusher.get_pushers(sender_user)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -362,10 +385,34 @@ pub(crate) async fn get_pushers_route(body: Ruma<get_pushers::v3::Request>) -> R
|
||||
/// Adds a pusher for the sender user.
|
||||
///
|
||||
/// - TODO: Handle `append`
|
||||
pub(crate) async fn set_pushers_route(body: Ruma<set_pusher::v3::Request>) -> Result<set_pusher::v3::Response> {
|
||||
pub(crate) async fn set_pushers_route(
|
||||
State(services): State<crate::State>, body: Ruma<set_pusher::v3::Request>,
|
||||
) -> Result<set_pusher::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
services().pusher.set_pusher(sender_user, &body.action)?;
|
||||
services.pusher.set_pusher(sender_user, &body.action)?;
|
||||
|
||||
Ok(set_pusher::v3::Response::default())
|
||||
}
|
||||
|
||||
/// user somehow has bad push rules, these must always exist per spec.
|
||||
/// so recreate it and return server default silently
|
||||
fn recreate_push_rules_and_return(
|
||||
services: &Services, sender_user: &ruma::UserId,
|
||||
) -> Result<get_pushrules_all::v3::Response> {
|
||||
services.account_data.update(
|
||||
None,
|
||||
sender_user,
|
||||
GlobalAccountDataEventType::PushRules.to_string().into(),
|
||||
&serde_json::to_value(PushRulesEvent {
|
||||
content: PushRulesEventContent {
|
||||
global: Ruleset::server_default(sender_user),
|
||||
},
|
||||
})
|
||||
.expect("to json always works"),
|
||||
)?;
|
||||
|
||||
Ok(get_pushrules_all::v3::Response {
|
||||
global: Ruleset::server_default(sender_user),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use axum::extract::State;
|
||||
use conduit::PduCount;
|
||||
use ruma::{
|
||||
api::client::{error::ErrorKind, read_marker::set_read_marker, receipt::create_receipt},
|
||||
@@ -10,7 +11,7 @@
|
||||
MilliSecondsSinceUnixEpoch,
|
||||
};
|
||||
|
||||
use crate::{services, Error, Result, Ruma};
|
||||
use crate::{Error, Result, Ruma};
|
||||
|
||||
/// # `POST /_matrix/client/r0/rooms/{roomId}/read_markers`
|
||||
///
|
||||
@@ -20,7 +21,7 @@
|
||||
/// - If `read_receipt` is set: Update private marker and public read receipt
|
||||
/// EDU
|
||||
pub(crate) async fn set_read_marker_route(
|
||||
body: Ruma<set_read_marker::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<set_read_marker::v3::Request>,
|
||||
) -> Result<set_read_marker::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
@@ -30,7 +31,7 @@ pub(crate) async fn set_read_marker_route(
|
||||
event_id: fully_read.clone(),
|
||||
},
|
||||
};
|
||||
services().account_data.update(
|
||||
services.account_data.update(
|
||||
Some(&body.room_id),
|
||||
sender_user,
|
||||
RoomAccountDataEventType::FullyRead,
|
||||
@@ -39,14 +40,14 @@ pub(crate) async fn set_read_marker_route(
|
||||
}
|
||||
|
||||
if body.private_read_receipt.is_some() || body.read_receipt.is_some() {
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.user
|
||||
.reset_notification_counts(sender_user, &body.room_id)?;
|
||||
}
|
||||
|
||||
if let Some(event) = &body.private_read_receipt {
|
||||
let count = services()
|
||||
let count = services
|
||||
.rooms
|
||||
.timeline
|
||||
.get_pdu_count(event)?
|
||||
@@ -60,7 +61,7 @@ pub(crate) async fn set_read_marker_route(
|
||||
},
|
||||
PduCount::Normal(c) => c,
|
||||
};
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.read_receipt
|
||||
.private_read_set(&body.room_id, sender_user, count)?;
|
||||
@@ -82,7 +83,7 @@ pub(crate) async fn set_read_marker_route(
|
||||
let mut receipt_content = BTreeMap::new();
|
||||
receipt_content.insert(event.to_owned(), receipts);
|
||||
|
||||
services().rooms.read_receipt.readreceipt_update(
|
||||
services.rooms.read_receipt.readreceipt_update(
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
&ruma::events::receipt::ReceiptEvent {
|
||||
@@ -99,7 +100,7 @@ pub(crate) async fn set_read_marker_route(
|
||||
///
|
||||
/// Sets private read marker and public read receipt EDU.
|
||||
pub(crate) async fn create_receipt_route(
|
||||
body: Ruma<create_receipt::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<create_receipt::v3::Request>,
|
||||
) -> Result<create_receipt::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
@@ -107,7 +108,7 @@ pub(crate) async fn create_receipt_route(
|
||||
&body.receipt_type,
|
||||
create_receipt::v3::ReceiptType::Read | create_receipt::v3::ReceiptType::ReadPrivate
|
||||
) {
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.user
|
||||
.reset_notification_counts(sender_user, &body.room_id)?;
|
||||
@@ -120,7 +121,7 @@ pub(crate) async fn create_receipt_route(
|
||||
event_id: body.event_id.clone(),
|
||||
},
|
||||
};
|
||||
services().account_data.update(
|
||||
services.account_data.update(
|
||||
Some(&body.room_id),
|
||||
sender_user,
|
||||
RoomAccountDataEventType::FullyRead,
|
||||
@@ -142,7 +143,7 @@ pub(crate) async fn create_receipt_route(
|
||||
let mut receipt_content = BTreeMap::new();
|
||||
receipt_content.insert(body.event_id.clone(), receipts);
|
||||
|
||||
services().rooms.read_receipt.readreceipt_update(
|
||||
services.rooms.read_receipt.readreceipt_update(
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
&ruma::events::receipt::ReceiptEvent {
|
||||
@@ -152,7 +153,7 @@ pub(crate) async fn create_receipt_route(
|
||||
)?;
|
||||
},
|
||||
create_receipt::v3::ReceiptType::ReadPrivate => {
|
||||
let count = services()
|
||||
let count = services
|
||||
.rooms
|
||||
.timeline
|
||||
.get_pdu_count(&body.event_id)?
|
||||
@@ -166,7 +167,7 @@ pub(crate) async fn create_receipt_route(
|
||||
},
|
||||
PduCount::Normal(c) => c,
|
||||
};
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.read_receipt
|
||||
.private_read_set(&body.room_id, sender_user, count)?;
|
||||
|
||||
@@ -1,23 +1,26 @@
|
||||
use axum::extract::State;
|
||||
use ruma::{
|
||||
api::client::redact::redact_event,
|
||||
events::{room::redaction::RoomRedactionEventContent, TimelineEventType},
|
||||
};
|
||||
use serde_json::value::to_raw_value;
|
||||
|
||||
use crate::{service::pdu::PduBuilder, services, Result, Ruma};
|
||||
use crate::{service::pdu::PduBuilder, Result, Ruma};
|
||||
|
||||
/// # `PUT /_matrix/client/r0/rooms/{roomId}/redact/{eventId}/{txnId}`
|
||||
///
|
||||
/// Tries to send a redaction event into the room.
|
||||
///
|
||||
/// - TODO: Handle txn id
|
||||
pub(crate) async fn redact_event_route(body: Ruma<redact_event::v3::Request>) -> Result<redact_event::v3::Response> {
|
||||
pub(crate) async fn redact_event_route(
|
||||
State(services): State<crate::State>, body: Ruma<redact_event::v3::Request>,
|
||||
) -> Result<redact_event::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
let body = body.body;
|
||||
|
||||
let state_lock = services().rooms.state.mutex.lock(&body.room_id).await;
|
||||
let state_lock = services.rooms.state.mutex.lock(&body.room_id).await;
|
||||
|
||||
let event_id = services()
|
||||
let event_id = services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -31,6 +34,7 @@ pub(crate) async fn redact_event_route(body: Ruma<redact_event::v3::Request>) ->
|
||||
unsigned: None,
|
||||
state_key: None,
|
||||
redacts: Some(body.event_id.into()),
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
|
||||
@@ -1,30 +1,28 @@
|
||||
use axum::extract::State;
|
||||
use ruma::api::client::relations::{
|
||||
get_relating_events, get_relating_events_with_rel_type, get_relating_events_with_rel_type_and_event_type,
|
||||
};
|
||||
|
||||
use crate::{services, Result, Ruma};
|
||||
use crate::{Result, Ruma};
|
||||
|
||||
/// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}/{eventType}`
|
||||
pub(crate) async fn get_relating_events_with_rel_type_and_event_type_route(
|
||||
body: Ruma<get_relating_events_with_rel_type_and_event_type::v1::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_relating_events_with_rel_type_and_event_type::v1::Request>,
|
||||
) -> Result<get_relating_events_with_rel_type_and_event_type::v1::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let res = services()
|
||||
.rooms
|
||||
.pdu_metadata
|
||||
.paginate_relations_with_filter(
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
&body.event_id,
|
||||
&Some(body.event_type.clone()),
|
||||
&Some(body.rel_type.clone()),
|
||||
&body.from,
|
||||
&body.to,
|
||||
&body.limit,
|
||||
body.recurse,
|
||||
body.dir,
|
||||
)?;
|
||||
let res = services.rooms.pdu_metadata.paginate_relations_with_filter(
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
&body.event_id,
|
||||
&Some(body.event_type.clone()),
|
||||
&Some(body.rel_type.clone()),
|
||||
&body.from,
|
||||
&body.to,
|
||||
&body.limit,
|
||||
body.recurse,
|
||||
body.dir,
|
||||
)?;
|
||||
|
||||
Ok(get_relating_events_with_rel_type_and_event_type::v1::Response {
|
||||
chunk: res.chunk,
|
||||
@@ -36,25 +34,22 @@ pub(crate) async fn get_relating_events_with_rel_type_and_event_type_route(
|
||||
|
||||
/// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}`
|
||||
pub(crate) async fn get_relating_events_with_rel_type_route(
|
||||
body: Ruma<get_relating_events_with_rel_type::v1::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_relating_events_with_rel_type::v1::Request>,
|
||||
) -> Result<get_relating_events_with_rel_type::v1::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let res = services()
|
||||
.rooms
|
||||
.pdu_metadata
|
||||
.paginate_relations_with_filter(
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
&body.event_id,
|
||||
&None,
|
||||
&Some(body.rel_type.clone()),
|
||||
&body.from,
|
||||
&body.to,
|
||||
&body.limit,
|
||||
body.recurse,
|
||||
body.dir,
|
||||
)?;
|
||||
let res = services.rooms.pdu_metadata.paginate_relations_with_filter(
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
&body.event_id,
|
||||
&None,
|
||||
&Some(body.rel_type.clone()),
|
||||
&body.from,
|
||||
&body.to,
|
||||
&body.limit,
|
||||
body.recurse,
|
||||
body.dir,
|
||||
)?;
|
||||
|
||||
Ok(get_relating_events_with_rel_type::v1::Response {
|
||||
chunk: res.chunk,
|
||||
@@ -66,23 +61,20 @@ pub(crate) async fn get_relating_events_with_rel_type_route(
|
||||
|
||||
/// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}`
|
||||
pub(crate) async fn get_relating_events_route(
|
||||
body: Ruma<get_relating_events::v1::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_relating_events::v1::Request>,
|
||||
) -> Result<get_relating_events::v1::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
services()
|
||||
.rooms
|
||||
.pdu_metadata
|
||||
.paginate_relations_with_filter(
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
&body.event_id,
|
||||
&None,
|
||||
&None,
|
||||
&body.from,
|
||||
&body.to,
|
||||
&body.limit,
|
||||
body.recurse,
|
||||
body.dir,
|
||||
)
|
||||
services.rooms.pdu_metadata.paginate_relations_with_filter(
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
&body.event_id,
|
||||
&None,
|
||||
&None,
|
||||
&body.from,
|
||||
&body.to,
|
||||
&body.limit,
|
||||
body.recurse,
|
||||
body.dir,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::State;
|
||||
use rand::Rng;
|
||||
use ruma::{
|
||||
api::client::{error::ErrorKind, room::report_content},
|
||||
@@ -9,13 +10,18 @@
|
||||
use tokio::time::sleep;
|
||||
use tracing::info;
|
||||
|
||||
use crate::{debug_info, service::pdu::PduEvent, services, utils::HtmlEscape, Error, Result, Ruma};
|
||||
use crate::{
|
||||
debug_info,
|
||||
service::{pdu::PduEvent, Services},
|
||||
utils::HtmlEscape,
|
||||
Error, Result, Ruma,
|
||||
};
|
||||
|
||||
/// # `POST /_matrix/client/v3/rooms/{roomId}/report/{eventId}`
|
||||
///
|
||||
/// Reports an inappropriate event to homeserver admins
|
||||
pub(crate) async fn report_event_route(
|
||||
body: Ruma<report_content::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<report_content::v3::Request>,
|
||||
) -> Result<report_content::v3::Response> {
|
||||
// user authentication
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
@@ -26,18 +32,26 @@ pub(crate) async fn report_event_route(
|
||||
);
|
||||
|
||||
// check if we know about the reported event ID or if it's invalid
|
||||
let Some(pdu) = services().rooms.timeline.get_pdu(&body.event_id)? else {
|
||||
let Some(pdu) = services.rooms.timeline.get_pdu(&body.event_id)? else {
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::NotFound,
|
||||
"Event ID is not known to us or Event ID is invalid",
|
||||
));
|
||||
};
|
||||
|
||||
is_report_valid(&pdu.event_id, &body.room_id, sender_user, &body.reason, body.score, &pdu)?;
|
||||
is_report_valid(
|
||||
&services,
|
||||
&pdu.event_id,
|
||||
&body.room_id,
|
||||
sender_user,
|
||||
&body.reason,
|
||||
body.score,
|
||||
&pdu,
|
||||
)?;
|
||||
|
||||
// send admin room message that we received the report with an @room ping for
|
||||
// urgency
|
||||
services()
|
||||
services
|
||||
.admin
|
||||
.send_message(message::RoomMessageEventContent::text_html(
|
||||
format!(
|
||||
@@ -79,8 +93,8 @@ pub(crate) async fn report_event_route(
|
||||
/// check if score is in valid range
|
||||
/// check if report reasoning is less than or equal to 750 characters
|
||||
fn is_report_valid(
|
||||
event_id: &EventId, room_id: &RoomId, sender_user: &UserId, reason: &Option<String>, score: Option<ruma::Int>,
|
||||
pdu: &std::sync::Arc<PduEvent>,
|
||||
services: &Services, event_id: &EventId, room_id: &RoomId, sender_user: &UserId, reason: &Option<String>,
|
||||
score: Option<ruma::Int>, pdu: &std::sync::Arc<PduEvent>,
|
||||
) -> Result<bool> {
|
||||
debug_info!("Checking if report from user {sender_user} for event {event_id} in room {room_id} is valid");
|
||||
|
||||
@@ -91,7 +105,7 @@ fn is_report_valid(
|
||||
));
|
||||
}
|
||||
|
||||
if !services()
|
||||
if !services
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_members(&pdu.room_id)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::{cmp::max, collections::BTreeMap};
|
||||
|
||||
use conduit::{debug_info, debug_warn};
|
||||
use axum::extract::State;
|
||||
use conduit::{debug_info, debug_warn, err};
|
||||
use ruma::{
|
||||
api::client::{
|
||||
error::ErrorKind,
|
||||
@@ -30,8 +31,8 @@
|
||||
|
||||
use super::invite_helper;
|
||||
use crate::{
|
||||
service::{appservice::RegistrationInfo, pdu::PduBuilder},
|
||||
services, Error, Result, Ruma,
|
||||
service::{appservice::RegistrationInfo, pdu::PduBuilder, Services},
|
||||
Error, Result, Ruma,
|
||||
};
|
||||
|
||||
/// Recommended transferable state events list from the spec
|
||||
@@ -63,44 +64,46 @@
|
||||
/// - Send events listed in initial state
|
||||
/// - Send events implied by `name` and `topic`
|
||||
/// - Send invite events
|
||||
pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<create_room::v3::Response> {
|
||||
pub(crate) async fn create_room_route(
|
||||
State(services): State<crate::State>, body: Ruma<create_room::v3::Request>,
|
||||
) -> Result<create_room::v3::Response> {
|
||||
use create_room::v3::RoomPreset;
|
||||
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
if !services().globals.allow_room_creation()
|
||||
if !services.globals.allow_room_creation()
|
||||
&& body.appservice_info.is_none()
|
||||
&& !services().users.is_admin(sender_user)?
|
||||
&& !services.users.is_admin(sender_user)?
|
||||
{
|
||||
return Err(Error::BadRequest(ErrorKind::forbidden(), "Room creation has been disabled."));
|
||||
}
|
||||
|
||||
let room_id: OwnedRoomId = if let Some(custom_room_id) = &body.room_id {
|
||||
custom_room_id_check(custom_room_id)?
|
||||
custom_room_id_check(&services, custom_room_id)?
|
||||
} else {
|
||||
RoomId::new(&services().globals.config.server_name)
|
||||
RoomId::new(&services.globals.config.server_name)
|
||||
};
|
||||
|
||||
// check if room ID doesn't already exist instead of erroring on auth check
|
||||
if services().rooms.short.get_shortroomid(&room_id)?.is_some() {
|
||||
if services.rooms.short.get_shortroomid(&room_id)?.is_some() {
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::RoomInUse,
|
||||
"Room with that custom room ID already exists",
|
||||
));
|
||||
}
|
||||
|
||||
let _short_id = services().rooms.short.get_or_create_shortroomid(&room_id)?;
|
||||
let state_lock = services().rooms.state.mutex.lock(&room_id).await;
|
||||
let _short_id = services.rooms.short.get_or_create_shortroomid(&room_id)?;
|
||||
let state_lock = services.rooms.state.mutex.lock(&room_id).await;
|
||||
|
||||
let alias: Option<OwnedRoomAliasId> = if let Some(alias) = &body.room_alias_name {
|
||||
Some(room_alias_check(alias, &body.appservice_info).await?)
|
||||
Some(room_alias_check(&services, alias, &body.appservice_info).await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let room_version = match body.room_version.clone() {
|
||||
Some(room_version) => {
|
||||
if services()
|
||||
if services
|
||||
.globals
|
||||
.supported_room_versions()
|
||||
.contains(&room_version)
|
||||
@@ -113,7 +116,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
));
|
||||
}
|
||||
},
|
||||
None => services().globals.default_room_version(),
|
||||
None => services.globals.default_room_version(),
|
||||
};
|
||||
|
||||
let content = match &body.creation_content {
|
||||
@@ -136,13 +139,8 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
})?,
|
||||
);
|
||||
},
|
||||
V11 => {}, // V11 removed the "creator" key
|
||||
_ => {
|
||||
warn!("Unexpected or unsupported room version {room_version}");
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::BadJson,
|
||||
"Unexpected or unsupported room version found",
|
||||
));
|
||||
// V11+ removed the "creator" key
|
||||
},
|
||||
}
|
||||
content.insert(
|
||||
@@ -158,14 +156,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
|
||||
let content = match room_version {
|
||||
V1 | V2 | V3 | V4 | V5 | V6 | V7 | V8 | V9 | V10 => RoomCreateEventContent::new_v1(sender_user.clone()),
|
||||
V11 => RoomCreateEventContent::new_v11(),
|
||||
_ => {
|
||||
warn!("Unexpected or unsupported room version {room_version}");
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::BadJson,
|
||||
"Unexpected or unsupported room version found",
|
||||
));
|
||||
},
|
||||
_ => RoomCreateEventContent::new_v11(),
|
||||
};
|
||||
let mut content = serde_json::from_str::<CanonicalJsonObject>(
|
||||
to_raw_value(&content)
|
||||
@@ -184,7 +175,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
};
|
||||
|
||||
// 1. The room create event
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -194,6 +185,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
unsigned: None,
|
||||
state_key: Some(String::new()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&room_id,
|
||||
@@ -202,7 +194,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
.await?;
|
||||
|
||||
// 2. Let the room creator join
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -210,11 +202,11 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
event_type: TimelineEventType::RoomMember,
|
||||
content: to_raw_value(&RoomMemberEventContent {
|
||||
membership: MembershipState::Join,
|
||||
displayname: services().users.displayname(sender_user)?,
|
||||
avatar_url: services().users.avatar_url(sender_user)?,
|
||||
displayname: services.users.displayname(sender_user)?,
|
||||
avatar_url: services.users.avatar_url(sender_user)?,
|
||||
is_direct: Some(body.is_direct),
|
||||
third_party_invite: None,
|
||||
blurhash: services().users.blurhash(sender_user)?,
|
||||
blurhash: services.users.blurhash(sender_user)?,
|
||||
reason: None,
|
||||
join_authorized_via_users_server: None,
|
||||
})
|
||||
@@ -222,6 +214,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
unsigned: None,
|
||||
state_key: Some(sender_user.to_string()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&room_id,
|
||||
@@ -249,7 +242,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
let power_levels_content =
|
||||
default_power_levels_content(&body.power_level_content_override, &body.visibility, users)?;
|
||||
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -259,6 +252,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
unsigned: None,
|
||||
state_key: Some(String::new()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&room_id,
|
||||
@@ -268,7 +262,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
|
||||
// 4. Canonical room alias
|
||||
if let Some(room_alias_id) = &alias {
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -282,6 +276,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
unsigned: None,
|
||||
state_key: Some(String::new()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&room_id,
|
||||
@@ -293,7 +288,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
// 5. Events set by preset
|
||||
|
||||
// 5.1 Join Rules
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -308,6 +303,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
unsigned: None,
|
||||
state_key: Some(String::new()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&room_id,
|
||||
@@ -316,7 +312,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
.await?;
|
||||
|
||||
// 5.2 History Visibility
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -327,6 +323,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
unsigned: None,
|
||||
state_key: Some(String::new()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&room_id,
|
||||
@@ -335,7 +332,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
.await?;
|
||||
|
||||
// 5.3 Guest Access
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -349,6 +346,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
unsigned: None,
|
||||
state_key: Some(String::new()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&room_id,
|
||||
@@ -378,11 +376,11 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
pdu_builder.state_key.get_or_insert_with(String::new);
|
||||
|
||||
// Silently skip encryption events if they are not allowed
|
||||
if pdu_builder.event_type == TimelineEventType::RoomEncryption && !services().globals.allow_encryption() {
|
||||
if pdu_builder.event_type == TimelineEventType::RoomEncryption && !services.globals.allow_encryption() {
|
||||
continue;
|
||||
}
|
||||
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock)
|
||||
@@ -391,7 +389,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
|
||||
// 7. Events implied by name and topic
|
||||
if let Some(name) = &body.name {
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -402,6 +400,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
unsigned: None,
|
||||
state_key: Some(String::new()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&room_id,
|
||||
@@ -411,7 +410,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
}
|
||||
|
||||
if let Some(topic) = &body.topic {
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -424,6 +423,7 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
unsigned: None,
|
||||
state_key: Some(String::new()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&room_id,
|
||||
@@ -435,21 +435,21 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
// 8. Events implied by invite (and TODO: invite_3pid)
|
||||
drop(state_lock);
|
||||
for user_id in &body.invite {
|
||||
if let Err(e) = invite_helper(sender_user, user_id, &room_id, None, body.is_direct).await {
|
||||
if let Err(e) = invite_helper(&services, sender_user, user_id, &room_id, None, body.is_direct).await {
|
||||
warn!(%e, "Failed to send invite");
|
||||
}
|
||||
}
|
||||
|
||||
// Homeserver specific stuff
|
||||
if let Some(alias) = alias {
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.alias
|
||||
.set_alias(&alias, &room_id, sender_user)?;
|
||||
}
|
||||
|
||||
if body.visibility == room::Visibility::Public {
|
||||
services().rooms.directory.set_public(&room_id)?;
|
||||
services.rooms.directory.set_public(&room_id)?;
|
||||
}
|
||||
|
||||
info!("{sender_user} created a room with room ID {room_id}");
|
||||
@@ -464,20 +464,17 @@ pub(crate) async fn create_room_route(body: Ruma<create_room::v3::Request>) -> R
|
||||
/// - You have to currently be joined to the room (TODO: Respect history
|
||||
/// visibility)
|
||||
pub(crate) async fn get_room_event_route(
|
||||
body: Ruma<get_room_event::v3::Request>,
|
||||
State(services): State<crate::State>, body: Ruma<get_room_event::v3::Request>,
|
||||
) -> Result<get_room_event::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let event = services()
|
||||
let event = services
|
||||
.rooms
|
||||
.timeline
|
||||
.get_pdu(&body.event_id)?
|
||||
.ok_or_else(|| {
|
||||
warn!("Event not found, event ID: {:?}", &body.event_id);
|
||||
Error::BadRequest(ErrorKind::NotFound, "Event not found.")
|
||||
})?;
|
||||
.ok_or_else(|| err!(Request(NotFound("Event {} not found.", &body.event_id))))?;
|
||||
|
||||
if !services()
|
||||
if !services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.user_can_see_event(sender_user, &event.room_id, &body.event_id)?
|
||||
@@ -502,10 +499,12 @@ pub(crate) async fn get_room_event_route(
|
||||
///
|
||||
/// - Only users joined to the room are allowed to call this, or if
|
||||
/// `history_visibility` is world readable in the room
|
||||
pub(crate) async fn get_room_aliases_route(body: Ruma<aliases::v3::Request>) -> Result<aliases::v3::Response> {
|
||||
pub(crate) async fn get_room_aliases_route(
|
||||
State(services): State<crate::State>, body: Ruma<aliases::v3::Request>,
|
||||
) -> Result<aliases::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
if !services()
|
||||
if !services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.user_can_see_state_events(sender_user, &body.room_id)?
|
||||
@@ -517,7 +516,7 @@ pub(crate) async fn get_room_aliases_route(body: Ruma<aliases::v3::Request>) ->
|
||||
}
|
||||
|
||||
Ok(aliases::v3::Response {
|
||||
aliases: services()
|
||||
aliases: services
|
||||
.rooms
|
||||
.alias
|
||||
.local_aliases_for_room(&body.room_id)
|
||||
@@ -536,10 +535,12 @@ pub(crate) async fn get_room_aliases_route(body: Ruma<aliases::v3::Request>) ->
|
||||
/// - Transfers some state events
|
||||
/// - Moves local aliases
|
||||
/// - Modifies old room power levels to prevent users from speaking
|
||||
pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result<upgrade_room::v3::Response> {
|
||||
pub(crate) async fn upgrade_room_route(
|
||||
State(services): State<crate::State>, body: Ruma<upgrade_room::v3::Request>,
|
||||
) -> Result<upgrade_room::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
if !services()
|
||||
if !services
|
||||
.globals
|
||||
.supported_room_versions()
|
||||
.contains(&body.new_version)
|
||||
@@ -551,19 +552,19 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
}
|
||||
|
||||
// Create a replacement room
|
||||
let replacement_room = RoomId::new(services().globals.server_name());
|
||||
let replacement_room = RoomId::new(services.globals.server_name());
|
||||
|
||||
let _short_id = services()
|
||||
let _short_id = services
|
||||
.rooms
|
||||
.short
|
||||
.get_or_create_shortroomid(&replacement_room)?;
|
||||
|
||||
let state_lock = services().rooms.state.mutex.lock(&body.room_id).await;
|
||||
let state_lock = services.rooms.state.mutex.lock(&body.room_id).await;
|
||||
|
||||
// Send a m.room.tombstone event to the old room to indicate that it is not
|
||||
// intended to be used any further Fail if the sender does not have the required
|
||||
// permissions
|
||||
let tombstone_event_id = services()
|
||||
let tombstone_event_id = services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -577,6 +578,7 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
unsigned: None,
|
||||
state_key: Some(String::new()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
@@ -586,11 +588,11 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
|
||||
// Change lock to replacement room
|
||||
drop(state_lock);
|
||||
let state_lock = services().rooms.state.mutex.lock(&replacement_room).await;
|
||||
let state_lock = services.rooms.state.mutex.lock(&replacement_room).await;
|
||||
|
||||
// Get the old room creation event
|
||||
let mut create_event_content = serde_json::from_str::<CanonicalJsonObject>(
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.room_state_get(&body.room_id, &StateEventType::RoomCreate, "")?
|
||||
@@ -620,16 +622,9 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
})?,
|
||||
);
|
||||
},
|
||||
V11 => {
|
||||
// "creator" key no longer exists in V11 rooms
|
||||
create_event_content.remove("creator");
|
||||
},
|
||||
_ => {
|
||||
warn!("Unexpected or unsupported room version {}", body.new_version);
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::BadJson,
|
||||
"Unexpected or unsupported room version found",
|
||||
));
|
||||
// "creator" key no longer exists in V11+ rooms
|
||||
create_event_content.remove("creator");
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -658,7 +653,7 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
return Err(Error::BadRequest(ErrorKind::BadJson, "Error forming creation event"));
|
||||
}
|
||||
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -668,6 +663,7 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
unsigned: None,
|
||||
state_key: Some(String::new()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&replacement_room,
|
||||
@@ -676,7 +672,7 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
.await?;
|
||||
|
||||
// Join the new room
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -684,11 +680,11 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
event_type: TimelineEventType::RoomMember,
|
||||
content: to_raw_value(&RoomMemberEventContent {
|
||||
membership: MembershipState::Join,
|
||||
displayname: services().users.displayname(sender_user)?,
|
||||
avatar_url: services().users.avatar_url(sender_user)?,
|
||||
displayname: services.users.displayname(sender_user)?,
|
||||
avatar_url: services.users.avatar_url(sender_user)?,
|
||||
is_direct: None,
|
||||
third_party_invite: None,
|
||||
blurhash: services().users.blurhash(sender_user)?,
|
||||
blurhash: services.users.blurhash(sender_user)?,
|
||||
reason: None,
|
||||
join_authorized_via_users_server: None,
|
||||
})
|
||||
@@ -696,6 +692,7 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
unsigned: None,
|
||||
state_key: Some(sender_user.to_string()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&replacement_room,
|
||||
@@ -705,7 +702,7 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
|
||||
// Replicate transferable state events to the new room
|
||||
for event_type in TRANSFERABLE_STATE_EVENTS {
|
||||
let event_content = match services()
|
||||
let event_content = match services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.room_state_get(&body.room_id, event_type, "")?
|
||||
@@ -714,7 +711,7 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
None => continue, // Skipping missing events.
|
||||
};
|
||||
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -724,6 +721,7 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
unsigned: None,
|
||||
state_key: Some(String::new()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&replacement_room,
|
||||
@@ -733,13 +731,18 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
}
|
||||
|
||||
// Moves any local aliases to the new room
|
||||
for alias in services()
|
||||
for alias in services
|
||||
.rooms
|
||||
.alias
|
||||
.local_aliases_for_room(&body.room_id)
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.alias
|
||||
.remove_alias(&alias, sender_user)
|
||||
.await?;
|
||||
services
|
||||
.rooms
|
||||
.alias
|
||||
.set_alias(&alias, &replacement_room, sender_user)?;
|
||||
@@ -747,7 +750,7 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
|
||||
// Get the old room power levels
|
||||
let mut power_levels_event_content: RoomPowerLevelsEventContent = serde_json::from_str(
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.room_state_get(&body.room_id, &StateEventType::RoomPowerLevels, "")?
|
||||
@@ -772,7 +775,7 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
|
||||
// Modify the power levels in the old room to prevent sending of events and
|
||||
// inviting new users
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
@@ -782,6 +785,7 @@ pub(crate) async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) ->
|
||||
unsigned: None,
|
||||
state_key: Some(String::new()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
@@ -841,7 +845,7 @@ fn default_power_levels_content(
|
||||
|
||||
/// if a room is being created with a room alias, run our checks
|
||||
async fn room_alias_check(
|
||||
room_alias_name: &str, appservice_info: &Option<RegistrationInfo>,
|
||||
services: &Services, room_alias_name: &str, appservice_info: &Option<RegistrationInfo>,
|
||||
) -> Result<OwnedRoomAliasId> {
|
||||
// Basic checks on the room alias validity
|
||||
if room_alias_name.contains(':') {
|
||||
@@ -858,7 +862,7 @@ async fn room_alias_check(
|
||||
}
|
||||
|
||||
// check if room alias is forbidden
|
||||
if services()
|
||||
if services
|
||||
.globals
|
||||
.forbidden_alias_names()
|
||||
.is_match(room_alias_name)
|
||||
@@ -866,13 +870,13 @@ async fn room_alias_check(
|
||||
return Err(Error::BadRequest(ErrorKind::Unknown, "Room alias name is forbidden."));
|
||||
}
|
||||
|
||||
let full_room_alias = RoomAliasId::parse(format!("#{}:{}", room_alias_name, services().globals.config.server_name))
|
||||
let full_room_alias = RoomAliasId::parse(format!("#{}:{}", room_alias_name, services.globals.config.server_name))
|
||||
.map_err(|e| {
|
||||
info!("Failed to parse room alias {room_alias_name}: {e}");
|
||||
Error::BadRequest(ErrorKind::InvalidParam, "Invalid room alias specified.")
|
||||
})?;
|
||||
info!("Failed to parse room alias {room_alias_name}: {e}");
|
||||
Error::BadRequest(ErrorKind::InvalidParam, "Invalid room alias specified.")
|
||||
})?;
|
||||
|
||||
if services()
|
||||
if services
|
||||
.rooms
|
||||
.alias
|
||||
.resolve_local_alias(&full_room_alias)?
|
||||
@@ -885,7 +889,7 @@ async fn room_alias_check(
|
||||
if !info.aliases.is_match(full_room_alias.as_str()) {
|
||||
return Err(Error::BadRequest(ErrorKind::Exclusive, "Room alias is not in namespace."));
|
||||
}
|
||||
} else if services()
|
||||
} else if services
|
||||
.appservice
|
||||
.is_exclusive_alias(&full_room_alias)
|
||||
.await
|
||||
@@ -899,9 +903,9 @@ async fn room_alias_check(
|
||||
}
|
||||
|
||||
/// if a room is being created with a custom room ID, run our checks against it
|
||||
fn custom_room_id_check(custom_room_id: &str) -> Result<OwnedRoomId> {
|
||||
fn custom_room_id_check(services: &Services, custom_room_id: &str) -> Result<OwnedRoomId> {
|
||||
// apply forbidden room alias checks to custom room IDs too
|
||||
if services()
|
||||
if services
|
||||
.globals
|
||||
.forbidden_alias_names()
|
||||
.is_match(custom_room_id)
|
||||
@@ -922,7 +926,7 @@ fn custom_room_id_check(custom_room_id: &str) -> Result<OwnedRoomId> {
|
||||
));
|
||||
}
|
||||
|
||||
let full_room_id = format!("!{}:{}", custom_room_id, services().globals.config.server_name);
|
||||
let full_room_id = format!("!{}:{}", custom_room_id, services.globals.config.server_name);
|
||||
|
||||
debug_info!("Full custom room ID: {full_room_id}");
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use axum::extract::State;
|
||||
use ruma::{
|
||||
api::client::{
|
||||
error::ErrorKind,
|
||||
@@ -14,7 +15,7 @@
|
||||
};
|
||||
use tracing::debug;
|
||||
|
||||
use crate::{services, Error, Result, Ruma};
|
||||
use crate::{Error, Result, Ruma};
|
||||
|
||||
/// # `POST /_matrix/client/r0/search`
|
||||
///
|
||||
@@ -22,7 +23,9 @@
|
||||
///
|
||||
/// - Only works if the user is currently joined to the room (TODO: Respect
|
||||
/// history visibility)
|
||||
pub(crate) async fn search_events_route(body: Ruma<search_events::v3::Request>) -> Result<search_events::v3::Response> {
|
||||
pub(crate) async fn search_events_route(
|
||||
State(services): State<crate::State>, body: Ruma<search_events::v3::Request>,
|
||||
) -> Result<search_events::v3::Response> {
|
||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||
|
||||
let search_criteria = body.search_categories.room_events.as_ref().unwrap();
|
||||
@@ -30,7 +33,7 @@ pub(crate) async fn search_events_route(body: Ruma<search_events::v3::Request>)
|
||||
let include_state = &search_criteria.include_state;
|
||||
|
||||
let room_ids = filter.rooms.clone().unwrap_or_else(|| {
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.state_cache
|
||||
.rooms_joined(sender_user)
|
||||
@@ -50,11 +53,7 @@ pub(crate) async fn search_events_route(body: Ruma<search_events::v3::Request>)
|
||||
|
||||
if include_state.is_some_and(|include_state| include_state) {
|
||||
for room_id in &room_ids {
|
||||
if !services()
|
||||
.rooms
|
||||
.state_cache
|
||||
.is_joined(sender_user, room_id)?
|
||||
{
|
||||
if !services.rooms.state_cache.is_joined(sender_user, room_id)? {
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::forbidden(),
|
||||
"You don't have permission to view this room.",
|
||||
@@ -62,12 +61,12 @@ pub(crate) async fn search_events_route(body: Ruma<search_events::v3::Request>)
|
||||
}
|
||||
|
||||
// check if sender_user can see state events
|
||||
if services()
|
||||
if services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.user_can_see_state_events(sender_user, room_id)?
|
||||
{
|
||||
let room_state = services()
|
||||
let room_state = services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.room_state_full(room_id)
|
||||
@@ -91,18 +90,14 @@ pub(crate) async fn search_events_route(body: Ruma<search_events::v3::Request>)
|
||||
let mut searches = Vec::new();
|
||||
|
||||
for room_id in &room_ids {
|
||||
if !services()
|
||||
.rooms
|
||||
.state_cache
|
||||
.is_joined(sender_user, room_id)?
|
||||
{
|
||||
if !services.rooms.state_cache.is_joined(sender_user, room_id)? {
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::forbidden(),
|
||||
"You don't have permission to view this room.",
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(search) = services()
|
||||
if let Some(search) = services
|
||||
.rooms
|
||||
.search
|
||||
.search_pdus(room_id, &search_criteria.search_term)?
|
||||
@@ -135,14 +130,14 @@ pub(crate) async fn search_events_route(body: Ruma<search_events::v3::Request>)
|
||||
.iter()
|
||||
.skip(skip)
|
||||
.filter_map(|result| {
|
||||
services()
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.get_pdu_from_id(result)
|
||||
.ok()?
|
||||
.filter(|pdu| {
|
||||
!pdu.is_redacted()
|
||||
&& services()
|
||||
&& services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.user_can_see_event(sender_user, &pdu.room_id, &pdu.event_id)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user