forked from jmug/stoatchat
Compare commits
69
Commits
20230103-1
...
20230421-3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43e45aef3f | ||
|
|
c5880596a4 | ||
|
|
59a644891d | ||
|
|
a326cdc736 | ||
|
|
03a28dbb3e | ||
|
|
32542a822e | ||
|
|
1df90ff53b | ||
|
|
487b979f0d | ||
|
|
b9d813d8f0 | ||
|
|
36dd128459 | ||
|
|
144f0d39c6 | ||
|
|
32a294a64a | ||
|
|
b7b70346b4 | ||
|
|
59832e6ba2 | ||
|
|
f309218573 | ||
|
|
0321eff62b | ||
|
|
4c8ea31d98 | ||
|
|
92ac86a6bd | ||
|
|
13ed69c82a | ||
|
|
b83f6da648 | ||
|
|
89f1167239 | ||
|
|
82d868751f | ||
|
|
31b9f18921 | ||
|
|
fd80823910 | ||
|
|
6bd8221eda | ||
|
|
ce77e926a5 | ||
|
|
2710edb76b | ||
|
|
8f1ff9e774 | ||
|
|
c09244039e | ||
|
|
bf9108408e | ||
|
|
304336d905 | ||
|
|
42b4906594 | ||
|
|
3038fb230f | ||
|
|
73af105feb | ||
|
|
2de37b23c1 | ||
|
|
0c75d8c8b3 | ||
|
|
be793b1570 | ||
|
|
5a3a97df34 | ||
|
|
0c072b01d7 | ||
|
|
056c0380b2 | ||
|
|
49598daf70 | ||
|
|
0445181d5b | ||
|
|
e780178cc0 | ||
|
|
c4b9884825 | ||
|
|
fdab997d17 | ||
|
|
8e0addc3e0 | ||
|
|
0da4baf777 | ||
|
|
c03fcda85b | ||
|
|
0afbcc065f | ||
|
|
a406e5504d | ||
|
|
e8c233f60b | ||
|
|
72595f30d4 | ||
|
|
39e345af74 | ||
|
|
e0b918771d | ||
|
|
7a6bd70dcd | ||
|
|
c0ef3d295a | ||
|
|
f5c95f9d12 | ||
|
|
fed1da72fd | ||
|
|
cf9c0bc5e1 | ||
|
|
cc2054838a | ||
|
|
d9d2735efa | ||
|
|
94b0472934 | ||
|
|
4a7917e9ea | ||
|
|
ce6b454874 | ||
|
|
fc32996b51 | ||
|
|
d74104fae4 | ||
|
|
32d3683013 | ||
|
|
0cebb69e02 | ||
|
|
117958d8cd |
No files matched your search
@@ -1,2 +0,0 @@
|
|||||||
ko_fi: insertish
|
|
||||||
custom: https://insrt.uk/donate
|
|
||||||
@@ -20,47 +20,52 @@ on:
|
|||||||
- "Dockerfile"
|
- "Dockerfile"
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
base:
|
base:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
name: Build base image (amd64)
|
name: Build base image
|
||||||
steps:
|
steps:
|
||||||
# Configure build environment
|
# Configure build environment
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v2
|
uses: docker/setup-buildx-action@v2
|
||||||
|
|
||||||
# Authenticate with GHCR
|
# Authenticate with GHCR
|
||||||
- name: Login to Github Container Registry
|
- name: Login to Github Container Registry
|
||||||
uses: docker/login-action@v1
|
if: ${{ github.event_name != 'pull_request' }}
|
||||||
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
# Build all projects and cache
|
- name: Build base image
|
||||||
- name: Build Base Image
|
uses: docker/build-push-action@v4
|
||||||
uses: docker/build-push-action@v3
|
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
push: true
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
tags: ghcr.io/revoltchat/base:latest
|
platforms: linux/amd64,linux/arm64
|
||||||
cache-from: type=gha
|
tags: ghcr.io/${{ github.repository_owner }}/base:latest
|
||||||
cache-to: type=gha,mode=max
|
cache-from: type=gha,scope=buildx-base-multi-arch
|
||||||
|
cache-to: type=gha,scope=buildx-base-multi-arch,mode=max
|
||||||
|
|
||||||
publish_amd64:
|
publish:
|
||||||
needs: [base]
|
needs: [base]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
if: github.event_name != 'pull_request'
|
if: github.event_name != 'pull_request'
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
project: [delta, bonfire]
|
project: [delta, bonfire]
|
||||||
name: Build ${{ matrix.project }} image (amd64)
|
name: Build ${{ matrix.project }} image
|
||||||
steps:
|
steps:
|
||||||
# Configure build environment
|
# Configure build environment
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v2
|
uses: docker/setup-buildx-action@v2
|
||||||
|
|
||||||
@@ -68,10 +73,11 @@ jobs:
|
|||||||
- name: Login to DockerHub
|
- name: Login to DockerHub
|
||||||
uses: docker/login-action@v2
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
|
registry: docker.io
|
||||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
- name: Login to Github Container Registry
|
- name: Login to Github Container Registry
|
||||||
uses: docker/login-action@v1
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
@@ -86,11 +92,11 @@ jobs:
|
|||||||
{
|
{
|
||||||
"delta": {
|
"delta": {
|
||||||
"path": "crates/delta",
|
"path": "crates/delta",
|
||||||
"tag": "revoltchat/server"
|
"tag": "${{ github.repository_owner }}/server"
|
||||||
},
|
},
|
||||||
"bonfire": {
|
"bonfire": {
|
||||||
"path": "crates/bonfire",
|
"path": "crates/bonfire",
|
||||||
"tag": "revoltchat/bonfire"
|
"tag": "${{ github.repository_owner }}/bonfire"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export_to: output
|
export_to: output
|
||||||
@@ -98,19 +104,21 @@ jobs:
|
|||||||
# Configure metadata
|
# Configure metadata
|
||||||
- name: Docker meta
|
- name: Docker meta
|
||||||
id: meta
|
id: meta
|
||||||
uses: docker/metadata-action@v3
|
uses: docker/metadata-action@v4
|
||||||
with:
|
with:
|
||||||
images: ${{ steps.export.outputs.tag }}, ghcr.io/${{ steps.export.outputs.tag }}
|
images: |
|
||||||
|
docker.io/${{ steps.export.outputs.tag }}
|
||||||
|
ghcr.io/${{ steps.export.outputs.tag }}
|
||||||
|
|
||||||
# Build crate image
|
# Build crate image
|
||||||
- name: Publish
|
- name: Publish
|
||||||
uses: docker/build-push-action@v3
|
uses: docker/build-push-action@v4
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
push: true
|
push: true
|
||||||
platforms: linux/amd64
|
platforms: linux/amd64,linux/arm64
|
||||||
file: ${{ steps.export.outputs.path }}/Dockerfile
|
file: ${{ steps.export.outputs.path }}/Dockerfile
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
build-args: |
|
||||||
|
BASE_IMAGE=ghcr.io/${{ github.repository_owner }}/base:latest
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
cache-from: type=gha
|
|
||||||
cache-to: type=gha,mode=max
|
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
name: Rust build and test
|
name: Rust build, test, and generate specification
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ master ]
|
branches: [master]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ master ]
|
branches: [master]
|
||||||
|
|
||||||
env:
|
env:
|
||||||
CARGO_TERM_COLOR: always
|
CARGO_TERM_COLOR: always
|
||||||
@@ -15,19 +15,62 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- name: Install latest nightly
|
- name: Install latest stable
|
||||||
uses: actions-rs/toolchain@v1
|
uses: actions-rs/toolchain@v1
|
||||||
with:
|
with:
|
||||||
toolchain: nightly
|
toolchain: stable
|
||||||
override: true
|
override: true
|
||||||
components: rustfmt, clippy
|
components: rustfmt, clippy
|
||||||
|
|
||||||
- name: Run cargo build
|
- name: Run cargo build
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
command: build
|
command: build
|
||||||
|
|
||||||
- name: Run cargo test
|
- name: Run cargo test
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
command: test
|
command: test
|
||||||
|
|
||||||
|
- name: Copy .env.example
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
run: |
|
||||||
|
cp .env.example .env
|
||||||
|
|
||||||
|
- name: Run services in background
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
run: |
|
||||||
|
docker-compose -f docker-compose.db.yml up -d
|
||||||
|
|
||||||
|
- name: Start API in background
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
run: |
|
||||||
|
cargo run --bin revolt-delta &
|
||||||
|
|
||||||
|
- name: Wait for API to go up
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
uses: nev7n/wait_for_response@v1
|
||||||
|
with:
|
||||||
|
url: "http://localhost:8000/"
|
||||||
|
|
||||||
|
- name: Checkout API repository
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
repository: revoltchat/api
|
||||||
|
path: api
|
||||||
|
token: ${{ secrets.PAT }}
|
||||||
|
|
||||||
|
- name: Download OpenAPI specification
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
run: curl http://localhost:8000/openapi.json -o api/OpenAPI.json
|
||||||
|
|
||||||
|
- name: Commit changes
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
uses: EndBug/add-and-commit@v4
|
||||||
|
with:
|
||||||
|
cwd: "api"
|
||||||
|
add: "*.json"
|
||||||
|
author_name: Revolt CI
|
||||||
|
author_email: revolt-ci@users.noreply.github.com
|
||||||
|
message: "chore: generate OpenAPI specification"
|
||||||
@@ -15,22 +15,27 @@ jobs:
|
|||||||
gh api graphql -f query='
|
gh api graphql -f query='
|
||||||
query {
|
query {
|
||||||
organization(login: "revoltchat"){
|
organization(login: "revoltchat"){
|
||||||
projectNext(number: 3) {
|
projectV2(number: 3) {
|
||||||
id
|
id
|
||||||
fields(first:20) {
|
fields(first:20) {
|
||||||
nodes {
|
nodes {
|
||||||
id
|
... on ProjectV2SingleSelectField {
|
||||||
name
|
id
|
||||||
settings
|
name
|
||||||
|
options {
|
||||||
|
id
|
||||||
|
name
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}' > project_data.json
|
}' > project_data.json
|
||||||
|
|
||||||
echo 'PROJECT_ID='$(jq '.data.organization.projectNext.id' project_data.json) >> $GITHUB_ENV
|
echo 'PROJECT_ID='$(jq '.data.organization.projectV2.id' project_data.json) >> $GITHUB_ENV
|
||||||
echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV
|
echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV
|
||||||
echo 'TODO_OPTION_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") |.settings | fromjson.options[] | select(.name=="Todo") |.id' project_data.json) >> $GITHUB_ENV
|
echo 'TODO_OPTION_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Status") | .options[] | select(.name=="Todo") |.id' project_data.json) >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: Add issue to project
|
- name: Add issue to project
|
||||||
env:
|
env:
|
||||||
@@ -39,11 +44,11 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
item_id="$( gh api graphql -f query='
|
item_id="$( gh api graphql -f query='
|
||||||
mutation($project:ID!, $issue:ID!) {
|
mutation($project:ID!, $issue:ID!) {
|
||||||
addProjectNextItem(input: {projectId: $project, contentId: $issue}) {
|
addProjectV2ItemById(input: {projectId: $project, contentId: $issue}) {
|
||||||
projectNextItem {
|
item {
|
||||||
id
|
id
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}' -f project=$PROJECT_ID -f issue=$ISSUE_ID --jq '.data.addProjectNextItem.projectNextItem.id')"
|
}' -f project=$PROJECT_ID -f issue=$ISSUE_ID --jq '.data.addProjectV2ItemById.item.id')"
|
||||||
|
|
||||||
echo 'ITEM_ID='$item_id >> $GITHUB_ENV
|
echo 'ITEM_ID='$item_id >> $GITHUB_ENV
|
||||||
@@ -15,22 +15,27 @@ jobs:
|
|||||||
gh api graphql -f query='
|
gh api graphql -f query='
|
||||||
query {
|
query {
|
||||||
organization(login: "revoltchat"){
|
organization(login: "revoltchat"){
|
||||||
projectNext(number: 3) {
|
projectV2(number: 3) {
|
||||||
id
|
id
|
||||||
fields(first:20) {
|
fields(first:20) {
|
||||||
nodes {
|
nodes {
|
||||||
id
|
... on ProjectV2SingleSelectField {
|
||||||
name
|
id
|
||||||
settings
|
name
|
||||||
|
options {
|
||||||
|
id
|
||||||
|
name
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}' > project_data.json
|
}' > project_data.json
|
||||||
|
|
||||||
echo 'PROJECT_ID='$(jq '.data.organization.projectNext.id' project_data.json) >> $GITHUB_ENV
|
echo 'PROJECT_ID='$(jq '.data.organization.projectV2.id' project_data.json) >> $GITHUB_ENV
|
||||||
echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV
|
echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV
|
||||||
echo 'INCOMING_OPTION_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") |.settings | fromjson.options[] | select(.name=="Incoming PRs") |.id' project_data.json) >> $GITHUB_ENV
|
echo 'INCOMING_OPTION_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Status") | .options[] | select(.name=="Incoming PRs") |.id' project_data.json) >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: Add PR to project
|
- name: Add PR to project
|
||||||
env:
|
env:
|
||||||
@@ -39,13 +44,13 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
item_id="$( gh api graphql -f query='
|
item_id="$( gh api graphql -f query='
|
||||||
mutation($project:ID!, $pr:ID!) {
|
mutation($project:ID!, $pr:ID!) {
|
||||||
addProjectNextItem(input: {projectId: $project, contentId: $pr}) {
|
addProjectV2ItemById(input: {projectId: $project, contentId: $pr}) {
|
||||||
projectNextItem {
|
item {
|
||||||
id
|
id
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}' -f project=$PROJECT_ID -f pr=$PR_ID --jq '.data.addProjectNextItem.projectNextItem.id')"
|
}' -f project=$PROJECT_ID -f pr=$PR_ID --jq '.data.addProjectV2ItemById.item.id')"
|
||||||
|
|
||||||
echo 'ITEM_ID='$item_id >> $GITHUB_ENV
|
echo 'ITEM_ID='$item_id >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: Set fields
|
- name: Set fields
|
||||||
@@ -59,14 +64,16 @@ jobs:
|
|||||||
$status_field: ID!
|
$status_field: ID!
|
||||||
$status_value: String!
|
$status_value: String!
|
||||||
) {
|
) {
|
||||||
set_status: updateProjectNextItemField(input: {
|
set_status: updateProjectV2ItemFieldValue(input: {
|
||||||
projectId: $project
|
projectId: $project
|
||||||
itemId: $item
|
itemId: $item
|
||||||
fieldId: $status_field
|
fieldId: $status_field
|
||||||
value: $status_value
|
value: {
|
||||||
|
singleSelectOptionId: $status_value
|
||||||
|
}
|
||||||
}) {
|
}) {
|
||||||
projectNextItem {
|
projectV2Item {
|
||||||
id
|
id
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}' -f project=$PROJECT_ID -f item=$ITEM_ID -f status_field=$STATUS_FIELD_ID -f status_value=${{ env.INCOMING_OPTION_ID }} --silent
|
}' -f project=$PROJECT_ID -f item=$ITEM_ID -f status_field=$STATUS_FIELD_ID -f status_value=${{ env.INCOMING_OPTION_ID }} --silent
|
||||||
Generated
+357
-215
File diff suppressed because it is too large.
Load diff
@@ -1,2 +1,6 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = ["crates/*"]
|
members = ["crates/*"]
|
||||||
|
|
||||||
|
[patch.crates-io]
|
||||||
|
# mobc-redis = { git = "https://github.com/insertish/mobc", rev = "8b880bb59f2ba80b4c7bc40c649c113d8857a186" }
|
||||||
|
redis = { git = "https://github.com/insertish/redis-rs", rev = "6575a6b1c09eb8c9cc7f0082d95fe6b8f903c4d7" }
|
||||||
+20
-5
@@ -1,12 +1,27 @@
|
|||||||
# Build Stage
|
# Build Stage
|
||||||
FROM rustlang/rust:nightly-slim AS builder
|
FROM --platform="${BUILDPLATFORM}" rustlang/rust:nightly-slim
|
||||||
USER 0:0
|
USER 0:0
|
||||||
WORKDIR /home/rust/src
|
WORKDIR /home/rust/src
|
||||||
|
|
||||||
# Install build requirements
|
ARG TARGETARCH
|
||||||
RUN apt-get update && apt-get install -y libssl-dev pkg-config
|
|
||||||
|
|
||||||
# Build all crates
|
# Install build requirements
|
||||||
|
RUN dpkg --add-architecture "${TARGETARCH}"
|
||||||
|
RUN apt-get update && \
|
||||||
|
apt-get install -y \
|
||||||
|
make \
|
||||||
|
pkg-config \
|
||||||
|
libssl-dev:"${TARGETARCH}"
|
||||||
|
COPY scripts/build-image-layer.sh /tmp/
|
||||||
|
RUN sh /tmp/build-image-layer.sh tools
|
||||||
|
|
||||||
|
# Build all dependencies
|
||||||
COPY Cargo.toml Cargo.lock ./
|
COPY Cargo.toml Cargo.lock ./
|
||||||
|
COPY crates/bonfire/Cargo.toml ./crates/bonfire/
|
||||||
|
COPY crates/delta/Cargo.toml ./crates/delta/
|
||||||
|
COPY crates/quark/Cargo.toml ./crates/quark/
|
||||||
|
RUN sh /tmp/build-image-layer.sh deps
|
||||||
|
|
||||||
|
# Build all apps
|
||||||
COPY crates ./crates
|
COPY crates ./crates
|
||||||
RUN cargo build --locked --release
|
RUN sh /tmp/build-image-layer.sh apps
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# Build base image
|
|
||||||
docker build -t revolt.chat/base:latest -f Dockerfile .
|
|
||||||
|
|
||||||
# Build crates
|
|
||||||
docker build -t revolt.chat/delta:latest -f crates/delta/Dockerfile .
|
|
||||||
docker build -t revolt.chat/bonfire:latest -f crates/bonfire/Dockerfile .
|
|
||||||
Vendored
-2
@@ -1,2 +0,0 @@
|
|||||||
ko_fi: insertish
|
|
||||||
custom: https://insrt.uk/donate
|
|
||||||
-98
@@ -1,98 +0,0 @@
|
|||||||
name: Docker
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- "master"
|
|
||||||
tags:
|
|
||||||
- "*"
|
|
||||||
paths-ignore:
|
|
||||||
- ".github/**"
|
|
||||||
- "!.github/workflows/docker.yml"
|
|
||||||
- ".vscode/**"
|
|
||||||
- ".gitignore"
|
|
||||||
- ".gitlab-ci.yml"
|
|
||||||
- "LICENSE"
|
|
||||||
- "README"
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- "master"
|
|
||||||
paths:
|
|
||||||
- "Dockerfile"
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
test:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
architecture: [linux/amd64]
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
with:
|
|
||||||
submodules: "recursive"
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v1
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v1
|
|
||||||
- name: Cache Docker layers
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: /tmp/.buildx-cache/${{ matrix.architecture }}
|
|
||||||
key: ${{ runner.os }}-buildx-${{ matrix.architecture }}-${{ github.sha }}
|
|
||||||
- name: Build
|
|
||||||
uses: docker/build-push-action@v2
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
platforms: ${{ matrix.architecture }}
|
|
||||||
cache-from: type=local,src=/tmp/.buildx-cache/${{ matrix.architecture }}
|
|
||||||
cache-to: type=local,dest=/tmp/.buildx-cache-new/${{ matrix.architecture }},mode=max
|
|
||||||
- name: Move cache
|
|
||||||
run: |
|
|
||||||
rm -rf /tmp/.buildx-cache/${{ matrix.architecture }}
|
|
||||||
mv /tmp/.buildx-cache-new/${{ matrix.architecture }} /tmp/.buildx-cache/${{ matrix.architecture }}
|
|
||||||
|
|
||||||
publish_amd64:
|
|
||||||
needs: [test]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
if: github.event_name != 'pull_request'
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
with:
|
|
||||||
submodules: "recursive"
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v1
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v1
|
|
||||||
- name: Cache amd64 Docker layers
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: /tmp/.buildx-cache/linux/amd64
|
|
||||||
key: ${{ runner.os }}-buildx-linux/amd64-${{ github.sha }}
|
|
||||||
- name: Docker meta
|
|
||||||
id: meta
|
|
||||||
uses: docker/metadata-action@v3
|
|
||||||
with:
|
|
||||||
images: ghcr.io/revoltchat/bonfire
|
|
||||||
- name: Login to Github Container Registry
|
|
||||||
uses: docker/login-action@v1
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: ${{ github.actor }}
|
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
- name: Build and publish
|
|
||||||
uses: docker/build-push-action@v2
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
push: true
|
|
||||||
platforms: linux/amd64
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
|
||||||
cache-from: type=local,src=/tmp/.buildx-cache/linux/amd64
|
|
||||||
cache-to: type=local,dest=/tmp/.buildx-cache-new,mode=max
|
|
||||||
- name: Move cache
|
|
||||||
run: |
|
|
||||||
rm -rf /tmp/.buildx-cache
|
|
||||||
mv /tmp/.buildx-cache-new /tmp/.buildx-cache
|
|
||||||
-33
@@ -1,33 +0,0 @@
|
|||||||
name: Rust build and test
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [ master ]
|
|
||||||
pull_request:
|
|
||||||
branches: [ master ]
|
|
||||||
|
|
||||||
env:
|
|
||||||
CARGO_TERM_COLOR: always
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
check:
|
|
||||||
name: Rust project
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
- name: Install latest nightly
|
|
||||||
uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: nightly
|
|
||||||
override: true
|
|
||||||
components: rustfmt, clippy
|
|
||||||
|
|
||||||
- name: Run cargo build
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: build
|
|
||||||
|
|
||||||
- name: Run cargo test
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
name: Add Issue to Board
|
|
||||||
|
|
||||||
on:
|
|
||||||
issues:
|
|
||||||
types: [opened]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
track_issue:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Get project data
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.PAT }}
|
|
||||||
run: |
|
|
||||||
gh api graphql -f query='
|
|
||||||
query {
|
|
||||||
organization(login: "revoltchat"){
|
|
||||||
projectNext(number: 3) {
|
|
||||||
id
|
|
||||||
fields(first:20) {
|
|
||||||
nodes {
|
|
||||||
id
|
|
||||||
name
|
|
||||||
settings
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}' > project_data.json
|
|
||||||
|
|
||||||
echo 'PROJECT_ID='$(jq '.data.organization.projectNext.id' project_data.json) >> $GITHUB_ENV
|
|
||||||
echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV
|
|
||||||
echo 'TODO_OPTION_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") |.settings | fromjson.options[] | select(.name=="Todo") |.id' project_data.json) >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Add issue to project
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.PAT }}
|
|
||||||
ISSUE_ID: ${{ github.event.issue.node_id }}
|
|
||||||
run: |
|
|
||||||
item_id="$( gh api graphql -f query='
|
|
||||||
mutation($project:ID!, $issue:ID!) {
|
|
||||||
addProjectNextItem(input: {projectId: $project, contentId: $issue}) {
|
|
||||||
projectNextItem {
|
|
||||||
id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}' -f project=$PROJECT_ID -f issue=$ISSUE_ID --jq '.data.addProjectNextItem.projectNextItem.id')"
|
|
||||||
|
|
||||||
echo 'ITEM_ID='$item_id >> $GITHUB_ENV
|
|
||||||
-72
@@ -1,72 +0,0 @@
|
|||||||
name: Add PR to Board
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request_target:
|
|
||||||
types: [opened, synchronize, ready_for_review, review_requested]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
track_pr:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Get project data
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.PAT }}
|
|
||||||
run: |
|
|
||||||
gh api graphql -f query='
|
|
||||||
query {
|
|
||||||
organization(login: "revoltchat"){
|
|
||||||
projectNext(number: 3) {
|
|
||||||
id
|
|
||||||
fields(first:20) {
|
|
||||||
nodes {
|
|
||||||
id
|
|
||||||
name
|
|
||||||
settings
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}' > project_data.json
|
|
||||||
|
|
||||||
echo 'PROJECT_ID='$(jq '.data.organization.projectNext.id' project_data.json) >> $GITHUB_ENV
|
|
||||||
echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV
|
|
||||||
echo 'INCOMING_OPTION_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") |.settings | fromjson.options[] | select(.name=="Incoming PRs") |.id' project_data.json) >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Add PR to project
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.PAT }}
|
|
||||||
PR_ID: ${{ github.event.pull_request.node_id }}
|
|
||||||
run: |
|
|
||||||
item_id="$( gh api graphql -f query='
|
|
||||||
mutation($project:ID!, $pr:ID!) {
|
|
||||||
addProjectNextItem(input: {projectId: $project, contentId: $pr}) {
|
|
||||||
projectNextItem {
|
|
||||||
id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}' -f project=$PROJECT_ID -f pr=$PR_ID --jq '.data.addProjectNextItem.projectNextItem.id')"
|
|
||||||
|
|
||||||
echo 'ITEM_ID='$item_id >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Set fields
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.PAT }}
|
|
||||||
run: |
|
|
||||||
gh api graphql -f query='
|
|
||||||
mutation (
|
|
||||||
$project: ID!
|
|
||||||
$item: ID!
|
|
||||||
$status_field: ID!
|
|
||||||
$status_value: String!
|
|
||||||
) {
|
|
||||||
set_status: updateProjectNextItemField(input: {
|
|
||||||
projectId: $project
|
|
||||||
itemId: $item
|
|
||||||
fieldId: $status_field
|
|
||||||
value: $status_value
|
|
||||||
}) {
|
|
||||||
projectNextItem {
|
|
||||||
id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}' -f project=$PROJECT_ID -f item=$ITEM_ID -f status_field=$STATUS_FIELD_ID -f status_value=${{ env.INCOMING_OPTION_ID }} --silent
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-bonfire"
|
name = "revolt-bonfire"
|
||||||
version = "0.5.5"
|
version = "0.5.19"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
# Build Stage
|
# Build Stage
|
||||||
FROM ghcr.io/revoltchat/base:latest AS builder
|
FROM ghcr.io/revoltchat/base:latest AS builder
|
||||||
RUN cargo install --locked --path crates/bonfire
|
|
||||||
|
|
||||||
# Bundle Stage
|
# Bundle Stage
|
||||||
FROM debian:buster-slim
|
FROM debian:bullseye-slim
|
||||||
RUN apt-get update && apt-get install -y ca-certificates
|
RUN apt-get update && \
|
||||||
COPY --from=builder /usr/local/cargo/bin/revolt-bonfire ./
|
apt-get install -y ca-certificates && \
|
||||||
|
apt-get clean
|
||||||
|
COPY --from=builder /home/rust/src/target/release/revolt-bonfire ./
|
||||||
EXPOSE 9000
|
EXPOSE 9000
|
||||||
CMD ["./revolt-bonfire"]
|
CMD ["./revolt-bonfire"]
|
||||||
+8
-12
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-delta"
|
name = "revolt-delta"
|
||||||
version = "0.5.5"
|
version = "0.5.19"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
@@ -15,9 +15,8 @@ log = "0.4.11"
|
|||||||
dotenv = "0.15.0"
|
dotenv = "0.15.0"
|
||||||
dashmap = "5.2.0"
|
dashmap = "5.2.0"
|
||||||
linkify = "0.6.0"
|
linkify = "0.6.0"
|
||||||
once_cell = "1.4.1"
|
once_cell = "1.17.1"
|
||||||
env_logger = "0.7.1"
|
env_logger = "0.7.1"
|
||||||
lazy_static = "1.4.0"
|
|
||||||
|
|
||||||
# Lang. Utilities
|
# Lang. Utilities
|
||||||
regex = "1"
|
regex = "1"
|
||||||
@@ -44,20 +43,17 @@ async-std = { version = "1.8.0", features = ["tokio1", "tokio02", "attributes"]
|
|||||||
# internal util
|
# internal util
|
||||||
lettre = "0.10.0-alpha.4"
|
lettre = "0.10.0-alpha.4"
|
||||||
|
|
||||||
# redis
|
|
||||||
redis = { version = "0.21.2", features = ["async-std-comp"] }
|
|
||||||
mobc = { version = "0.7.3" }
|
|
||||||
mobc-redis = { version = "0.7.0", default-features = false, features = ["async-std-comp"] }
|
|
||||||
|
|
||||||
# web
|
# web
|
||||||
rocket = { version = "0.5.0-rc.2", default-features = false, features = ["json"] }
|
rocket = { version = "0.5.0-rc.2", default-features = false, features = ["json"] }
|
||||||
rocket_empty = { git = "https://github.com/insertish/rocket_empty", branch = "master" }
|
rocket_empty = { version = "0.1.1", features = ["schema"] }
|
||||||
rocket_rauth = { git = "https://github.com/insertish/rauth", rev = "cbdec69c684a4854fbedba9ed1f0e7ee466bf3f7" }
|
rocket_authifier = { version = "1.0.7" }
|
||||||
|
|
||||||
# spec generation
|
# spec generation
|
||||||
schemars = "0.8.8"
|
schemars = "0.8.8"
|
||||||
# rocket_okapi = "0.8.0-rc.1"
|
revolt_rocket_okapi = { version = "0.9.1", features = [ "swagger" ] }
|
||||||
rocket_okapi = { git = "https://github.com/insertish/okapi", rev = "a1048d0c8cd771e424ec97d33d825c32e06aa120", features = [ "swagger" ] }
|
|
||||||
|
|
||||||
# quark
|
# quark
|
||||||
revolt-quark = { path = "../quark" }
|
revolt-quark = { path = "../quark" }
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
vergen = "7.5.0"
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
# Build Stage
|
# Build Stage
|
||||||
FROM ghcr.io/revoltchat/base:latest AS builder
|
FROM ghcr.io/revoltchat/base:latest AS builder
|
||||||
RUN cargo install --locked --path crates/delta
|
|
||||||
|
|
||||||
# Bundle Stage
|
# Bundle Stage
|
||||||
FROM debian:buster-slim
|
FROM debian:bullseye-slim
|
||||||
RUN apt-get update && apt-get install -y ca-certificates
|
RUN apt-get update && \
|
||||||
COPY --from=builder /usr/local/cargo/bin/revolt-delta ./
|
apt-get install -y ca-certificates && \
|
||||||
|
apt-get clean
|
||||||
|
COPY --from=builder /home/rust/src/target/release/revolt-delta ./
|
||||||
|
|
||||||
EXPOSE 8000
|
EXPOSE 8000
|
||||||
ENV ROCKET_ADDRESS 0.0.0.0
|
ENV ROCKET_ADDRESS 0.0.0.0
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
use vergen::{vergen, Config};
|
||||||
|
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
if let Ok(output) = Command::new("git")
|
||||||
|
.args(["config", "--get", "remote.origin.url"])
|
||||||
|
.output()
|
||||||
|
{
|
||||||
|
if let Ok(git_origin) = String::from_utf8(output.stdout) {
|
||||||
|
println!("cargo:rustc-env=GIT_ORIGIN_URL={git_origin}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
vergen(Config::default()).ok();
|
||||||
|
}
|
||||||
@@ -1,16 +1,16 @@
|
|||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate rocket;
|
extern crate rocket;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate rocket_okapi;
|
extern crate revolt_rocket_okapi;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate serde_json;
|
extern crate serde_json;
|
||||||
#[macro_use]
|
|
||||||
extern crate lazy_static;
|
|
||||||
|
|
||||||
pub mod routes;
|
pub mod routes;
|
||||||
pub mod util;
|
pub mod util;
|
||||||
|
|
||||||
use revolt_quark::rauth::RAuth;
|
use async_std::channel::unbounded;
|
||||||
|
use revolt_quark::authifier::{Authifier, AuthifierEvent};
|
||||||
|
use revolt_quark::events::client::EventV1;
|
||||||
use revolt_quark::DatabaseInfo;
|
use revolt_quark::DatabaseInfo;
|
||||||
|
|
||||||
#[launch]
|
#[launch]
|
||||||
@@ -25,13 +25,33 @@ async fn rocket() -> _ {
|
|||||||
let db = DatabaseInfo::Auto.connect().await.unwrap();
|
let db = DatabaseInfo::Auto.connect().await.unwrap();
|
||||||
db.migrate_database().await.unwrap();
|
db.migrate_database().await.unwrap();
|
||||||
|
|
||||||
// Setup rAuth
|
// Setup Authifier event channel
|
||||||
let rauth = RAuth {
|
let (sender, receiver) = unbounded();
|
||||||
|
|
||||||
|
// Setup Authifier
|
||||||
|
let authifier = Authifier {
|
||||||
database: db.clone().into(),
|
database: db.clone().into(),
|
||||||
config: revolt_quark::util::rauth::config(),
|
config: revolt_quark::util::authifier::config(),
|
||||||
|
event_channel: Some(sender),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Launch background task workers.
|
// Launch a listener for Authifier events
|
||||||
|
async_std::task::spawn(async move {
|
||||||
|
while let Ok(event) = receiver.recv().await {
|
||||||
|
match &event {
|
||||||
|
AuthifierEvent::CreateSession { .. } | AuthifierEvent::CreateAccount { .. } => {
|
||||||
|
EventV1::Auth(event).global().await
|
||||||
|
}
|
||||||
|
AuthifierEvent::DeleteSession { user_id, .. }
|
||||||
|
| AuthifierEvent::DeleteAllSessions { user_id, .. } => {
|
||||||
|
let id = user_id.to_string();
|
||||||
|
EventV1::Auth(event).private(id).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Launch background task workers
|
||||||
async_std::task::spawn(revolt_quark::tasks::start_workers(db.clone()));
|
async_std::task::spawn(revolt_quark::tasks::start_workers(db.clone()));
|
||||||
|
|
||||||
// Configure CORS
|
// Configure CORS
|
||||||
@@ -43,7 +63,7 @@ async fn rocket() -> _ {
|
|||||||
.mount("/", revolt_quark::web::cors::catch_all_options_routes())
|
.mount("/", revolt_quark::web::cors::catch_all_options_routes())
|
||||||
.mount("/", revolt_quark::web::ratelimiter::routes())
|
.mount("/", revolt_quark::web::ratelimiter::routes())
|
||||||
.mount("/swagger/", revolt_quark::web::swagger::routes())
|
.mount("/swagger/", revolt_quark::web::swagger::routes())
|
||||||
.manage(rauth)
|
.manage(authifier)
|
||||||
.manage(db)
|
.manage(db)
|
||||||
.manage(cors.clone())
|
.manage(cors.clone())
|
||||||
.attach(revolt_quark::web::ratelimiter::RatelimitFairing)
|
.attach(revolt_quark::web::ratelimiter::RatelimitFairing)
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
use revolt_quark::{
|
||||||
|
models::{
|
||||||
|
message::{BulkMessageResponse, MessageQuery},
|
||||||
|
User,
|
||||||
|
},
|
||||||
|
Db, Error, Result,
|
||||||
|
};
|
||||||
|
use rocket::serde::json::Json;
|
||||||
|
|
||||||
|
/// # Globally Fetch Messages
|
||||||
|
///
|
||||||
|
/// This is a privileged route to globally fetch messages.
|
||||||
|
#[openapi(tag = "Admin")]
|
||||||
|
#[post("/messages", data = "<data>")]
|
||||||
|
pub async fn message_query(
|
||||||
|
db: &Db,
|
||||||
|
user: User,
|
||||||
|
data: Json<MessageQuery>,
|
||||||
|
) -> Result<Json<BulkMessageResponse>> {
|
||||||
|
// Must be privileged for this route
|
||||||
|
if !user.privileged {
|
||||||
|
return Err(Error::NotPrivileged);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch data using query
|
||||||
|
let data = data.into_inner();
|
||||||
|
let messages = db.fetch_messages(data).await?;
|
||||||
|
BulkMessageResponse::transform(db, None, messages, Some(true))
|
||||||
|
.await
|
||||||
|
.map(Json)
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
use revolt_rocket_okapi::revolt_okapi::openapi3::OpenApi;
|
||||||
|
use rocket::Route;
|
||||||
|
|
||||||
|
mod message_query;
|
||||||
|
mod stats;
|
||||||
|
|
||||||
|
pub fn routes() -> (Vec<Route>, OpenApi) {
|
||||||
|
openapi_get_routes_spec![stats::stats, message_query::message_query]
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
use revolt_quark::models::stats::Stats;
|
||||||
|
use revolt_quark::{Db, Result};
|
||||||
|
|
||||||
|
use rocket::serde::json::Json;
|
||||||
|
|
||||||
|
/// # Query Stats
|
||||||
|
///
|
||||||
|
/// Fetch various technical statistics.
|
||||||
|
#[openapi(tag = "Admin")]
|
||||||
|
#[get("/stats")]
|
||||||
|
pub async fn stats(db: &Db) -> Result<Json<Stats>> {
|
||||||
|
Ok(Json(db.generate_stats().await?))
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
|
use revolt_rocket_okapi::revolt_okapi::openapi3::OpenApi;
|
||||||
use rocket::Route;
|
use rocket::Route;
|
||||||
use rocket_okapi::okapi::openapi3::OpenApi;
|
|
||||||
|
|
||||||
mod create;
|
mod create;
|
||||||
mod delete;
|
mod delete;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
use revolt_quark::{
|
use revolt_quark::{
|
||||||
models::{Channel, User},
|
get_relationship,
|
||||||
|
models::{user::RelationshipStatus, Channel, User},
|
||||||
perms, Db, EmptyResponse, Error, Permission, Ref, Result,
|
perms, Db, EmptyResponse, Error, Permission, Ref, Result,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -22,6 +23,13 @@ pub async fn req(db: &Db, user: User, target: Ref, member: Ref) -> Result<EmptyR
|
|||||||
match &channel {
|
match &channel {
|
||||||
Channel::Group { .. } => {
|
Channel::Group { .. } => {
|
||||||
let member = member.as_user(db).await?;
|
let member = member.as_user(db).await?;
|
||||||
|
if !matches!(
|
||||||
|
get_relationship(&user, &member.id),
|
||||||
|
RelationshipStatus::Friend
|
||||||
|
) {
|
||||||
|
return Err(Error::NotFriends);
|
||||||
|
}
|
||||||
|
|
||||||
channel
|
channel
|
||||||
.add_user_to_group(db, &member.id, &user.id)
|
.add_user_to_group(db, &member.id, &user.id)
|
||||||
.await
|
.await
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
use revolt_quark::{
|
use revolt_quark::{
|
||||||
models::message::{PartialMessage, SendableEmbed},
|
models::message::{PartialMessage, SendableEmbed},
|
||||||
models::{Message, User},
|
models::{Message, User},
|
||||||
|
perms,
|
||||||
types::january::Embed,
|
types::january::Embed,
|
||||||
Db, Error, Ref, Result, Timestamp,
|
Db, Error, Permission, Ref, Result, Timestamp,
|
||||||
};
|
};
|
||||||
|
|
||||||
use rocket::serde::json::Json;
|
use rocket::serde::json::Json;
|
||||||
@@ -28,7 +29,7 @@ pub struct DataEditMessage {
|
|||||||
pub async fn req(
|
pub async fn req(
|
||||||
db: &Db,
|
db: &Db,
|
||||||
user: User,
|
user: User,
|
||||||
target: String,
|
target: Ref,
|
||||||
msg: Ref,
|
msg: Ref,
|
||||||
edit: Json<DataEditMessage>,
|
edit: Json<DataEditMessage>,
|
||||||
) -> Result<Json<Message>> {
|
) -> Result<Json<Message>> {
|
||||||
@@ -36,10 +37,17 @@ pub async fn req(
|
|||||||
edit.validate()
|
edit.validate()
|
||||||
.map_err(|error| Error::FailedValidation { error })?;
|
.map_err(|error| Error::FailedValidation { error })?;
|
||||||
|
|
||||||
|
// Ensure we have permissions to send a message
|
||||||
|
let channel = target.as_channel(db).await?;
|
||||||
|
let mut permissions = perms(&user).channel(&channel);
|
||||||
|
permissions
|
||||||
|
.throw_permission_and_view_channel(db, Permission::SendMessage)
|
||||||
|
.await?;
|
||||||
|
|
||||||
Message::validate_sum(&edit.content, &edit.embeds)?;
|
Message::validate_sum(&edit.content, &edit.embeds)?;
|
||||||
|
|
||||||
let mut message = msg.as_message(db).await?;
|
let mut message = msg.as_message(db).await?;
|
||||||
if message.channel != target {
|
if message.channel != channel.id() {
|
||||||
return Err(Error::NotFound);
|
return Err(Error::NotFound);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
use revolt_quark::{
|
use revolt_quark::{
|
||||||
models::{
|
models::{
|
||||||
message::{BulkMessageResponse, MessageSort},
|
message::{
|
||||||
|
BulkMessageResponse, MessageFilter, MessageQuery, MessageSort, MessageTimePeriod,
|
||||||
|
},
|
||||||
User,
|
User,
|
||||||
},
|
},
|
||||||
perms, Db, Error, Permission, Ref, Result,
|
perms, Db, Error, Permission, Ref, Result,
|
||||||
@@ -68,14 +70,28 @@ pub async fn req(
|
|||||||
sort,
|
sort,
|
||||||
nearby,
|
nearby,
|
||||||
include_users,
|
include_users,
|
||||||
..
|
|
||||||
} = options;
|
} = options;
|
||||||
|
|
||||||
let messages = db
|
let messages = db
|
||||||
.fetch_messages(channel.id(), limit, before, after, sort, nearby)
|
.fetch_messages(MessageQuery {
|
||||||
|
filter: MessageFilter {
|
||||||
|
channel: Some(channel.id().to_string()),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
time_period: if let Some(nearby) = nearby {
|
||||||
|
MessageTimePeriod::Relative { nearby }
|
||||||
|
} else {
|
||||||
|
MessageTimePeriod::Absolute {
|
||||||
|
before,
|
||||||
|
after,
|
||||||
|
sort,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
limit,
|
||||||
|
})
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
BulkMessageResponse::transform(db, &channel, messages, include_users)
|
BulkMessageResponse::transform(db, Some(&channel), messages, include_users)
|
||||||
.await
|
.await
|
||||||
.map(Json)
|
.map(Json)
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
use revolt_quark::{
|
use revolt_quark::{
|
||||||
models::{
|
models::{
|
||||||
message::{BulkMessageResponse, MessageSort},
|
message::{
|
||||||
|
BulkMessageResponse, MessageFilter, MessageQuery, MessageSort, MessageTimePeriod,
|
||||||
|
},
|
||||||
User,
|
User,
|
||||||
},
|
},
|
||||||
perms, Db, Error, Permission, Ref, Result,
|
perms, Db, Error, Permission, Ref, Result,
|
||||||
@@ -30,7 +32,7 @@ pub struct OptionsMessageSearch {
|
|||||||
after: Option<String>,
|
after: Option<String>,
|
||||||
/// Message sort direction
|
/// Message sort direction
|
||||||
///
|
///
|
||||||
/// By default, it will be sorted by relevance.
|
/// By default, it will be sorted by latest.
|
||||||
#[serde(default = "MessageSort::default")]
|
#[serde(default = "MessageSort::default")]
|
||||||
sort: MessageSort,
|
sort: MessageSort,
|
||||||
/// Whether to include user (and member, if server channel) objects
|
/// Whether to include user (and member, if server channel) objects
|
||||||
@@ -73,10 +75,22 @@ pub async fn req(
|
|||||||
} = options;
|
} = options;
|
||||||
|
|
||||||
let messages = db
|
let messages = db
|
||||||
.search_messages(channel.id(), &query, limit, before, after, sort)
|
.fetch_messages(MessageQuery {
|
||||||
|
filter: MessageFilter {
|
||||||
|
channel: Some(channel.id().to_string()),
|
||||||
|
query: Some(query),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
time_period: MessageTimePeriod::Absolute {
|
||||||
|
before,
|
||||||
|
after,
|
||||||
|
sort: Some(sort),
|
||||||
|
},
|
||||||
|
limit,
|
||||||
|
})
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
BulkMessageResponse::transform(db, &channel, messages, include_users)
|
BulkMessageResponse::transform(db, Some(&channel), messages, include_users)
|
||||||
.await
|
.await
|
||||||
.map(Json)
|
.map(Json)
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,7 @@ use revolt_quark::{
|
|||||||
},
|
},
|
||||||
perms,
|
perms,
|
||||||
web::idempotency::IdempotencyKey,
|
web::idempotency::IdempotencyKey,
|
||||||
Db, Error, Permission, Ref, Result,
|
Db, Error, Permission, Ref, Result, variables::delta::{MAX_ATTACHMENT_COUNT, MAX_REPLY_COUNT},
|
||||||
};
|
};
|
||||||
|
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
@@ -15,6 +15,7 @@ use rocket::serde::json::Json;
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
use validator::Validate;
|
use validator::Validate;
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
|
||||||
#[derive(Validate, Serialize, Deserialize, JsonSchema)]
|
#[derive(Validate, Serialize, Deserialize, JsonSchema)]
|
||||||
pub struct DataMessageSend {
|
pub struct DataMessageSend {
|
||||||
@@ -44,10 +45,7 @@ pub struct DataMessageSend {
|
|||||||
interactions: Option<Interactions>,
|
interactions: Option<Interactions>,
|
||||||
}
|
}
|
||||||
|
|
||||||
lazy_static! {
|
static RE_MENTION: Lazy<Regex> = Lazy::new(|| Regex::new(r"<@([0-9A-HJKMNP-TV-Z]{26})>").unwrap());
|
||||||
// ignoring I L O and U is intentional
|
|
||||||
static ref RE_MENTION: Regex = Regex::new(r"<@([0-9A-HJKMNP-TV-Z]{26})>").unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// # Send Message
|
/// # Send Message
|
||||||
///
|
///
|
||||||
@@ -65,16 +63,20 @@ pub async fn message_send(
|
|||||||
data.validate()
|
data.validate()
|
||||||
.map_err(|error| Error::FailedValidation { error })?;
|
.map_err(|error| Error::FailedValidation { error })?;
|
||||||
|
|
||||||
|
// Validate Message is within reasonable length limits
|
||||||
Message::validate_sum(&data.content, &data.embeds)?;
|
Message::validate_sum(&data.content, &data.embeds)?;
|
||||||
|
|
||||||
|
// Ensure the request is unique
|
||||||
idempotency.consume_nonce(data.nonce).await?;
|
idempotency.consume_nonce(data.nonce).await?;
|
||||||
|
|
||||||
|
// Ensure we have permissions to send a message
|
||||||
let channel = target.as_channel(db).await?;
|
let channel = target.as_channel(db).await?;
|
||||||
let mut permissions = perms(&user).channel(&channel);
|
let mut permissions = perms(&user).channel(&channel);
|
||||||
permissions
|
permissions
|
||||||
.throw_permission_and_view_channel(db, Permission::SendMessage)
|
.throw_permission_and_view_channel(db, Permission::SendMessage)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
// Check the message is not empty
|
||||||
if (data.content.as_ref().map_or(true, |v| v.is_empty()))
|
if (data.content.as_ref().map_or(true, |v| v.is_empty()))
|
||||||
&& (data.attachments.as_ref().map_or(true, |v| v.is_empty()))
|
&& (data.attachments.as_ref().map_or(true, |v| v.is_empty()))
|
||||||
&& (data.embeds.as_ref().map_or(true, |v| v.is_empty()))
|
&& (data.embeds.as_ref().map_or(true, |v| v.is_empty()))
|
||||||
@@ -82,6 +84,22 @@ pub async fn message_send(
|
|||||||
return Err(Error::EmptyMessage);
|
return Err(Error::EmptyMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ensure restrict_reactions is not specified without reactions list
|
||||||
|
if let Some(interactions) = &data.interactions {
|
||||||
|
if interactions.restrict_reactions {
|
||||||
|
let disallowed = if let Some(list) = &interactions.reactions {
|
||||||
|
list.is_empty()
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
};
|
||||||
|
|
||||||
|
if disallowed {
|
||||||
|
return Err(Error::InvalidProperty);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start constructing the message
|
||||||
let message_id = Ulid::new().to_string();
|
let message_id = Ulid::new().to_string();
|
||||||
let mut message = Message {
|
let mut message = Message {
|
||||||
id: message_id.clone(),
|
id: message_id.clone(),
|
||||||
@@ -121,8 +139,8 @@ pub async fn message_send(
|
|||||||
// 4. Verify replies are valid.
|
// 4. Verify replies are valid.
|
||||||
let mut replies = HashSet::new();
|
let mut replies = HashSet::new();
|
||||||
if let Some(entries) = data.replies {
|
if let Some(entries) = data.replies {
|
||||||
if entries.len() > 5 {
|
if entries.len() > *MAX_REPLY_COUNT {
|
||||||
return Err(Error::TooManyReplies);
|
return Err(Error::TooManyReplies { max: *MAX_REPLY_COUNT });
|
||||||
}
|
}
|
||||||
|
|
||||||
for Reply { id, mention } in entries {
|
for Reply { id, mention } in entries {
|
||||||
@@ -173,8 +191,8 @@ pub async fn message_send(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ! FIXME: move this to app config
|
// ! FIXME: move this to app config
|
||||||
if ids.len() > 5 {
|
if ids.len() > *MAX_ATTACHMENT_COUNT {
|
||||||
return Err(Error::TooManyAttachments);
|
return Err(Error::TooManyAttachments { max: *MAX_ATTACHMENT_COUNT} );
|
||||||
}
|
}
|
||||||
|
|
||||||
for attachment_id in ids {
|
for attachment_id in ids {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
|
use revolt_rocket_okapi::revolt_okapi::openapi3::OpenApi;
|
||||||
use rocket::Route;
|
use rocket::Route;
|
||||||
use rocket_okapi::okapi::openapi3::OpenApi;
|
|
||||||
|
|
||||||
mod channel_ack;
|
mod channel_ack;
|
||||||
mod channel_delete;
|
mod channel_delete;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
use revolt_quark::models::emoji::EmojiParent;
|
use revolt_quark::models::emoji::EmojiParent;
|
||||||
use revolt_quark::models::{Emoji, File, User};
|
use revolt_quark::models::{Emoji, File, User};
|
||||||
|
use revolt_quark::variables::delta::MAX_EMOJI_COUNT;
|
||||||
use revolt_quark::{perms, Db, Error, Permission, Result};
|
use revolt_quark::{perms, Db, Error, Permission, Result};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use validator::Validate;
|
use validator::Validate;
|
||||||
@@ -55,8 +56,8 @@ pub async fn create_emoji(
|
|||||||
// Check that there are no more than 100 emoji
|
// Check that there are no more than 100 emoji
|
||||||
// ! FIXME: hardcoded upper limit
|
// ! FIXME: hardcoded upper limit
|
||||||
let emojis = db.fetch_emoji_by_parent_id(&server.id).await?;
|
let emojis = db.fetch_emoji_by_parent_id(&server.id).await?;
|
||||||
if emojis.len() > 99 {
|
if emojis.len() > *MAX_EMOJI_COUNT {
|
||||||
return Err(Error::TooManyEmoji);
|
return Err(Error::TooManyEmoji { max: *MAX_EMOJI_COUNT });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
EmojiParent::Detached => return Err(Error::InvalidOperation),
|
EmojiParent::Detached => return Err(Error::InvalidOperation),
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
|
use revolt_rocket_okapi::revolt_okapi::openapi3::OpenApi;
|
||||||
use rocket::Route;
|
use rocket::Route;
|
||||||
use rocket_okapi::okapi::openapi3::OpenApi;
|
|
||||||
|
|
||||||
mod emoji_create;
|
mod emoji_create;
|
||||||
mod emoji_delete;
|
mod emoji_delete;
|
||||||
|
|||||||
@@ -23,6 +23,9 @@ pub enum InviteResponse {
|
|||||||
/// Attachment for server banner
|
/// Attachment for server banner
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
server_banner: Option<File>,
|
server_banner: Option<File>,
|
||||||
|
/// Enum of server flags
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
server_flags: Option<i32>,
|
||||||
/// Id of server channel
|
/// Id of server channel
|
||||||
channel_id: String,
|
channel_id: String,
|
||||||
/// Name of server channel
|
/// Name of server channel
|
||||||
@@ -94,6 +97,7 @@ pub async fn req(db: &Db, target: Ref) -> Result<Json<InviteResponse>> {
|
|||||||
server_name: server.name,
|
server_name: server.name,
|
||||||
server_icon: server.icon,
|
server_icon: server.icon,
|
||||||
server_banner: server.banner,
|
server_banner: server.banner,
|
||||||
|
server_flags: server.flags,
|
||||||
channel_id: id,
|
channel_id: id,
|
||||||
channel_name: name,
|
channel_name: name,
|
||||||
channel_description: description,
|
channel_description: description,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
|
use revolt_rocket_okapi::revolt_okapi::openapi3::OpenApi;
|
||||||
use rocket::Route;
|
use rocket::Route;
|
||||||
use rocket_okapi::okapi::openapi3::OpenApi;
|
|
||||||
|
|
||||||
mod invite_delete;
|
mod invite_delete;
|
||||||
mod invite_fetch;
|
mod invite_fetch;
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
|
use revolt_rocket_okapi::{revolt_okapi::openapi3::OpenApi, settings::OpenApiSettings};
|
||||||
pub use rocket::http::Status;
|
pub use rocket::http::Status;
|
||||||
pub use rocket::response::Redirect;
|
pub use rocket::response::Redirect;
|
||||||
use rocket::{Build, Rocket};
|
use rocket::{Build, Rocket};
|
||||||
use rocket_okapi::{okapi::openapi3::OpenApi, settings::OpenApiSettings};
|
|
||||||
|
|
||||||
|
mod admin;
|
||||||
mod bots;
|
mod bots;
|
||||||
mod channels;
|
mod channels;
|
||||||
mod customisation;
|
mod customisation;
|
||||||
@@ -10,6 +11,7 @@ mod invites;
|
|||||||
mod onboard;
|
mod onboard;
|
||||||
mod push;
|
mod push;
|
||||||
mod root;
|
mod root;
|
||||||
|
mod safety;
|
||||||
mod servers;
|
mod servers;
|
||||||
mod sync;
|
mod sync;
|
||||||
mod users;
|
mod users;
|
||||||
@@ -21,15 +23,17 @@ pub fn mount(mut rocket: Rocket<Build>) -> Rocket<Build> {
|
|||||||
rocket, "/".to_owned(), settings,
|
rocket, "/".to_owned(), settings,
|
||||||
"/" => (vec![], custom_openapi_spec()),
|
"/" => (vec![], custom_openapi_spec()),
|
||||||
"" => openapi_get_routes_spec![root::root, root::ping],
|
"" => openapi_get_routes_spec![root::root, root::ping],
|
||||||
|
"/admin" => admin::routes(),
|
||||||
"/users" => users::routes(),
|
"/users" => users::routes(),
|
||||||
"/bots" => bots::routes(),
|
"/bots" => bots::routes(),
|
||||||
"/channels" => channels::routes(),
|
"/channels" => channels::routes(),
|
||||||
"/servers" => servers::routes(),
|
"/servers" => servers::routes(),
|
||||||
"/invites" => invites::routes(),
|
"/invites" => invites::routes(),
|
||||||
"/custom" => customisation::routes(),
|
"/custom" => customisation::routes(),
|
||||||
"/auth/account" => rocket_rauth::routes::account::routes(),
|
"/safety" => safety::routes(),
|
||||||
"/auth/session" => rocket_rauth::routes::session::routes(),
|
"/auth/account" => rocket_authifier::routes::account::routes(),
|
||||||
"/auth/mfa" => rocket_rauth::routes::mfa::routes(),
|
"/auth/session" => rocket_authifier::routes::session::routes(),
|
||||||
|
"/auth/mfa" => rocket_authifier::routes::mfa::routes(),
|
||||||
"/onboard" => onboard::routes(),
|
"/onboard" => onboard::routes(),
|
||||||
"/push" => push::routes(),
|
"/push" => push::routes(),
|
||||||
"/sync" => sync::routes(),
|
"/sync" => sync::routes(),
|
||||||
@@ -39,7 +43,7 @@ pub fn mount(mut rocket: Rocket<Build>) -> Rocket<Build> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn custom_openapi_spec() -> OpenApi {
|
fn custom_openapi_spec() -> OpenApi {
|
||||||
use rocket_okapi::okapi::openapi3::*;
|
use revolt_rocket_okapi::revolt_okapi::openapi3::*;
|
||||||
|
|
||||||
let mut extensions = schemars::Map::new();
|
let mut extensions = schemars::Map::new();
|
||||||
extensions.insert(
|
extensions.insert(
|
||||||
@@ -105,6 +109,13 @@ fn custom_openapi_spec() -> OpenApi {
|
|||||||
"Emojis"
|
"Emojis"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "Platform Administration",
|
||||||
|
"tags": [
|
||||||
|
"Admin",
|
||||||
|
"User Safety"
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "Authentication",
|
"name": "Authentication",
|
||||||
"tags": [
|
"tags": [
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
use crate::util::regex::RE_USERNAME;
|
use crate::util::regex::RE_USERNAME;
|
||||||
use revolt_quark::{models::User, rauth::models::Session, Database, EmptyResponse, Error, Result};
|
use revolt_quark::{
|
||||||
|
authifier::models::Session, models::User, Database, EmptyResponse, Error, Result,
|
||||||
|
};
|
||||||
|
|
||||||
use rocket::{serde::json::Json, State};
|
use rocket::{serde::json::Json, State};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use revolt_quark::{models::User, rauth::models::Session};
|
use revolt_quark::{authifier::models::Session, models::User};
|
||||||
use rocket::serde::json::Json;
|
use rocket::serde::json::Json;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
|
use revolt_rocket_okapi::revolt_okapi::openapi3::OpenApi;
|
||||||
use rocket::Route;
|
use rocket::Route;
|
||||||
use rocket_okapi::okapi::openapi3::OpenApi;
|
|
||||||
|
|
||||||
mod complete;
|
mod complete;
|
||||||
mod hello;
|
mod hello;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
|
use revolt_rocket_okapi::revolt_okapi::openapi3::OpenApi;
|
||||||
use rocket::Route;
|
use rocket::Route;
|
||||||
use rocket_okapi::okapi::openapi3::OpenApi;
|
|
||||||
|
|
||||||
mod subscribe;
|
mod subscribe;
|
||||||
mod unsubscribe;
|
mod unsubscribe;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use revolt_quark::{
|
use revolt_quark::{
|
||||||
rauth::{
|
authifier::{
|
||||||
models::{Session, WebPushSubscription},
|
models::{Session, WebPushSubscription},
|
||||||
RAuth,
|
Authifier,
|
||||||
},
|
},
|
||||||
EmptyResponse, Error, Result,
|
EmptyResponse, Error, Result,
|
||||||
};
|
};
|
||||||
@@ -16,13 +16,13 @@ use rocket::{serde::json::Json, State};
|
|||||||
#[openapi(tag = "Web Push")]
|
#[openapi(tag = "Web Push")]
|
||||||
#[post("/subscribe", data = "<data>")]
|
#[post("/subscribe", data = "<data>")]
|
||||||
pub async fn req(
|
pub async fn req(
|
||||||
rauth: &State<RAuth>,
|
authifier: &State<Authifier>,
|
||||||
mut session: Session,
|
mut session: Session,
|
||||||
data: Json<WebPushSubscription>,
|
data: Json<WebPushSubscription>,
|
||||||
) -> Result<EmptyResponse> {
|
) -> Result<EmptyResponse> {
|
||||||
session.subscription = Some(data.into_inner());
|
session.subscription = Some(data.into_inner());
|
||||||
session
|
session
|
||||||
.save(rauth)
|
.save(authifier)
|
||||||
.await
|
.await
|
||||||
.map(|_| EmptyResponse)
|
.map(|_| EmptyResponse)
|
||||||
.map_err(|_| Error::DatabaseError {
|
.map_err(|_| Error::DatabaseError {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use revolt_quark::{
|
use revolt_quark::{
|
||||||
rauth::{models::Session, RAuth},
|
authifier::{models::Session, Authifier},
|
||||||
EmptyResponse, Error, Result,
|
EmptyResponse, Error, Result,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -10,10 +10,10 @@ use rocket::State;
|
|||||||
/// Remove the Web Push subscription associated with the current session.
|
/// Remove the Web Push subscription associated with the current session.
|
||||||
#[openapi(tag = "Web Push")]
|
#[openapi(tag = "Web Push")]
|
||||||
#[post("/unsubscribe")]
|
#[post("/unsubscribe")]
|
||||||
pub async fn req(rauth: &State<RAuth>, mut session: Session) -> Result<EmptyResponse> {
|
pub async fn req(authifier: &State<Authifier>, mut session: Session) -> Result<EmptyResponse> {
|
||||||
session.subscription = None;
|
session.subscription = None;
|
||||||
session
|
session
|
||||||
.save(rauth)
|
.save(authifier)
|
||||||
.await
|
.await
|
||||||
.map(|_| EmptyResponse)
|
.map(|_| EmptyResponse)
|
||||||
.map_err(|_| Error::DatabaseError {
|
.map_err(|_| Error::DatabaseError {
|
||||||
|
|||||||
@@ -54,6 +54,21 @@ pub struct RevoltFeatures {
|
|||||||
pub voso: VoiceFeature,
|
pub voso: VoiceFeature,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// # Build Information
|
||||||
|
#[derive(Serialize, JsonSchema, Debug)]
|
||||||
|
pub struct BuildInformation {
|
||||||
|
/// Commit Hash
|
||||||
|
pub commit_sha: String,
|
||||||
|
/// Commit Timestamp
|
||||||
|
pub commit_timestamp: String,
|
||||||
|
/// Git Semver
|
||||||
|
pub semver: String,
|
||||||
|
/// Git Origin URL
|
||||||
|
pub origin_url: String,
|
||||||
|
/// Build Timestamp
|
||||||
|
pub timestamp: String,
|
||||||
|
}
|
||||||
|
|
||||||
/// # Server Configuration
|
/// # Server Configuration
|
||||||
#[derive(Serialize, JsonSchema, Debug)]
|
#[derive(Serialize, JsonSchema, Debug)]
|
||||||
pub struct RevoltConfig {
|
pub struct RevoltConfig {
|
||||||
@@ -67,6 +82,8 @@ pub struct RevoltConfig {
|
|||||||
pub app: String,
|
pub app: String,
|
||||||
/// Web Push VAPID public key
|
/// Web Push VAPID public key
|
||||||
pub vapid: String,
|
pub vapid: String,
|
||||||
|
/// Build information
|
||||||
|
pub build: BuildInformation,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// # Query Node
|
/// # Query Node
|
||||||
@@ -101,6 +118,23 @@ pub async fn root() -> Result<Json<RevoltConfig>> {
|
|||||||
ws: EXTERNAL_WS_URL.to_string(),
|
ws: EXTERNAL_WS_URL.to_string(),
|
||||||
app: APP_URL.to_string(),
|
app: APP_URL.to_string(),
|
||||||
vapid: VAPID_PUBLIC_KEY.to_string(),
|
vapid: VAPID_PUBLIC_KEY.to_string(),
|
||||||
|
build: BuildInformation {
|
||||||
|
commit_sha: option_env!("VERGEN_GIT_SHA")
|
||||||
|
.unwrap_or_else(|| "<failed to generate>")
|
||||||
|
.to_string(),
|
||||||
|
commit_timestamp: option_env!("VERGEN_GIT_COMMIT_TIMESTAMP")
|
||||||
|
.unwrap_or_else(|| "<failed to generate>")
|
||||||
|
.to_string(),
|
||||||
|
semver: option_env!("VERGEN_GIT_SEMVER")
|
||||||
|
.unwrap_or_else(|| "<failed to generate>")
|
||||||
|
.to_string(),
|
||||||
|
origin_url: option_env!("GIT_ORIGIN_URL")
|
||||||
|
.unwrap_or_else(|| "<failed to generate>")
|
||||||
|
.to_string(),
|
||||||
|
timestamp: option_env!("VERGEN_BUILD_TIMESTAMP")
|
||||||
|
.unwrap_or_else(|| "<failed to generate>")
|
||||||
|
.to_string(),
|
||||||
|
},
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
use revolt_quark::{
|
||||||
|
models::{
|
||||||
|
report::{PartialReport, ReportStatus},
|
||||||
|
Report, User,
|
||||||
|
},
|
||||||
|
Db, Error, Ref, Result,
|
||||||
|
};
|
||||||
|
use rocket::serde::json::Json;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use validator::Validate;
|
||||||
|
|
||||||
|
/// # Report Data
|
||||||
|
#[derive(Validate, Deserialize, JsonSchema)]
|
||||||
|
pub struct DataEditReport {
|
||||||
|
/// New report status
|
||||||
|
status: Option<ReportStatus>,
|
||||||
|
/// Report notes
|
||||||
|
notes: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Edit Report
|
||||||
|
///
|
||||||
|
/// Edit a report.
|
||||||
|
#[openapi(tag = "User Safety")]
|
||||||
|
#[patch("/reports/<report>", data = "<edit>")]
|
||||||
|
pub async fn edit_report(
|
||||||
|
db: &Db,
|
||||||
|
user: User,
|
||||||
|
report: Ref,
|
||||||
|
edit: Json<DataEditReport>,
|
||||||
|
) -> Result<Json<Report>> {
|
||||||
|
// Must be privileged for this route
|
||||||
|
if !user.privileged {
|
||||||
|
return Err(Error::NotPrivileged);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate data
|
||||||
|
let edit = edit.into_inner();
|
||||||
|
edit.validate()
|
||||||
|
.map_err(|error| Error::FailedValidation { error })?;
|
||||||
|
|
||||||
|
// Create and apply update to report
|
||||||
|
let mut report = report.as_report(db).await?;
|
||||||
|
report
|
||||||
|
.update(
|
||||||
|
db,
|
||||||
|
PartialReport {
|
||||||
|
status: edit.status,
|
||||||
|
notes: edit.notes,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(Json(report))
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
use revolt_quark::models::{Report, User};
|
||||||
|
use revolt_quark::{Db, Error, Result};
|
||||||
|
use rocket::serde::json::Json;
|
||||||
|
|
||||||
|
/// # Fetch Report
|
||||||
|
///
|
||||||
|
/// Fetch a report by its ID
|
||||||
|
#[openapi(tag = "User Safety")]
|
||||||
|
#[get("/report/<id>")]
|
||||||
|
pub async fn fetch_report(db: &Db, user: User, id: String) -> Result<Json<Report>> {
|
||||||
|
// Must be privileged for this route
|
||||||
|
if !user.privileged {
|
||||||
|
return Err(Error::NotPrivileged);
|
||||||
|
}
|
||||||
|
|
||||||
|
db.fetch_report(&id).await.map(Json)
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
use revolt_quark::models::{Report, User};
|
||||||
|
use revolt_quark::{Db, Error, Result};
|
||||||
|
use rocket::serde::json::Json;
|
||||||
|
|
||||||
|
/// # Fetch Reports
|
||||||
|
///
|
||||||
|
/// Fetch all available reports
|
||||||
|
#[openapi(tag = "User Safety")]
|
||||||
|
#[get("/reports")]
|
||||||
|
pub async fn fetch_reports(db: &Db, user: User) -> Result<Json<Vec<Report>>> {
|
||||||
|
// Must be privileged for this route
|
||||||
|
if !user.privileged {
|
||||||
|
return Err(Error::NotPrivileged);
|
||||||
|
}
|
||||||
|
|
||||||
|
db.fetch_reports().await.map(Json)
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
use revolt_quark::models::snapshot::{SnapshotContent, SnapshotWithContext};
|
||||||
|
use revolt_quark::models::{Channel, User};
|
||||||
|
use revolt_quark::{Db, Error, Result};
|
||||||
|
use rocket::serde::json::Json;
|
||||||
|
|
||||||
|
/// # Fetch Snapshot
|
||||||
|
///
|
||||||
|
/// Fetch a snapshot for a given report
|
||||||
|
#[openapi(tag = "User Safety")]
|
||||||
|
#[get("/snapshot/<report_id>")]
|
||||||
|
pub async fn fetch_snapshot(
|
||||||
|
db: &Db,
|
||||||
|
user: User,
|
||||||
|
report_id: String,
|
||||||
|
) -> Result<Json<SnapshotWithContext>> {
|
||||||
|
// Must be privileged for this route
|
||||||
|
if !user.privileged {
|
||||||
|
return Err(Error::NotPrivileged);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch snapshot
|
||||||
|
let snapshot = db.fetch_snapshot(&report_id).await?;
|
||||||
|
|
||||||
|
// Resolve and fetch IDs of associated content
|
||||||
|
let mut user_ids: HashSet<&str> = HashSet::new();
|
||||||
|
let mut channel_ids: HashSet<&str> = HashSet::new();
|
||||||
|
|
||||||
|
match &snapshot.content {
|
||||||
|
SnapshotContent::Message {
|
||||||
|
prior_context,
|
||||||
|
leading_context,
|
||||||
|
message,
|
||||||
|
} => {
|
||||||
|
for msg in prior_context {
|
||||||
|
user_ids.insert(&msg.author);
|
||||||
|
}
|
||||||
|
|
||||||
|
for msg in leading_context {
|
||||||
|
user_ids.insert(&msg.author);
|
||||||
|
}
|
||||||
|
|
||||||
|
user_ids.insert(&message.author);
|
||||||
|
channel_ids.insert(&message.channel);
|
||||||
|
}
|
||||||
|
SnapshotContent::User(user) => {
|
||||||
|
user_ids.insert(&user.id);
|
||||||
|
}
|
||||||
|
SnapshotContent::Server(server) => {
|
||||||
|
for channel in &server.channels {
|
||||||
|
channel_ids.insert(channel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect user and channel IDs
|
||||||
|
let user_ids: Vec<String> = user_ids.into_iter().map(|s| s.to_owned()).collect();
|
||||||
|
let channel_ids: Vec<String> = channel_ids.into_iter().map(|s| s.to_owned()).collect();
|
||||||
|
|
||||||
|
// Fetch users and channels
|
||||||
|
let users = db.fetch_users(&user_ids).await?;
|
||||||
|
let channels = db.fetch_channels(&channel_ids).await?;
|
||||||
|
|
||||||
|
// Pull out first server from channels if possible
|
||||||
|
let server = if let Some(server_id) = channels.iter().find_map(|channel| match channel {
|
||||||
|
Channel::TextChannel { server, .. } => Some(server),
|
||||||
|
_ => None,
|
||||||
|
}) {
|
||||||
|
Some(db.fetch_server(server_id).await?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
// Return snapshot with context
|
||||||
|
Ok(Json(SnapshotWithContext {
|
||||||
|
snapshot,
|
||||||
|
users,
|
||||||
|
channels,
|
||||||
|
server,
|
||||||
|
}))
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
use revolt_rocket_okapi::revolt_okapi::openapi3::OpenApi;
|
||||||
|
use rocket::Route;
|
||||||
|
|
||||||
|
mod edit_report;
|
||||||
|
mod fetch_report;
|
||||||
|
mod fetch_reports;
|
||||||
|
mod report_content;
|
||||||
|
|
||||||
|
mod fetch_snapshot;
|
||||||
|
|
||||||
|
pub fn routes() -> (Vec<Route>, OpenApi) {
|
||||||
|
openapi_get_routes_spec![
|
||||||
|
// Reports
|
||||||
|
edit_report::edit_report,
|
||||||
|
fetch_report::fetch_report,
|
||||||
|
fetch_reports::fetch_reports,
|
||||||
|
report_content::report_content,
|
||||||
|
// Snapshots
|
||||||
|
fetch_snapshot::fetch_snapshot
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
use revolt_quark::events::client::EventV1;
|
||||||
|
use revolt_quark::models::message::{MessageFilter, MessageQuery, MessageSort, MessageTimePeriod};
|
||||||
|
use revolt_quark::models::report::{ReportStatus, ReportedContent};
|
||||||
|
use revolt_quark::models::snapshot::{Snapshot, SnapshotContent};
|
||||||
|
use revolt_quark::models::{Report, User};
|
||||||
|
use revolt_quark::{Db, Error, Result};
|
||||||
|
use serde::Deserialize;
|
||||||
|
use ulid::Ulid;
|
||||||
|
use validator::Validate;
|
||||||
|
|
||||||
|
use rocket::serde::json::Json;
|
||||||
|
|
||||||
|
/// # Report Data
|
||||||
|
#[derive(Validate, Deserialize, JsonSchema)]
|
||||||
|
pub struct DataReportContent {
|
||||||
|
/// Content being reported
|
||||||
|
content: ReportedContent,
|
||||||
|
/// Additional report description
|
||||||
|
#[validate(length(min = 0, max = 1000))]
|
||||||
|
#[serde(default)]
|
||||||
|
additional_context: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Report Content
|
||||||
|
///
|
||||||
|
/// Report a piece of content to the moderation team.
|
||||||
|
#[openapi(tag = "User Safety")]
|
||||||
|
#[post("/report", data = "<data>")]
|
||||||
|
pub async fn report_content(db: &Db, user: User, data: Json<DataReportContent>) -> Result<()> {
|
||||||
|
let data = data.into_inner();
|
||||||
|
data.validate()
|
||||||
|
.map_err(|error| Error::FailedValidation { error })?;
|
||||||
|
|
||||||
|
// Bots cannot create reports
|
||||||
|
if user.bot.is_some() {
|
||||||
|
return Err(Error::IsBot);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find the content and create a snapshot of it
|
||||||
|
// Also retrieve any references to Files
|
||||||
|
let (content, files): (SnapshotContent, Vec<String>) = match &data.content {
|
||||||
|
ReportedContent::Message { id, .. } => {
|
||||||
|
let message = db.fetch_message(id).await?;
|
||||||
|
|
||||||
|
// Users cannot report themselves
|
||||||
|
if message.author == user.id {
|
||||||
|
return Err(Error::CannotReportYourself);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect message attachments
|
||||||
|
let files = message
|
||||||
|
.attachments
|
||||||
|
.as_ref()
|
||||||
|
.map(|attachments| attachments.iter().map(|x| x.id.to_string()).collect())
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
// Collect prior context
|
||||||
|
let prior_context = db
|
||||||
|
.fetch_messages(MessageQuery {
|
||||||
|
filter: MessageFilter {
|
||||||
|
channel: Some(message.channel.to_string()),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
limit: Some(15),
|
||||||
|
time_period: MessageTimePeriod::Absolute {
|
||||||
|
before: Some(message.id.to_string()),
|
||||||
|
after: None,
|
||||||
|
sort: Some(MessageSort::Latest),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Collect leading context
|
||||||
|
let leading_context = db
|
||||||
|
.fetch_messages(MessageQuery {
|
||||||
|
filter: MessageFilter {
|
||||||
|
channel: Some(message.channel.to_string()),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
limit: Some(15),
|
||||||
|
time_period: MessageTimePeriod::Absolute {
|
||||||
|
before: None,
|
||||||
|
after: Some(message.id.to_string()),
|
||||||
|
sort: Some(MessageSort::Oldest),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
(
|
||||||
|
SnapshotContent::Message {
|
||||||
|
message,
|
||||||
|
prior_context,
|
||||||
|
leading_context,
|
||||||
|
},
|
||||||
|
files,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
ReportedContent::Server { id, .. } => {
|
||||||
|
let server = db.fetch_server(id).await?;
|
||||||
|
|
||||||
|
// Users cannot report their own server
|
||||||
|
if server.owner == user.id {
|
||||||
|
return Err(Error::CannotReportYourself);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect server's icon and banner
|
||||||
|
let files = [&server.icon, &server.banner]
|
||||||
|
.iter()
|
||||||
|
.filter_map(|x| x.as_ref().map(|x| x.id.to_string()))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
(SnapshotContent::Server(server), files)
|
||||||
|
}
|
||||||
|
ReportedContent::User { id, .. } => {
|
||||||
|
let reported_user = db.fetch_user(id).await?;
|
||||||
|
|
||||||
|
// Users cannot report themselves
|
||||||
|
if reported_user.id == user.id {
|
||||||
|
return Err(Error::CannotReportYourself);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect user's avatar and profile background
|
||||||
|
let files = [
|
||||||
|
reported_user.avatar.as_ref(),
|
||||||
|
reported_user
|
||||||
|
.profile
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|profile| profile.background.as_ref()),
|
||||||
|
]
|
||||||
|
.iter()
|
||||||
|
.filter_map(|x| x.as_ref().map(|x| x.id.to_string()))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
(SnapshotContent::User(reported_user), files)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Mark all the attachments as reported
|
||||||
|
for file in files {
|
||||||
|
db.mark_attachment_as_reported(&file).await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate an id for the report
|
||||||
|
let id = Ulid::new().to_string();
|
||||||
|
|
||||||
|
// Save a snapshot of the content
|
||||||
|
let snapshot = Snapshot {
|
||||||
|
id: Ulid::new().to_string(),
|
||||||
|
report_id: id.to_string(),
|
||||||
|
content,
|
||||||
|
};
|
||||||
|
|
||||||
|
db.insert_snapshot(&snapshot).await?;
|
||||||
|
|
||||||
|
// Save the report
|
||||||
|
let report = Report {
|
||||||
|
id,
|
||||||
|
author_id: user.id,
|
||||||
|
content: data.content,
|
||||||
|
additional_context: data.additional_context,
|
||||||
|
status: ReportStatus::Created {},
|
||||||
|
notes: String::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
db.insert_report(&report).await?;
|
||||||
|
|
||||||
|
EventV1::ReportCreate(report).global().await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@ use std::collections::HashMap;
|
|||||||
|
|
||||||
use revolt_quark::{
|
use revolt_quark::{
|
||||||
models::{server::PartialServer, Channel, User},
|
models::{server::PartialServer, Channel, User},
|
||||||
perms, Db, Error, Permission, Ref, Result,
|
perms, Db, Error, Permission, Ref, Result, variables::delta::MAX_CHANNEL_COUNT,
|
||||||
};
|
};
|
||||||
|
|
||||||
use rocket::serde::json::Json;
|
use rocket::serde::json::Json;
|
||||||
@@ -11,20 +11,15 @@ use ulid::Ulid;
|
|||||||
use validator::Validate;
|
use validator::Validate;
|
||||||
|
|
||||||
/// # Channel Type
|
/// # Channel Type
|
||||||
#[derive(Serialize, Deserialize, JsonSchema)]
|
#[derive(Serialize, Deserialize, JsonSchema, Default)]
|
||||||
enum ChannelType {
|
enum ChannelType {
|
||||||
/// Text Channel
|
/// Text Channel
|
||||||
|
#[default]
|
||||||
Text,
|
Text,
|
||||||
/// Voice Channel
|
/// Voice Channel
|
||||||
Voice,
|
Voice,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ChannelType {
|
|
||||||
fn default() -> Self {
|
|
||||||
ChannelType::Text
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// # Channel Data
|
/// # Channel Data
|
||||||
#[derive(Validate, Serialize, Deserialize, JsonSchema)]
|
#[derive(Validate, Serialize, Deserialize, JsonSchema)]
|
||||||
pub struct DataCreateChannel {
|
pub struct DataCreateChannel {
|
||||||
@@ -63,6 +58,10 @@ pub async fn req(
|
|||||||
.throw_permission(db, Permission::ManageChannel)
|
.throw_permission(db, Permission::ManageChannel)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
if server.channels.len() > *MAX_CHANNEL_COUNT {
|
||||||
|
return Err(Error::TooManyChannels { max: *MAX_CHANNEL_COUNT })
|
||||||
|
};
|
||||||
|
|
||||||
let id = Ulid::new().to_string();
|
let id = Ulid::new().to_string();
|
||||||
let mut channels = server.channels.clone();
|
let mut channels = server.channels.clone();
|
||||||
channels.push(id.clone());
|
channels.push(id.clone());
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use revolt_quark::{
|
use revolt_quark::{
|
||||||
models::{Invite, User},
|
models::{Invite, User},
|
||||||
perms, Db, Error, Permission, Ref, Result,
|
perms, Db, Permission, Ref, Result,
|
||||||
};
|
};
|
||||||
|
|
||||||
use rocket::serde::json::Json;
|
use rocket::serde::json::Json;
|
||||||
@@ -11,10 +11,6 @@ use rocket::serde::json::Json;
|
|||||||
#[openapi(tag = "Server Members")]
|
#[openapi(tag = "Server Members")]
|
||||||
#[get("/<target>/invites")]
|
#[get("/<target>/invites")]
|
||||||
pub async fn req(db: &Db, user: User, target: Ref) -> Result<Json<Vec<Invite>>> {
|
pub async fn req(db: &Db, user: User, target: Ref) -> Result<Json<Vec<Invite>>> {
|
||||||
if user.bot.is_some() {
|
|
||||||
return Err(Error::IsBot);
|
|
||||||
}
|
|
||||||
|
|
||||||
let server = target.as_server(db).await?;
|
let server = target.as_server(db).await?;
|
||||||
perms(&user)
|
perms(&user)
|
||||||
.server(&server)
|
.server(&server)
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
|
use revolt_rocket_okapi::revolt_okapi::openapi3::OpenApi;
|
||||||
use rocket::Route;
|
use rocket::Route;
|
||||||
use rocket_okapi::okapi::openapi3::OpenApi;
|
|
||||||
|
|
||||||
mod ban_create;
|
mod ban_create;
|
||||||
mod ban_list;
|
mod ban_list;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use revolt_quark::{
|
use revolt_quark::{
|
||||||
models::{server::Role, User},
|
models::{server::Role, User},
|
||||||
perms, Db, Error, Permission, Ref, Result,
|
perms, Db, Error, Permission, Ref, Result, variables::delta::MAX_ROLE_COUNT,
|
||||||
};
|
};
|
||||||
|
|
||||||
use rocket::serde::json::Json;
|
use rocket::serde::json::Json;
|
||||||
@@ -50,6 +50,10 @@ pub async fn req(
|
|||||||
.throw_permission(db, Permission::ManageRole)
|
.throw_permission(db, Permission::ManageRole)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
if server.roles.len() > *MAX_ROLE_COUNT {
|
||||||
|
return Err(Error::TooManyRoles { max: *MAX_ROLE_COUNT })
|
||||||
|
};
|
||||||
|
|
||||||
let member_rank = permissions.get_member_rank();
|
let member_rank = permissions.get_member_rank();
|
||||||
let rank = if let Some(given_rank) = data.rank {
|
let rank = if let Some(given_rank) = data.rank {
|
||||||
if given_rank <= member_rank.unwrap_or(i64::MIN) {
|
if given_rank <= member_rank.unwrap_or(i64::MIN) {
|
||||||
|
|||||||
@@ -44,6 +44,10 @@ pub async fn req(
|
|||||||
user: User,
|
user: User,
|
||||||
info: Json<DataCreateServer>,
|
info: Json<DataCreateServer>,
|
||||||
) -> Result<Json<CreateServerResponse>> {
|
) -> Result<Json<CreateServerResponse>> {
|
||||||
|
if user.bot.is_some() {
|
||||||
|
return Err(Error::IsBot);
|
||||||
|
}
|
||||||
|
|
||||||
let info = info.into_inner();
|
let info = info.into_inner();
|
||||||
info.validate()
|
info.validate()
|
||||||
.map_err(|error| Error::FailedValidation { error })?;
|
.map_err(|error| Error::FailedValidation { error })?;
|
||||||
|
|||||||
@@ -33,6 +33,10 @@ pub struct DataEditServer {
|
|||||||
/// System message configuration
|
/// System message configuration
|
||||||
system_messages: Option<SystemMessageChannels>,
|
system_messages: Option<SystemMessageChannels>,
|
||||||
|
|
||||||
|
/// Bitfield of server flags
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub flags: Option<i32>,
|
||||||
|
|
||||||
// Whether this server is age-restricted
|
// Whether this server is age-restricted
|
||||||
// nsfw: Option<bool>,
|
// nsfw: Option<bool>,
|
||||||
/// Whether this server is public and should show up on [Revolt Discover](https://rvlt.gg)
|
/// Whether this server is public and should show up on [Revolt Discover](https://rvlt.gg)
|
||||||
@@ -92,6 +96,11 @@ pub async fn req(
|
|||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check we are privileged if changing sensitive fields
|
||||||
|
if data.flags.is_some() && !user.privileged {
|
||||||
|
return Err(Error::NotPrivileged);
|
||||||
|
}
|
||||||
|
|
||||||
if data.categories.is_some() {
|
if data.categories.is_some() {
|
||||||
permissions
|
permissions
|
||||||
.throw_permission(db, Permission::ManageChannel)
|
.throw_permission(db, Permission::ManageChannel)
|
||||||
@@ -105,6 +114,7 @@ pub async fn req(
|
|||||||
banner,
|
banner,
|
||||||
categories,
|
categories,
|
||||||
system_messages,
|
system_messages,
|
||||||
|
flags,
|
||||||
// nsfw,
|
// nsfw,
|
||||||
discoverable,
|
discoverable,
|
||||||
analytics,
|
analytics,
|
||||||
@@ -116,6 +126,7 @@ pub async fn req(
|
|||||||
description,
|
description,
|
||||||
categories,
|
categories,
|
||||||
system_messages,
|
system_messages,
|
||||||
|
flags,
|
||||||
// nsfw,
|
// nsfw,
|
||||||
discoverable,
|
discoverable,
|
||||||
analytics,
|
analytics,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
|
use revolt_rocket_okapi::revolt_okapi::openapi3::OpenApi;
|
||||||
use rocket::Route;
|
use rocket::Route;
|
||||||
use rocket_okapi::okapi::openapi3::OpenApi;
|
|
||||||
|
|
||||||
mod get_settings;
|
mod get_settings;
|
||||||
mod get_unreads;
|
mod get_unreads;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use crate::util::regex::RE_USERNAME;
|
use crate::util::regex::RE_USERNAME;
|
||||||
use revolt_quark::{models::User, rauth::models::Account, Database, Error, Result};
|
use revolt_quark::{authifier::models::Account, models::User, Database, Error, Result};
|
||||||
use rocket::{serde::json::Json, State};
|
use rocket::{serde::json::Json, State};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use validator::Validate;
|
use validator::Validate;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use revolt_quark::models::user::{FieldsUser, PartialUser, User};
|
use revolt_quark::models::user::{FieldsUser, PartialUser, User};
|
||||||
use revolt_quark::models::File;
|
use revolt_quark::models::File;
|
||||||
use revolt_quark::{Database, Error, Result};
|
use revolt_quark::{Database, Error, Ref, Result};
|
||||||
|
|
||||||
use revolt_quark::models::user::UserStatus;
|
use revolt_quark::models::user::UserStatus;
|
||||||
use rocket::serde::json::Json;
|
use rocket::serde::json::Json;
|
||||||
@@ -24,6 +24,10 @@ pub struct UserProfileData {
|
|||||||
/// # User Data
|
/// # User Data
|
||||||
#[derive(Validate, Serialize, Deserialize, JsonSchema)]
|
#[derive(Validate, Serialize, Deserialize, JsonSchema)]
|
||||||
pub struct DataEditUser {
|
pub struct DataEditUser {
|
||||||
|
/// Attachment Id for avatar
|
||||||
|
#[validate(length(min = 1, max = 128))]
|
||||||
|
avatar: Option<String>,
|
||||||
|
|
||||||
/// New user status
|
/// New user status
|
||||||
#[validate]
|
#[validate]
|
||||||
status: Option<UserStatus>,
|
status: Option<UserStatus>,
|
||||||
@@ -32,9 +36,14 @@ pub struct DataEditUser {
|
|||||||
/// This is applied as a partial.
|
/// This is applied as a partial.
|
||||||
#[validate]
|
#[validate]
|
||||||
profile: Option<UserProfileData>,
|
profile: Option<UserProfileData>,
|
||||||
/// Attachment Id for avatar
|
|
||||||
#[validate(length(min = 1, max = 128))]
|
/// Bitfield of user badges
|
||||||
avatar: Option<String>,
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
badges: Option<i32>,
|
||||||
|
/// Enum of user flags
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
flags: Option<i32>,
|
||||||
|
|
||||||
/// Fields to remove from user object
|
/// Fields to remove from user object
|
||||||
#[validate(length(min = 1))]
|
#[validate(length(min = 1))]
|
||||||
remove: Option<Vec<FieldsUser>>,
|
remove: Option<Vec<FieldsUser>>,
|
||||||
@@ -44,19 +53,36 @@ pub struct DataEditUser {
|
|||||||
///
|
///
|
||||||
/// Edit currently authenticated user.
|
/// Edit currently authenticated user.
|
||||||
#[openapi(tag = "User Information")]
|
#[openapi(tag = "User Information")]
|
||||||
#[patch("/@me", data = "<data>")]
|
#[patch("/<target>", data = "<data>")]
|
||||||
pub async fn req(
|
pub async fn req(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
mut user: User,
|
mut user: User,
|
||||||
|
target: Ref,
|
||||||
data: Json<DataEditUser>,
|
data: Json<DataEditUser>,
|
||||||
) -> Result<Json<User>> {
|
) -> Result<Json<User>> {
|
||||||
let data = data.into_inner();
|
let data = data.into_inner();
|
||||||
data.validate()
|
data.validate()
|
||||||
.map_err(|error| Error::FailedValidation { error })?;
|
.map_err(|error| Error::FailedValidation { error })?;
|
||||||
|
|
||||||
|
// If we want to edit a different user than self, ensure we have
|
||||||
|
// permissions and subsequently replace the user in question
|
||||||
|
if target.id != "@me" {
|
||||||
|
if !user.privileged {
|
||||||
|
return Err(Error::NotPrivileged);
|
||||||
|
}
|
||||||
|
|
||||||
|
user = target.as_user(db).await?;
|
||||||
|
// Otherwise, filter out invalid edit fields
|
||||||
|
} else if data.badges.is_some() || data.flags.is_some() {
|
||||||
|
return Err(Error::NotPrivileged);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exit out early if nothing is changed
|
||||||
if data.status.is_none()
|
if data.status.is_none()
|
||||||
&& data.profile.is_none()
|
&& data.profile.is_none()
|
||||||
&& data.avatar.is_none()
|
&& data.avatar.is_none()
|
||||||
|
&& data.badges.is_none()
|
||||||
|
&& data.flags.is_none()
|
||||||
&& data.remove.is_none()
|
&& data.remove.is_none()
|
||||||
{
|
{
|
||||||
return Ok(Json(user));
|
return Ok(Json(user));
|
||||||
@@ -83,7 +109,11 @@ pub async fn req(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut partial: PartialUser = Default::default();
|
let mut partial: PartialUser = PartialUser {
|
||||||
|
badges: data.badges,
|
||||||
|
flags: data.flags,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
// 2. Apply new avatar
|
// 2. Apply new avatar
|
||||||
if let Some(avatar) = data.avatar {
|
if let Some(avatar) = data.avatar {
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
use revolt_quark::{Database, Ref, Result};
|
||||||
|
|
||||||
|
use rocket::{serde::json::Json, State};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
/// # Flag Response
|
||||||
|
#[derive(Serialize, JsonSchema)]
|
||||||
|
pub struct FlagResponse {
|
||||||
|
/// Flags
|
||||||
|
flags: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Fetch User Flags
|
||||||
|
///
|
||||||
|
/// Retrieve a user's flags.
|
||||||
|
#[openapi(tag = "User Information")]
|
||||||
|
#[get("/<target>/flags")]
|
||||||
|
pub async fn fetch_user_flags(db: &State<Database>, target: Ref) -> Result<Json<FlagResponse>> {
|
||||||
|
let flags = if let Ok(target) = target.as_user(db).await {
|
||||||
|
target.flags.unwrap_or_default()
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Json(FlagResponse { flags }))
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
|
use revolt_rocket_okapi::revolt_okapi::openapi3::{self, MediaType, RefOr};
|
||||||
use rocket::http::ContentType;
|
use rocket::http::ContentType;
|
||||||
use rocket::response::{self, Responder};
|
use rocket::response::{self, Responder};
|
||||||
use rocket::{Request, Response};
|
use rocket::{Request, Response};
|
||||||
use rocket_okapi::okapi::openapi3::{self, MediaType, RefOr};
|
|
||||||
use schemars::schema::{InstanceType, SchemaObject, SingleOrVec};
|
use schemars::schema::{InstanceType, SchemaObject, SingleOrVec};
|
||||||
|
|
||||||
pub struct CachedFile((ContentType, Vec<u8>));
|
pub struct CachedFile((ContentType, Vec<u8>));
|
||||||
@@ -16,10 +16,10 @@ impl<'r> Responder<'r, 'static> for CachedFile {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl rocket_okapi::response::OpenApiResponderInner for CachedFile {
|
impl revolt_rocket_okapi::response::OpenApiResponderInner for CachedFile {
|
||||||
fn responses(
|
fn responses(
|
||||||
_gen: &mut rocket_okapi::gen::OpenApiGenerator,
|
_gen: &mut revolt_rocket_okapi::gen::OpenApiGenerator,
|
||||||
) -> std::result::Result<openapi3::Responses, rocket_okapi::OpenApiError> {
|
) -> std::result::Result<openapi3::Responses, revolt_rocket_okapi::OpenApiError> {
|
||||||
let mut responses = schemars::Map::new();
|
let mut responses = schemars::Map::new();
|
||||||
let mut content = schemars::Map::new();
|
let mut content = schemars::Map::new();
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
|
use revolt_rocket_okapi::revolt_okapi::openapi3::OpenApi;
|
||||||
use rocket::Route;
|
use rocket::Route;
|
||||||
use rocket_okapi::okapi::openapi3::OpenApi;
|
|
||||||
|
|
||||||
mod add_friend;
|
mod add_friend;
|
||||||
mod block_user;
|
mod block_user;
|
||||||
@@ -9,6 +9,7 @@ mod fetch_dms;
|
|||||||
mod fetch_profile;
|
mod fetch_profile;
|
||||||
mod fetch_self;
|
mod fetch_self;
|
||||||
mod fetch_user;
|
mod fetch_user;
|
||||||
|
mod fetch_user_flags;
|
||||||
mod find_mutual;
|
mod find_mutual;
|
||||||
mod get_default_avatar;
|
mod get_default_avatar;
|
||||||
mod open_dm;
|
mod open_dm;
|
||||||
@@ -21,6 +22,7 @@ pub fn routes() -> (Vec<Route>, OpenApi) {
|
|||||||
// User Information
|
// User Information
|
||||||
fetch_self::req,
|
fetch_self::req,
|
||||||
fetch_user::req,
|
fetch_user::req,
|
||||||
|
fetch_user_flags::fetch_user_flags,
|
||||||
edit_user::req,
|
edit_user::req,
|
||||||
change_username::req,
|
change_username::req,
|
||||||
get_default_avatar::req,
|
get_default_avatar::req,
|
||||||
|
|||||||
Vendored
-2
@@ -1,2 +0,0 @@
|
|||||||
ko_fi: insertish
|
|
||||||
custom: https://insrt.uk/donate
|
|
||||||
-33
@@ -1,33 +0,0 @@
|
|||||||
name: Rust build and test
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [ master ]
|
|
||||||
pull_request:
|
|
||||||
branches: [ master ]
|
|
||||||
|
|
||||||
env:
|
|
||||||
CARGO_TERM_COLOR: always
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
check:
|
|
||||||
name: Rust project
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
- name: Install latest nightly
|
|
||||||
uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: nightly
|
|
||||||
override: true
|
|
||||||
components: rustfmt, clippy
|
|
||||||
|
|
||||||
- name: Run cargo build
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: build
|
|
||||||
|
|
||||||
- name: Run cargo test
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
-49
@@ -1,49 +0,0 @@
|
|||||||
name: Add Issue to Board
|
|
||||||
|
|
||||||
on:
|
|
||||||
issues:
|
|
||||||
types: [opened]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
track_issue:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Get project data
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.PAT }}
|
|
||||||
run: |
|
|
||||||
gh api graphql -f query='
|
|
||||||
query {
|
|
||||||
organization(login: "revoltchat"){
|
|
||||||
projectNext(number: 3) {
|
|
||||||
id
|
|
||||||
fields(first:20) {
|
|
||||||
nodes {
|
|
||||||
id
|
|
||||||
name
|
|
||||||
settings
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}' > project_data.json
|
|
||||||
|
|
||||||
echo 'PROJECT_ID='$(jq '.data.organization.projectNext.id' project_data.json) >> $GITHUB_ENV
|
|
||||||
echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV
|
|
||||||
echo 'TODO_OPTION_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") |.settings | fromjson.options[] | select(.name=="Todo") |.id' project_data.json) >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Add issue to project
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.PAT }}
|
|
||||||
ISSUE_ID: ${{ github.event.issue.node_id }}
|
|
||||||
run: |
|
|
||||||
item_id="$( gh api graphql -f query='
|
|
||||||
mutation($project:ID!, $issue:ID!) {
|
|
||||||
addProjectNextItem(input: {projectId: $project, contentId: $issue}) {
|
|
||||||
projectNextItem {
|
|
||||||
id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}' -f project=$PROJECT_ID -f issue=$ISSUE_ID --jq '.data.addProjectNextItem.projectNextItem.id')"
|
|
||||||
|
|
||||||
echo 'ITEM_ID='$item_id >> $GITHUB_ENV
|
|
||||||
-72
@@ -1,72 +0,0 @@
|
|||||||
name: Add PR to Board
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request_target:
|
|
||||||
types: [opened, synchronize, ready_for_review, review_requested]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
track_pr:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Get project data
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.PAT }}
|
|
||||||
run: |
|
|
||||||
gh api graphql -f query='
|
|
||||||
query {
|
|
||||||
organization(login: "revoltchat"){
|
|
||||||
projectNext(number: 3) {
|
|
||||||
id
|
|
||||||
fields(first:20) {
|
|
||||||
nodes {
|
|
||||||
id
|
|
||||||
name
|
|
||||||
settings
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}' > project_data.json
|
|
||||||
|
|
||||||
echo 'PROJECT_ID='$(jq '.data.organization.projectNext.id' project_data.json) >> $GITHUB_ENV
|
|
||||||
echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV
|
|
||||||
echo 'INCOMING_OPTION_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") |.settings | fromjson.options[] | select(.name=="Incoming PRs") |.id' project_data.json) >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Add PR to project
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.PAT }}
|
|
||||||
PR_ID: ${{ github.event.pull_request.node_id }}
|
|
||||||
run: |
|
|
||||||
item_id="$( gh api graphql -f query='
|
|
||||||
mutation($project:ID!, $pr:ID!) {
|
|
||||||
addProjectNextItem(input: {projectId: $project, contentId: $pr}) {
|
|
||||||
projectNextItem {
|
|
||||||
id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}' -f project=$PROJECT_ID -f pr=$PR_ID --jq '.data.addProjectNextItem.projectNextItem.id')"
|
|
||||||
|
|
||||||
echo 'ITEM_ID='$item_id >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Set fields
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.PAT }}
|
|
||||||
run: |
|
|
||||||
gh api graphql -f query='
|
|
||||||
mutation (
|
|
||||||
$project: ID!
|
|
||||||
$item: ID!
|
|
||||||
$status_field: ID!
|
|
||||||
$status_value: String!
|
|
||||||
) {
|
|
||||||
set_status: updateProjectNextItemField(input: {
|
|
||||||
projectId: $project
|
|
||||||
itemId: $item
|
|
||||||
fieldId: $status_field
|
|
||||||
value: $status_value
|
|
||||||
}) {
|
|
||||||
projectNextItem {
|
|
||||||
id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}' -f project=$PROJECT_ID -f item=$ITEM_ID -f status_field=$STATUS_FIELD_ID -f status_value=${{ env.INCOMING_OPTION_ID }} --silent
|
|
||||||
+15
-16
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-quark"
|
name = "revolt-quark"
|
||||||
version = "0.1.0"
|
version = "0.5.19"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
@@ -16,9 +16,9 @@ rocket_impl = [
|
|||||||
"lru",
|
"lru",
|
||||||
"dashmap",
|
"dashmap",
|
||||||
|
|
||||||
"rauth/database-mongodb",
|
"authifier/database-mongodb",
|
||||||
"rauth/rocket_impl",
|
"authifier/rocket_impl",
|
||||||
"rauth/okapi_impl"
|
"authifier/okapi_impl"
|
||||||
]
|
]
|
||||||
|
|
||||||
test = [ "async-std", "mongo", "mongodb/async-std-runtime", "rocket_impl" ]
|
test = [ "async-std", "mongo", "mongodb/async-std-runtime", "rocket_impl" ]
|
||||||
@@ -29,7 +29,7 @@ default = [ "test" ]
|
|||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
validator = { version = "0.14", features = ["derive"] }
|
validator = { version = "0.14", features = ["derive"] }
|
||||||
iso8601-timestamp = { version = "0.1.8", features = ["schema", "bson"] }
|
iso8601-timestamp = { version = "0.1.8", features = ["schema", "bson"] }
|
||||||
optional_struct = { git = "https://github.com/insertish/OptionalStruct", rev = "e275d2726595474632485934aa0887fa52281f70" }
|
optional_struct = { git = "https://github.com/insertish/OptionalStruct", rev = "ee56427cee1f007839825d93d07fffd5a5e038c7" }
|
||||||
|
|
||||||
# Formats
|
# Formats
|
||||||
bincode = "1.3.3"
|
bincode = "1.3.3"
|
||||||
@@ -38,13 +38,11 @@ bson = { version = "2.1.0", features = ["chrono-0_4"] }
|
|||||||
|
|
||||||
# Spec Generation
|
# Spec Generation
|
||||||
schemars = "0.8.8"
|
schemars = "0.8.8"
|
||||||
okapi = { git = "https://github.com/insertish/okapi", rev = "a1048d0c8cd771e424ec97d33d825c32e06aa120" }
|
revolt_okapi = "0.9.1"
|
||||||
rocket_okapi = { git = "https://github.com/insertish/okapi", rev = "a1048d0c8cd771e424ec97d33d825c32e06aa120" }
|
revolt_rocket_okapi = { version = "0.9.1", features = [ "swagger" ] }
|
||||||
# okapi = "0.7.0-rc.1"
|
|
||||||
# rocket_okapi = "0.8.0-rc.1"
|
|
||||||
|
|
||||||
# Databases
|
# Databases
|
||||||
redis-kiss = { version = "0.1.3" }
|
redis-kiss = { version = "0.1.4" }
|
||||||
mongodb = { optional = true, version = "2.1.0", default-features = false }
|
mongodb = { optional = true, version = "2.1.0", default-features = false }
|
||||||
|
|
||||||
# Async
|
# Async
|
||||||
@@ -59,6 +57,7 @@ log = "0.4.14"
|
|||||||
pretty_env_logger = "0.4.0"
|
pretty_env_logger = "0.4.0"
|
||||||
|
|
||||||
# Util
|
# Util
|
||||||
|
rand = "0.8.5"
|
||||||
ulid = "0.5.0"
|
ulid = "0.5.0"
|
||||||
regex = "1.5.5"
|
regex = "1.5.5"
|
||||||
nanoid = "0.4.0"
|
nanoid = "0.4.0"
|
||||||
@@ -69,8 +68,8 @@ impl_ops = "0.1.1"
|
|||||||
num_enum = "0.5.6"
|
num_enum = "0.5.6"
|
||||||
reqwest = "0.11.10"
|
reqwest = "0.11.10"
|
||||||
bitfield = "0.13.2"
|
bitfield = "0.13.2"
|
||||||
once_cell = "1.13.0"
|
once_cell = "1.17.1"
|
||||||
lazy_static = "1.4.0"
|
async-lock = "2.6.0"
|
||||||
|
|
||||||
lru = { version = "0.7.6", optional = true }
|
lru = { version = "0.7.6", optional = true }
|
||||||
dashmap = { version = "5.2.0", optional = true }
|
dashmap = { version = "5.2.0", optional = true }
|
||||||
@@ -82,11 +81,11 @@ web-push = "0.7.2"
|
|||||||
# Implementations
|
# Implementations
|
||||||
rocket_http = { optional = true, version = "0.5.0-rc.2" }
|
rocket_http = { optional = true, version = "0.5.0-rc.2" }
|
||||||
rocket = { optional = true, version = "0.5.0-rc.2", default-features = false, features = ["json"] }
|
rocket = { optional = true, version = "0.5.0-rc.2", default-features = false, features = ["json"] }
|
||||||
rocket_empty = { optional = true, git = "https://github.com/insertish/rocket_empty", branch = "master" }
|
rocket_empty = { version = "0.1.1", optional = true, features = [ "schema" ] }
|
||||||
rocket_cors = { optional = true, git = "https://github.com/lawliet89/rocket_cors", rev = "5843861a88958c16bfaa0b40f0d8910772bcd2f6" }
|
rocket_cors = { optional = true, git = "https://github.com/lawliet89/rocket_cors", rev = "c17e8145baa4790319fdb6a473e465b960f55e7c" }
|
||||||
|
|
||||||
# rAuth
|
# Authifier
|
||||||
rauth = { git = "https://github.com/insertish/rauth", rev = "cbdec69c684a4854fbedba9ed1f0e7ee466bf3f7", features = [ "async-std-runtime" ] }
|
authifier = { version = "1.0.7", features = [ "async-std-runtime" ] }
|
||||||
|
|
||||||
# Sentry
|
# Sentry
|
||||||
sentry = "0.25.0"
|
sentry = "0.25.0"
|
||||||
@@ -61,13 +61,13 @@ impl Deref for Database {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Database> for rauth::Database {
|
impl From<Database> for authifier::Database {
|
||||||
fn from(val: Database) -> Self {
|
fn from(val: Database) -> Self {
|
||||||
match val {
|
match val {
|
||||||
Database::Dummy(_) => rauth::Database::default(),
|
Database::Dummy(_) => authifier::Database::default(),
|
||||||
Database::MongoDb(MongoDb(client)) => {
|
Database::MongoDb(MongoDb(client)) => authifier::Database::MongoDb(
|
||||||
rauth::Database::MongoDb(rauth::database::MongoDb(client.database("revolt")))
|
authifier::database::MongoDb(client.database("revolt")),
|
||||||
}
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use authifier::AuthifierEvent;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::models::channel::{FieldsChannel, PartialChannel};
|
use crate::models::channel::{FieldsChannel, PartialChannel};
|
||||||
@@ -5,7 +6,7 @@ use crate::models::message::{AppendMessage, PartialMessage};
|
|||||||
use crate::models::server::{FieldsRole, FieldsServer, PartialRole, PartialServer};
|
use crate::models::server::{FieldsRole, FieldsServer, PartialRole, PartialServer};
|
||||||
use crate::models::server_member::{FieldsMember, MemberCompositeKey, PartialMember};
|
use crate::models::server_member::{FieldsMember, MemberCompositeKey, PartialMember};
|
||||||
use crate::models::user::{FieldsUser, PartialUser, RelationshipStatus};
|
use crate::models::user::{FieldsUser, PartialUser, RelationshipStatus};
|
||||||
use crate::models::{Channel, Emoji, Member, Message, Server, User, UserSettings};
|
use crate::models::{Channel, Emoji, Member, Message, Report, Server, User, UserSettings};
|
||||||
use crate::Error;
|
use crate::Error;
|
||||||
|
|
||||||
/// WebSocket Client Errors
|
/// WebSocket Client Errors
|
||||||
@@ -195,9 +196,26 @@ pub enum EventV1 {
|
|||||||
/// Settings updated remotely
|
/// Settings updated remotely
|
||||||
UserSettingsUpdate { id: String, update: UserSettings },
|
UserSettingsUpdate { id: String, update: UserSettings },
|
||||||
|
|
||||||
|
/// User has been platform banned or deleted their account
|
||||||
|
///
|
||||||
|
/// Clients should remove the following associated data:
|
||||||
|
/// - Messages
|
||||||
|
/// - DM Channels
|
||||||
|
/// - Relationships
|
||||||
|
/// - Server Memberships
|
||||||
|
///
|
||||||
|
/// User flags are specified to explain why a wipe is occurring though not all reasons will necessarily ever appear.
|
||||||
|
UserPlatformWipe { user_id: String, flags: i32 },
|
||||||
|
|
||||||
/// New emoji
|
/// New emoji
|
||||||
EmojiCreate(Emoji),
|
EmojiCreate(Emoji),
|
||||||
|
|
||||||
/// Delete emoji
|
/// Delete emoji
|
||||||
EmojiDelete { id: String },
|
EmojiDelete { id: String },
|
||||||
|
|
||||||
|
/// New report
|
||||||
|
ReportCreate(Report),
|
||||||
|
|
||||||
|
/// Auth events
|
||||||
|
Auth(AuthifierEvent),
|
||||||
}
|
}
|
||||||
@@ -23,11 +23,7 @@ impl Cache {
|
|||||||
pub async fn can_view_channel(&self, db: &Database, channel: &Channel) -> bool {
|
pub async fn can_view_channel(&self, db: &Database, channel: &Channel) -> bool {
|
||||||
match &channel {
|
match &channel {
|
||||||
Channel::TextChannel { server, .. } | Channel::VoiceChannel { server, .. } => {
|
Channel::TextChannel { server, .. } | Channel::VoiceChannel { server, .. } => {
|
||||||
let member = self
|
let member = self.members.values().find(|x| &x.id.server == server);
|
||||||
.members
|
|
||||||
.iter()
|
|
||||||
.map(|(_, x)| x)
|
|
||||||
.find(|x| &x.id.server == server);
|
|
||||||
|
|
||||||
let server = self.servers.get(server);
|
let server = self.servers.get(server);
|
||||||
let mut perms = perms(self.users.get(&self.user_id).unwrap()).channel(channel);
|
let mut perms = perms(self.users.get(&self.user_id).unwrap()).channel(channel);
|
||||||
@@ -103,7 +99,7 @@ impl State {
|
|||||||
let mut user = self.clone_user();
|
let mut user = self.clone_user();
|
||||||
|
|
||||||
// Find all relationships to the user.
|
// Find all relationships to the user.
|
||||||
let mut user_ids: Vec<String> = user
|
let mut user_ids: HashSet<String> = user
|
||||||
.relations
|
.relations
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|arr| arr.iter().map(|x| x.id.to_string()).collect())
|
.map(|arr| arr.iter().map(|x| x.id.to_string()).collect())
|
||||||
@@ -132,14 +128,15 @@ impl State {
|
|||||||
for channel in &channels {
|
for channel in &channels {
|
||||||
match channel {
|
match channel {
|
||||||
Channel::DirectMessage { recipients, .. } | Channel::Group { recipients, .. } => {
|
Channel::DirectMessage { recipients, .. } | Channel::Group { recipients, .. } => {
|
||||||
user_ids.append(&mut recipients.clone());
|
user_ids.extend(&mut recipients.clone().into_iter());
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch presence data for known users.
|
// Fetch presence data for known users.
|
||||||
let online_ids = presence_filter_online(&user_ids).await;
|
let online_ids =
|
||||||
|
presence_filter_online(&user_ids.iter().cloned().collect::<Vec<String>>()).await;
|
||||||
user.online = Some(true);
|
user.online = Some(true);
|
||||||
|
|
||||||
// Fetch user data.
|
// Fetch user data.
|
||||||
@@ -561,6 +558,11 @@ impl EventV1 {
|
|||||||
|
|
||||||
/// Publish private event
|
/// Publish private event
|
||||||
pub async fn private(self, id: String) {
|
pub async fn private(self, id: String) {
|
||||||
self.p(format!("{}!", id)).await;
|
self.p(format!("{id}!")).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Publish internal global event
|
||||||
|
pub async fn global(self) {
|
||||||
|
self.p("global".to_string()).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
use crate::{models::stats::Stats, AbstractStats, Result};
|
||||||
|
|
||||||
|
use super::super::DummyDb;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl AbstractStats for DummyDb {
|
||||||
|
async fn generate_stats(&self) -> Result<Stats> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::models::message::{AppendMessage, Message, MessageSort, PartialMessage};
|
use crate::models::message::{AppendMessage, Message, MessageQuery, PartialMessage};
|
||||||
use crate::{AbstractMessage, Result};
|
use crate::{AbstractMessage, Result};
|
||||||
|
|
||||||
use super::super::DummyDb;
|
use super::super::DummyDb;
|
||||||
@@ -41,28 +41,8 @@ impl AbstractMessage for DummyDb {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn fetch_messages(
|
async fn fetch_messages(&self, _query: MessageQuery) -> Result<Vec<Message>> {
|
||||||
&self,
|
Ok(vec![])
|
||||||
channel: &str,
|
|
||||||
_limit: Option<i64>,
|
|
||||||
_before: Option<String>,
|
|
||||||
_after: Option<String>,
|
|
||||||
_sort: Option<MessageSort>,
|
|
||||||
_nearby: Option<String>,
|
|
||||||
) -> Result<Vec<Message>> {
|
|
||||||
Ok(vec![self.fetch_message(channel).await.unwrap()])
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn search_messages(
|
|
||||||
&self,
|
|
||||||
channel: &str,
|
|
||||||
_query: &str,
|
|
||||||
_limit: Option<i64>,
|
|
||||||
_before: Option<String>,
|
|
||||||
_after: Option<String>,
|
|
||||||
_sort: MessageSort,
|
|
||||||
) -> Result<Vec<Message>> {
|
|
||||||
Ok(vec![self.fetch_message(channel).await.unwrap()])
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add a new reaction to a message
|
/// Add a new reaction to a message
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use crate::AbstractDatabase;
|
|||||||
|
|
||||||
pub mod admin {
|
pub mod admin {
|
||||||
pub mod migrations;
|
pub mod migrations;
|
||||||
|
pub mod stats;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub mod media {
|
pub mod media {
|
||||||
@@ -28,6 +29,11 @@ pub mod users {
|
|||||||
pub mod user_settings;
|
pub mod user_settings;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub mod safety {
|
||||||
|
pub mod report;
|
||||||
|
pub mod snapshot;
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct DummyDb;
|
pub struct DummyDb;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
use crate::models::report::PartialReport;
|
||||||
|
use crate::models::Report;
|
||||||
|
use crate::{AbstractReport, Result};
|
||||||
|
|
||||||
|
use super::super::DummyDb;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl AbstractReport for DummyDb {
|
||||||
|
async fn insert_report(&self, report: &Report) -> Result<()> {
|
||||||
|
info!("Insert {:?}", report);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_report(&self, _id: &str, _report: &PartialReport) -> Result<()> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_report(&self, _report_id: &str) -> Result<Report> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_reports(&self) -> Result<Vec<Report>> {
|
||||||
|
Ok(vec![])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
use crate::models::Snapshot;
|
||||||
|
use crate::{AbstractSnapshot, Result};
|
||||||
|
|
||||||
|
use super::super::DummyDb;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl AbstractSnapshot for DummyDb {
|
||||||
|
async fn insert_snapshot(&self, snapshot: &Snapshot) -> Result<()> {
|
||||||
|
info!("Insert {:?}", snapshot);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_snapshot(&self, _report_id: &str) -> Result<Snapshot> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,13 +5,11 @@ use crate::{
|
|||||||
Database, Error, Result,
|
Database, Error, Result,
|
||||||
};
|
};
|
||||||
|
|
||||||
lazy_static! {
|
static ALPHABET: [char; 54] = [
|
||||||
static ref ALPHABET: [char; 54] = [
|
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
|
||||||
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
|
'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
|
||||||
'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
|
'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'
|
||||||
'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'
|
];
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Invite {
|
impl Invite {
|
||||||
/// Get the invite code for this invite
|
/// Get the invite code for this invite
|
||||||
@@ -30,7 +28,7 @@ impl Invite {
|
|||||||
|
|
||||||
/// Create a new invite from given information
|
/// Create a new invite from given information
|
||||||
pub async fn create(db: &Database, creator: &User, target: &Channel) -> Result<Invite> {
|
pub async fn create(db: &Database, creator: &User, target: &Channel) -> Result<Invite> {
|
||||||
let code = nanoid!(8, &*ALPHABET);
|
let code = nanoid!(8, &ALPHABET);
|
||||||
let invite = match &target {
|
let invite = match &target {
|
||||||
Channel::Group { id, .. } => Ok(Invite::Group {
|
Channel::Group { id, .. } => Ok(Invite::Group {
|
||||||
code,
|
code,
|
||||||
|
|||||||
@@ -305,12 +305,12 @@ impl IntoUsers for Message {
|
|||||||
|
|
||||||
impl IntoUsers for Vec<Message> {
|
impl IntoUsers for Vec<Message> {
|
||||||
fn get_user_ids(&self) -> Vec<String> {
|
fn get_user_ids(&self) -> Vec<String> {
|
||||||
let mut ids = vec![];
|
let mut ids = HashSet::new();
|
||||||
for message in self {
|
for message in self {
|
||||||
ids.append(&mut message.get_user_ids());
|
ids.extend(&mut message.get_user_ids().into_iter());
|
||||||
}
|
}
|
||||||
|
|
||||||
ids
|
ids.into_iter().collect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -377,7 +377,7 @@ impl SendableEmbed {
|
|||||||
impl BulkMessageResponse {
|
impl BulkMessageResponse {
|
||||||
pub async fn transform(
|
pub async fn transform(
|
||||||
db: &Database,
|
db: &Database,
|
||||||
channel: &Channel,
|
channel: Option<&Channel>,
|
||||||
messages: Vec<Message>,
|
messages: Vec<Message>,
|
||||||
include_users: Option<bool>,
|
include_users: Option<bool>,
|
||||||
) -> Result<BulkMessageResponse> {
|
) -> Result<BulkMessageResponse> {
|
||||||
@@ -386,7 +386,8 @@ impl BulkMessageResponse {
|
|||||||
let users = User::fetch_foreign_users(db, &user_ids).await?;
|
let users = User::fetch_foreign_users(db, &user_ids).await?;
|
||||||
|
|
||||||
Ok(match channel {
|
Ok(match channel {
|
||||||
Channel::TextChannel { server, .. } | Channel::VoiceChannel { server, .. } => {
|
Some(Channel::TextChannel { server, .. })
|
||||||
|
| Some(Channel::VoiceChannel { server, .. }) => {
|
||||||
BulkMessageResponse::MessagesAndUsers {
|
BulkMessageResponse::MessagesAndUsers {
|
||||||
messages,
|
messages,
|
||||||
users,
|
users,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use std::{collections::HashSet, str::FromStr};
|
use std::{collections::HashSet, str::FromStr};
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
|
|
||||||
@@ -8,13 +9,10 @@ use crate::{
|
|||||||
Database, Result,
|
Database, Result,
|
||||||
};
|
};
|
||||||
|
|
||||||
lazy_static! {
|
static PERMISSIBLE_EMOJIS: Lazy<HashSet<String>> = Lazy::new(|| include_str!(crate::asset!("emojis.txt"))
|
||||||
/// Permissible emojis
|
.split('\n')
|
||||||
static ref PERMISSIBLE_EMOJIS: HashSet<String> = include_str!(crate::asset!("emojis.txt"))
|
.map(|x| x.into())
|
||||||
.split('\n')
|
.collect());
|
||||||
.map(|x| x.into())
|
|
||||||
.collect();
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Emoji {
|
impl Emoji {
|
||||||
/// Get parent id
|
/// Get parent id
|
||||||
|
|||||||
@@ -27,3 +27,7 @@ pub mod users {
|
|||||||
pub mod user;
|
pub mod user;
|
||||||
pub mod user_settings;
|
pub mod user_settings;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub mod safety {
|
||||||
|
pub mod report;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
use crate::{models::report::PartialReport, models::Report, Database, Result};
|
||||||
|
|
||||||
|
impl Report {
|
||||||
|
/// Update report data
|
||||||
|
pub async fn update(&mut self, db: &Database, partial: PartialReport) -> Result<()> {
|
||||||
|
self.apply_options(partial.clone());
|
||||||
|
db.update_report(&self.id, &partial).await
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -57,6 +57,14 @@ pub async fn create_database(db: &MongoDb) {
|
|||||||
.await
|
.await
|
||||||
.expect("Failed to create user_settings collection.");
|
.expect("Failed to create user_settings collection.");
|
||||||
|
|
||||||
|
db.create_collection("safety_reports", None)
|
||||||
|
.await
|
||||||
|
.expect("Failed to create safety_reports collection.");
|
||||||
|
|
||||||
|
db.create_collection("safety_snapshots", None)
|
||||||
|
.await
|
||||||
|
.expect("Failed to create safety_snapshots collection.");
|
||||||
|
|
||||||
db.create_collection("bots", None)
|
db.create_collection("bots", None)
|
||||||
.await
|
.await
|
||||||
.expect("Failed to create bots collection.");
|
.expect("Failed to create bots collection.");
|
||||||
@@ -103,18 +111,18 @@ pub async fn create_database(db: &MongoDb) {
|
|||||||
},
|
},
|
||||||
"name": "content"
|
"name": "content"
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"key": {
|
|
||||||
"channel": 1_i32
|
|
||||||
},
|
|
||||||
"name": "channel"
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"key": {
|
"key": {
|
||||||
"channel": 1_i32,
|
"channel": 1_i32,
|
||||||
"_id": 1_i32
|
"_id": 1_i32
|
||||||
},
|
},
|
||||||
"name": "channel_id_compound"
|
"name": "channel_id_compound"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": {
|
||||||
|
"author": 1_i32
|
||||||
|
},
|
||||||
|
"name": "author"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use std::time::Duration;
|
use std::{time::Duration, ops::BitXor};
|
||||||
|
|
||||||
use bson::{Bson, DateTime};
|
use bson::{Bson, DateTime};
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
@@ -16,7 +16,7 @@ struct MigrationInfo {
|
|||||||
revision: i32,
|
revision: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const LATEST_REVISION: i32 = 18;
|
pub const LATEST_REVISION: i32 = 21;
|
||||||
|
|
||||||
pub async fn migrate_database(db: &MongoDb) {
|
pub async fn migrate_database(db: &MongoDb) {
|
||||||
let migrations = db.col::<Document>("migrations");
|
let migrations = db.col::<Document>("migrations");
|
||||||
@@ -215,7 +215,7 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if revision <= 8 {
|
if revision <= 8 {
|
||||||
info!("Running migration [revision 8 / 2021-09-10]: Update to rAuth version 1.");
|
info!("Running migration [revision 8 / 2021-09-10]: Update to Authifier version 1.");
|
||||||
|
|
||||||
db.db()
|
db.db()
|
||||||
.run_command(
|
.run_command(
|
||||||
@@ -503,13 +503,8 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
|
|||||||
|
|
||||||
update.insert(
|
update.insert(
|
||||||
"default_permissions",
|
"default_permissions",
|
||||||
(*DEFAULT_PERMISSION_SERVER
|
// Remove Send Message permission if it wasn't originally granted
|
||||||
// Remove Send Message permission if it wasn't originally granted
|
DEFAULT_PERMISSION_SERVER.bitxor(if has_send { 0 } else { Permission::SendMessage as u64}) as i64,
|
||||||
^ (if has_send {
|
|
||||||
0
|
|
||||||
} else {
|
|
||||||
Permission::SendMessage as u64
|
|
||||||
})) as i64,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
if let Some(Bson::Document(mut roles)) = document.remove("roles") {
|
if let Some(Bson::Document(mut roles)) = document.remove("roles") {
|
||||||
@@ -603,20 +598,20 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if revision <= 15 {
|
if revision <= 15 {
|
||||||
info!("Running migration [revision 15 / 04-06-2022]: Migrate rAuth to latest version.");
|
info!("Running migration [revision 15 / 04-06-2022]: Migrate Authifier to latest version.");
|
||||||
|
|
||||||
let db = rauth::Database::MongoDb(rauth::database::MongoDb(db.db()));
|
let db = authifier::Database::MongoDb(authifier::database::MongoDb(db.db()));
|
||||||
db.run_migration(rauth::Migration::M2022_06_03EnsureUpToSpec)
|
db.run_migration(authifier::Migration::M2022_06_03EnsureUpToSpec)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
if revision <= 16 {
|
if revision <= 16 {
|
||||||
info!("Running migration [revision 16 / 07-07-2022]: Add `emojis` collection and rAuth migration.");
|
info!("Running migration [revision 16 / 07-07-2022]: Add `emojis` collection and Authifier migration.");
|
||||||
|
|
||||||
let rauth_db = rauth::Database::MongoDb(rauth::database::MongoDb(db.db()));
|
let authifier_db = authifier::Database::MongoDb(authifier::database::MongoDb(db.db()));
|
||||||
rauth_db
|
authifier_db
|
||||||
.run_migration(rauth::Migration::M2022_06_09AddIndexForDeletion)
|
.run_migration(authifier::Migration::M2022_06_09AddIndexForDeletion)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
@@ -661,6 +656,103 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
|
|||||||
.expect("Failed to update server members.");
|
.expect("Failed to update server members.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if revision <= 18 {
|
||||||
|
info!("Running migration [revision 18 / 27-02-2022]: Create author index on messages. Drop plain channel index if exists.");
|
||||||
|
|
||||||
|
if db
|
||||||
|
.db()
|
||||||
|
.run_command(
|
||||||
|
doc! {
|
||||||
|
"dropIndexes": "messages",
|
||||||
|
"index": ["channel"]
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
info!("Failed to drop `messages.channel` index but this is ok since that means it's probably gone.");
|
||||||
|
}
|
||||||
|
|
||||||
|
db.db()
|
||||||
|
.run_command(
|
||||||
|
doc! {
|
||||||
|
"createIndexes": "messages",
|
||||||
|
"indexes": [
|
||||||
|
{
|
||||||
|
"key": {
|
||||||
|
"author": 1_i32,
|
||||||
|
},
|
||||||
|
"name": "author"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("Failed to create messages author index.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if revision <= 19 {
|
||||||
|
info!("Running migration [revision 19 / 27-02-2023]: Create report / snapshot collections, migrate to new model if applicable.");
|
||||||
|
|
||||||
|
// TODO: make these fail once production is migrated
|
||||||
|
if db
|
||||||
|
.db()
|
||||||
|
.create_collection("safety_reports", None)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
info!("Failed to create safety_reports collection but this is expected in production.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if db
|
||||||
|
.db()
|
||||||
|
.create_collection("safety_snapshots", None)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
info!(
|
||||||
|
"Failed to create safety_snapshots collection but this is expected in production."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
db.col::<Document>("safety_reports")
|
||||||
|
.update_many(
|
||||||
|
doc! {},
|
||||||
|
doc! {
|
||||||
|
"$set": {
|
||||||
|
"status": "Created"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
if revision <= 20 {
|
||||||
|
info!("Running migration [revision 20 / 28-02-2023]: Add index `snapshot.report_id`.");
|
||||||
|
|
||||||
|
db.db()
|
||||||
|
.run_command(
|
||||||
|
doc! {
|
||||||
|
"createIndexes": "safety_snapshots",
|
||||||
|
"indexes": [
|
||||||
|
{
|
||||||
|
"key": {
|
||||||
|
"report_id": 1_i32
|
||||||
|
},
|
||||||
|
"name": "report_id"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("Failed to create safety snapshot index.");
|
||||||
|
}
|
||||||
|
|
||||||
// Need to migrate fields on attachments, change `user_id`, `object_id`, etc to `parent`.
|
// Need to migrate fields on attachments, change `user_id`, `object_id`, etc to `parent`.
|
||||||
|
|
||||||
// Reminder to update LATEST_REVISION when adding new migrations.
|
// Reminder to update LATEST_REVISION when adding new migrations.
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use bson::{from_document, Document};
|
||||||
|
use futures::StreamExt;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
models::stats::{Index, Stats},
|
||||||
|
AbstractStats, Error, Result,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::super::MongoDb;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl AbstractStats for MongoDb {
|
||||||
|
async fn generate_stats(&self) -> Result<Stats> {
|
||||||
|
let mut indices = HashMap::new();
|
||||||
|
let mut coll_stats = HashMap::new();
|
||||||
|
|
||||||
|
let collection_names =
|
||||||
|
self.db()
|
||||||
|
.list_collection_names(None)
|
||||||
|
.await
|
||||||
|
.map_err(|_| Error::DatabaseError {
|
||||||
|
operation: "list_collection_names",
|
||||||
|
with: "database",
|
||||||
|
})?;
|
||||||
|
|
||||||
|
for collection in collection_names {
|
||||||
|
indices.insert(
|
||||||
|
collection.to_string(),
|
||||||
|
self.col::<Document>(&collection)
|
||||||
|
.aggregate(
|
||||||
|
vec![doc! {
|
||||||
|
"$indexStats": { }
|
||||||
|
}],
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|_| Error::DatabaseError {
|
||||||
|
operation: "aggregate",
|
||||||
|
with: "col",
|
||||||
|
})?
|
||||||
|
.filter_map(|s| async { s.ok() })
|
||||||
|
.collect::<Vec<Document>>()
|
||||||
|
.await
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|doc| from_document(doc).ok())
|
||||||
|
.collect::<Vec<Index>>(),
|
||||||
|
);
|
||||||
|
|
||||||
|
coll_stats.insert(
|
||||||
|
collection.to_string(),
|
||||||
|
self.col::<Document>(&collection)
|
||||||
|
.aggregate(
|
||||||
|
vec![doc! {
|
||||||
|
"$collStats": {
|
||||||
|
"latencyStats": {
|
||||||
|
"histograms": true
|
||||||
|
},
|
||||||
|
"storageStats": {},
|
||||||
|
"count": {},
|
||||||
|
"queryExecStats": {}
|
||||||
|
}
|
||||||
|
}],
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|_| Error::DatabaseError {
|
||||||
|
operation: "aggregate",
|
||||||
|
with: "col",
|
||||||
|
})?
|
||||||
|
.filter_map(|s| async { s.ok() })
|
||||||
|
.collect::<Vec<Document>>()
|
||||||
|
.await
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|doc| from_document(doc).ok())
|
||||||
|
.next()
|
||||||
|
.ok_or(Error::DatabaseError {
|
||||||
|
operation: "next aggregation",
|
||||||
|
with: "col",
|
||||||
|
})?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Stats {
|
||||||
|
indices,
|
||||||
|
coll_stats,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,9 @@ use bson::{to_bson, Document};
|
|||||||
use futures::try_join;
|
use futures::try_join;
|
||||||
use mongodb::options::FindOptions;
|
use mongodb::options::FindOptions;
|
||||||
|
|
||||||
use crate::models::message::{AppendMessage, Message, MessageSort, PartialMessage};
|
use crate::models::message::{
|
||||||
|
AppendMessage, Message, MessageQuery, MessageSort, MessageTimePeriod, PartialMessage,
|
||||||
|
};
|
||||||
use crate::r#impl::mongo::DocumentId;
|
use crate::r#impl::mongo::DocumentId;
|
||||||
use crate::{AbstractMessage, Error, Result};
|
use crate::{AbstractMessage, Error, Result};
|
||||||
|
|
||||||
@@ -139,145 +141,138 @@ impl AbstractMessage for MongoDb {
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn fetch_messages(
|
async fn fetch_messages(&self, query: MessageQuery) -> Result<Vec<Message>> {
|
||||||
&self,
|
let mut filter = doc! {};
|
||||||
channel: &str,
|
|
||||||
limit: Option<i64>,
|
// 1. Apply message filters
|
||||||
before: Option<String>,
|
if let Some(channel) = query.filter.channel {
|
||||||
after: Option<String>,
|
filter.insert("channel", channel);
|
||||||
sort: Option<MessageSort>,
|
}
|
||||||
nearby: Option<String>,
|
|
||||||
) -> Result<Vec<Message>> {
|
if let Some(author) = query.filter.author {
|
||||||
let limit = limit.unwrap_or(50);
|
filter.insert("author", author);
|
||||||
Ok(if let Some(nearby) = nearby {
|
}
|
||||||
let (a, b) = try_join!(
|
|
||||||
self.find_with_options::<_, Message>(
|
let is_search_query = if let Some(query) = query.filter.query {
|
||||||
COL,
|
filter.insert(
|
||||||
|
"$text",
|
||||||
|
doc! {
|
||||||
|
"$search": query
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
};
|
||||||
|
|
||||||
|
// 2. Find query limit
|
||||||
|
let limit = query.limit.unwrap_or(50);
|
||||||
|
|
||||||
|
// 3. Apply message time period
|
||||||
|
match query.time_period {
|
||||||
|
MessageTimePeriod::Relative { nearby } => {
|
||||||
|
// 3.1. Prepare filters
|
||||||
|
let mut older_message_filter = filter.clone();
|
||||||
|
let mut newer_message_filter = filter;
|
||||||
|
|
||||||
|
older_message_filter.insert(
|
||||||
|
"_id",
|
||||||
doc! {
|
doc! {
|
||||||
"channel": channel,
|
"$lt": &nearby
|
||||||
"_id": {
|
|
||||||
"$gte": &nearby
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
FindOptions::builder()
|
);
|
||||||
.limit(limit / 2 + 1)
|
|
||||||
.sort(doc! {
|
newer_message_filter.insert(
|
||||||
"_id": 1_i32
|
"_id",
|
||||||
})
|
|
||||||
.build(),
|
|
||||||
),
|
|
||||||
self.find_with_options::<_, Message>(
|
|
||||||
COL,
|
|
||||||
doc! {
|
doc! {
|
||||||
"channel": channel,
|
"$gte": &nearby
|
||||||
"_id": {
|
|
||||||
"$lt": &nearby
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// 3.2. Execute in both directions
|
||||||
|
let (a, b) = try_join!(
|
||||||
|
self.find_with_options::<_, Message>(
|
||||||
|
COL,
|
||||||
|
newer_message_filter,
|
||||||
|
FindOptions::builder()
|
||||||
|
.limit(limit / 2 + 1)
|
||||||
|
.sort(doc! {
|
||||||
|
"_id": 1_i32
|
||||||
|
})
|
||||||
|
.build(),
|
||||||
|
),
|
||||||
|
self.find_with_options::<_, Message>(
|
||||||
|
COL,
|
||||||
|
older_message_filter,
|
||||||
|
FindOptions::builder()
|
||||||
|
.limit(limit / 2)
|
||||||
|
.sort(doc! {
|
||||||
|
"_id": -1_i32
|
||||||
|
})
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
)?;
|
||||||
|
|
||||||
|
Ok([a, b].concat())
|
||||||
|
}
|
||||||
|
MessageTimePeriod::Absolute {
|
||||||
|
before,
|
||||||
|
after,
|
||||||
|
sort,
|
||||||
|
} => {
|
||||||
|
// 3.1. Apply message ID filter
|
||||||
|
if let Some(doc) = match (before, after) {
|
||||||
|
(Some(before), Some(after)) => Some(doc! {
|
||||||
|
"$lt": before,
|
||||||
|
"$gt": after
|
||||||
|
}),
|
||||||
|
(Some(before), _) => Some(doc! {
|
||||||
|
"$lt": before
|
||||||
|
}),
|
||||||
|
(_, Some(after)) => Some(doc! {
|
||||||
|
"$gt": after
|
||||||
|
}),
|
||||||
|
_ => None,
|
||||||
|
} {
|
||||||
|
filter.insert("_id", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.2. Execute with given message sort
|
||||||
|
self.find_with_options(
|
||||||
|
COL,
|
||||||
|
filter,
|
||||||
FindOptions::builder()
|
FindOptions::builder()
|
||||||
.limit(limit / 2)
|
.limit(limit)
|
||||||
.sort(doc! {
|
.sort(match sort.unwrap_or(MessageSort::Latest) {
|
||||||
"_id": -1_i32
|
// Sort by relevance, fallback to latest
|
||||||
|
MessageSort::Relevance => {
|
||||||
|
if is_search_query {
|
||||||
|
doc! {
|
||||||
|
"score": {
|
||||||
|
"$meta": "textScore"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
doc! {
|
||||||
|
"_id": -1_i32
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Sort by latest first
|
||||||
|
MessageSort::Latest => doc! {
|
||||||
|
"_id": -1_i32
|
||||||
|
},
|
||||||
|
// Sort by oldest first
|
||||||
|
MessageSort::Oldest => doc! {
|
||||||
|
"_id": 1_i32
|
||||||
|
},
|
||||||
})
|
})
|
||||||
.build(),
|
.build(),
|
||||||
)
|
)
|
||||||
)?;
|
.await
|
||||||
|
|
||||||
[a, b].concat()
|
|
||||||
} else {
|
|
||||||
let mut query = doc! { "channel": channel };
|
|
||||||
if let Some(before) = before {
|
|
||||||
query.insert("_id", doc! { "$lt": before });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(after) = after {
|
|
||||||
query.insert("_id", doc! { "$gt": after });
|
|
||||||
}
|
|
||||||
|
|
||||||
let sort: i32 = if let MessageSort::Latest = sort.unwrap_or(MessageSort::Latest) {
|
|
||||||
-1
|
|
||||||
} else {
|
|
||||||
1
|
|
||||||
};
|
|
||||||
|
|
||||||
self.find_with_options::<_, Message>(
|
|
||||||
COL,
|
|
||||||
query,
|
|
||||||
FindOptions::builder()
|
|
||||||
.limit(limit)
|
|
||||||
.sort(doc! {
|
|
||||||
"_id": sort
|
|
||||||
})
|
|
||||||
.build(),
|
|
||||||
)
|
|
||||||
.await?
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn search_messages(
|
|
||||||
&self,
|
|
||||||
channel: &str,
|
|
||||||
query: &str,
|
|
||||||
limit: Option<i64>,
|
|
||||||
before: Option<String>,
|
|
||||||
after: Option<String>,
|
|
||||||
sort: MessageSort,
|
|
||||||
) -> Result<Vec<Message>> {
|
|
||||||
let limit = limit.unwrap_or(50);
|
|
||||||
|
|
||||||
let mut filter = doc! {
|
|
||||||
"channel": channel,
|
|
||||||
"$text": {
|
|
||||||
"$search": query
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(doc) = match (before, after) {
|
|
||||||
(Some(before), Some(after)) => Some(doc! {
|
|
||||||
"lt": before,
|
|
||||||
"gt": after
|
|
||||||
}),
|
|
||||||
(Some(before), _) => Some(doc! {
|
|
||||||
"lt": before
|
|
||||||
}),
|
|
||||||
(_, Some(after)) => Some(doc! {
|
|
||||||
"gt": after
|
|
||||||
}),
|
|
||||||
_ => None,
|
|
||||||
} {
|
|
||||||
filter.insert("_id", doc);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.find_with_options(
|
|
||||||
COL,
|
|
||||||
filter,
|
|
||||||
FindOptions::builder()
|
|
||||||
.projection(if let MessageSort::Relevance = &sort {
|
|
||||||
doc! {
|
|
||||||
"score": {
|
|
||||||
"$meta": "textScore"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
doc! {}
|
|
||||||
})
|
|
||||||
.limit(limit)
|
|
||||||
.sort(match &sort {
|
|
||||||
MessageSort::Relevance => doc! {
|
|
||||||
"score": {
|
|
||||||
"$meta": "textScore"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
MessageSort::Latest => doc! {
|
|
||||||
"_id": -1_i32
|
|
||||||
},
|
|
||||||
MessageSort::Oldest => doc! {
|
|
||||||
"_id": 1_i32
|
|
||||||
},
|
|
||||||
})
|
|
||||||
.build(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add a new reaction to a message
|
/// Add a new reaction to a message
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ impl AbstractAttachment for MongoDb {
|
|||||||
parent_type: &str,
|
parent_type: &str,
|
||||||
parent_id: &str,
|
parent_id: &str,
|
||||||
) -> Result<File> {
|
) -> Result<File> {
|
||||||
let key = format!("{}_id", parent_type);
|
let key = format!("{parent_type}_id");
|
||||||
match self
|
match self
|
||||||
.find_one::<File>(
|
.find_one::<File>(
|
||||||
COL,
|
COL,
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ use crate::{util::manipulation::prefix_keys, AbstractDatabase, Error, Result};
|
|||||||
|
|
||||||
pub mod admin {
|
pub mod admin {
|
||||||
pub mod migrations;
|
pub mod migrations;
|
||||||
|
pub mod stats;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub mod media {
|
pub mod media {
|
||||||
@@ -39,6 +40,11 @@ pub mod users {
|
|||||||
pub mod user_settings;
|
pub mod user_settings;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub mod safety {
|
||||||
|
pub mod report;
|
||||||
|
pub mod snapshot;
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct MongoDb(pub mongodb::Client);
|
pub struct MongoDb(pub mongodb::Client);
|
||||||
|
|
||||||
@@ -84,17 +90,25 @@ impl MongoDb {
|
|||||||
where
|
where
|
||||||
O: Into<Option<FindOptions>>,
|
O: Into<Option<FindOptions>>,
|
||||||
{
|
{
|
||||||
Ok(self
|
let result = self.col::<T>(collection).find(projection, options).await;
|
||||||
.col::<T>(collection)
|
Ok(if cfg!(debug_assertions) {
|
||||||
.find(projection, options)
|
result.unwrap()
|
||||||
.await
|
} else {
|
||||||
.map_err(|_| Error::DatabaseError {
|
result.map_err(|_| Error::DatabaseError {
|
||||||
operation: "find",
|
operation: "find",
|
||||||
with: collection,
|
with: collection,
|
||||||
})?
|
})?
|
||||||
.filter_map(|s| async { s.ok() })
|
}
|
||||||
.collect::<Vec<T>>()
|
.filter_map(|s| async {
|
||||||
.await)
|
if cfg!(debug_assertions) {
|
||||||
|
// Hard fail on invalid documents
|
||||||
|
Some(s.unwrap())
|
||||||
|
} else {
|
||||||
|
s.ok()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<Vec<T>>()
|
||||||
|
.await)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn find<T: DeserializeOwned + Unpin + Send + Sync>(
|
async fn find<T: DeserializeOwned + Unpin + Send + Sync>(
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
use crate::models::report::PartialReport;
|
||||||
|
use crate::models::Report;
|
||||||
|
use crate::{AbstractReport, Result};
|
||||||
|
|
||||||
|
use super::super::MongoDb;
|
||||||
|
|
||||||
|
static COL: &str = "safety_reports";
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl AbstractReport for MongoDb {
|
||||||
|
async fn insert_report(&self, report: &Report) -> Result<()> {
|
||||||
|
self.insert_one(COL, report).await.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_report(&self, id: &str, report: &PartialReport) -> Result<()> {
|
||||||
|
self.update_one_by_id(COL, id, report, vec![], None)
|
||||||
|
.await
|
||||||
|
.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_report(&self, report_id: &str) -> Result<Report> {
|
||||||
|
self.find_one_by_id(COL, report_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_reports(&self) -> Result<Vec<Report>> {
|
||||||
|
self.find(COL, doc! {}).await
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
use crate::models::Snapshot;
|
||||||
|
use crate::{AbstractSnapshot, Result};
|
||||||
|
|
||||||
|
use super::super::MongoDb;
|
||||||
|
|
||||||
|
static COL: &str = "safety_snapshots";
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl AbstractSnapshot for MongoDb {
|
||||||
|
async fn insert_snapshot(&self, snapshot: &Snapshot) -> Result<()> {
|
||||||
|
self.insert_one(COL, snapshot).await.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_snapshot(&self, report_id: &str) -> Result<Snapshot> {
|
||||||
|
self.find_one(
|
||||||
|
COL,
|
||||||
|
doc! {
|
||||||
|
"report_id": report_id
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
use bson::Document;
|
use bson::Document;
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use mongodb::options::{Collation, CollationStrength, FindOneOptions, FindOptions};
|
use mongodb::options::{Collation, CollationStrength, FindOneOptions, FindOptions};
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
|
||||||
use crate::models::user::{FieldsUser, PartialUser, RelationshipStatus, User};
|
use crate::models::user::{FieldsUser, PartialUser, RelationshipStatus, User};
|
||||||
use crate::r#impl::mongo::IntoDocumentPath;
|
use crate::r#impl::mongo::IntoDocumentPath;
|
||||||
@@ -8,16 +9,14 @@ use crate::{AbstractUser, Error, Result};
|
|||||||
|
|
||||||
use super::super::MongoDb;
|
use super::super::MongoDb;
|
||||||
|
|
||||||
lazy_static! {
|
static FIND_USERNAME_OPTIONS: Lazy<FindOneOptions> = Lazy::new(|| FindOneOptions::builder()
|
||||||
static ref FIND_USERNAME_OPTIONS: FindOneOptions = FindOneOptions::builder()
|
.collation(
|
||||||
.collation(
|
Collation::builder()
|
||||||
Collation::builder()
|
.locale("en")
|
||||||
.locale("en")
|
.strength(CollationStrength::Secondary)
|
||||||
.strength(CollationStrength::Secondary)
|
.build()
|
||||||
.build()
|
)
|
||||||
)
|
.build());
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
static COL: &str = "users";
|
static COL: &str = "users";
|
||||||
|
|
||||||
@@ -265,7 +264,7 @@ impl AbstractUser for MongoDb {
|
|||||||
[
|
[
|
||||||
{
|
{
|
||||||
"_id": target_id,
|
"_id": target_id,
|
||||||
"status": format!("{:?}", relationship)
|
"status": format!("{relationship:?}")
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use okapi::openapi3::{SecurityScheme, SecuritySchemeData};
|
use authifier::models::Session;
|
||||||
use rauth::models::Session;
|
use revolt_okapi::openapi3::{SecurityScheme, SecuritySchemeData};
|
||||||
use rocket_okapi::gen::OpenApiGenerator;
|
use revolt_rocket_okapi::gen::OpenApiGenerator;
|
||||||
use rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
|
use revolt_rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
|
||||||
|
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
use rocket::request::{self, FromRequest, Outcome, Request};
|
use rocket::request::{self, FromRequest, Outcome, Request};
|
||||||
@@ -12,7 +12,7 @@ use crate::Database;
|
|||||||
|
|
||||||
#[rocket::async_trait]
|
#[rocket::async_trait]
|
||||||
impl<'r> FromRequest<'r> for User {
|
impl<'r> FromRequest<'r> for User {
|
||||||
type Error = rauth::Error;
|
type Error = authifier::Error;
|
||||||
|
|
||||||
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
||||||
let user: &Option<User> = request
|
let user: &Option<User> = request
|
||||||
@@ -43,7 +43,7 @@ impl<'r> FromRequest<'r> for User {
|
|||||||
if let Some(user) = user {
|
if let Some(user) = user {
|
||||||
Outcome::Success(user.clone())
|
Outcome::Success(user.clone())
|
||||||
} else {
|
} else {
|
||||||
Outcome::Failure((Status::Unauthorized, rauth::Error::InvalidSession))
|
Outcome::Failure((Status::Unauthorized, authifier::Error::InvalidSession))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -53,7 +53,7 @@ impl<'r> OpenApiFromRequest<'r> for User {
|
|||||||
_gen: &mut OpenApiGenerator,
|
_gen: &mut OpenApiGenerator,
|
||||||
_name: String,
|
_name: String,
|
||||||
_required: bool,
|
_required: bool,
|
||||||
) -> rocket_okapi::Result<RequestHeaderInput> {
|
) -> revolt_rocket_okapi::Result<RequestHeaderInput> {
|
||||||
let mut requirements = schemars::Map::new();
|
let mut requirements = schemars::Map::new();
|
||||||
requirements.insert("Session Token".to_owned(), vec![]);
|
requirements.insert("Session Token".to_owned(), vec![]);
|
||||||
|
|
||||||
|
|||||||
@@ -11,14 +11,12 @@ extern crate impl_ops;
|
|||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate optional_struct;
|
extern crate optional_struct;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate lazy_static;
|
|
||||||
#[macro_use]
|
|
||||||
extern crate bitfield;
|
extern crate bitfield;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate bson;
|
extern crate bson;
|
||||||
|
|
||||||
|
pub use authifier;
|
||||||
pub use iso8601_timestamp::Timestamp;
|
pub use iso8601_timestamp::Timestamp;
|
||||||
pub use rauth;
|
|
||||||
pub use redis_kiss;
|
pub use redis_kiss;
|
||||||
|
|
||||||
pub mod events;
|
pub mod events;
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use iso8601_timestamp::Timestamp;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Index access information
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug)]
|
||||||
|
pub struct IndexAccess {
|
||||||
|
/// Operations since timestamp
|
||||||
|
ops: i32,
|
||||||
|
|
||||||
|
/// Timestamp at which data keeping begun
|
||||||
|
since: Timestamp,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collection index
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug)]
|
||||||
|
pub struct Index {
|
||||||
|
/// Index name
|
||||||
|
name: String,
|
||||||
|
|
||||||
|
/// Access information
|
||||||
|
accesses: IndexAccess,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Histogram entry
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug)]
|
||||||
|
pub struct LatencyHistogramEntry {
|
||||||
|
/// Time
|
||||||
|
micros: i64,
|
||||||
|
|
||||||
|
/// Count
|
||||||
|
count: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collection latency stats
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug)]
|
||||||
|
pub struct LatencyStats {
|
||||||
|
/// Total operations
|
||||||
|
ops: i64,
|
||||||
|
|
||||||
|
/// Timestamp at which data keeping begun
|
||||||
|
latency: i64,
|
||||||
|
|
||||||
|
/// Histogram representation of latency data
|
||||||
|
histogram: Vec<LatencyHistogramEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collection storage stats
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct StorageStats {
|
||||||
|
/// Uncompressed data size
|
||||||
|
size: i64,
|
||||||
|
|
||||||
|
/// Data size on disk
|
||||||
|
storage_size: i64,
|
||||||
|
|
||||||
|
/// Total size of all indexes
|
||||||
|
total_index_size: i64,
|
||||||
|
|
||||||
|
/// Sum of storage size and total index size
|
||||||
|
total_size: i64,
|
||||||
|
|
||||||
|
/// Individual index sizes
|
||||||
|
index_sizes: HashMap<String, i64>,
|
||||||
|
|
||||||
|
/// Number of documents in collection
|
||||||
|
count: i64,
|
||||||
|
|
||||||
|
/// Average size of each document
|
||||||
|
avg_obj_size: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Query collection scan stats
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct CollectionScans {
|
||||||
|
/// Number of total collection scans
|
||||||
|
total: i64,
|
||||||
|
|
||||||
|
/// Number of total collection scans not using a tailable cursor
|
||||||
|
non_tailable: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collection query execution stats
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct QueryExecStats {
|
||||||
|
/// Stats regarding collection scans
|
||||||
|
collection_scans: CollectionScans,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collection stats
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct CollectionStats {
|
||||||
|
/// Namespace
|
||||||
|
ns: String,
|
||||||
|
|
||||||
|
/// Local time
|
||||||
|
local_time: Timestamp,
|
||||||
|
|
||||||
|
/// Latency stats
|
||||||
|
latency_stats: HashMap<String, LatencyStats>,
|
||||||
|
|
||||||
|
/// Query exec stats
|
||||||
|
query_exec_stats: QueryExecStats,
|
||||||
|
|
||||||
|
/// Number of documents in collection
|
||||||
|
count: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Server Stats
|
||||||
|
#[derive(Serialize, JsonSchema, Debug)]
|
||||||
|
pub struct Stats {
|
||||||
|
/// Index usage information
|
||||||
|
pub indices: HashMap<String, Vec<Index>>,
|
||||||
|
|
||||||
|
/// Collection stats
|
||||||
|
pub coll_stats: HashMap<String, CollectionStats>,
|
||||||
|
}
|
||||||
@@ -81,7 +81,7 @@ pub struct Masquerade {
|
|||||||
pub name: Option<String>,
|
pub name: Option<String>,
|
||||||
/// Replace the avatar shown on this message (URL to image file)
|
/// Replace the avatar shown on this message (URL to image file)
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
#[validate(length(min = 1, max = 128))]
|
#[validate(length(min = 1, max = 256))]
|
||||||
pub avatar: Option<String>,
|
pub avatar: Option<String>,
|
||||||
/// Replace the display role colour shown on this message
|
/// Replace the display role colour shown on this message
|
||||||
///
|
///
|
||||||
@@ -98,6 +98,8 @@ pub struct Interactions {
|
|||||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||||
pub reactions: Option<IndexSet<String>>,
|
pub reactions: Option<IndexSet<String>>,
|
||||||
/// Whether reactions should be restricted to the given list
|
/// Whether reactions should be restricted to the given list
|
||||||
|
///
|
||||||
|
/// Can only be set to true if reactions list is of at least length 1
|
||||||
#[serde(skip_serializing_if = "if_false", default)]
|
#[serde(skip_serializing_if = "if_false", default)]
|
||||||
pub restrict_reactions: bool,
|
pub restrict_reactions: bool,
|
||||||
}
|
}
|
||||||
@@ -155,10 +157,11 @@ pub struct Message {
|
|||||||
/// # Message Sort
|
/// # Message Sort
|
||||||
///
|
///
|
||||||
/// Sort used for retrieving messages
|
/// Sort used for retrieving messages
|
||||||
#[derive(Serialize, Deserialize, JsonSchema)]
|
#[derive(Serialize, Deserialize, JsonSchema, Debug, Default)]
|
||||||
#[cfg_attr(feature = "rocket_impl", derive(FromFormField))]
|
#[cfg_attr(feature = "rocket_impl", derive(FromFormField))]
|
||||||
pub enum MessageSort {
|
pub enum MessageSort {
|
||||||
/// Sort by the most relevant messages
|
/// Sort by the most relevant messages
|
||||||
|
#[default]
|
||||||
Relevance,
|
Relevance,
|
||||||
/// Sort by the newest messages first
|
/// Sort by the newest messages first
|
||||||
Latest,
|
Latest,
|
||||||
@@ -166,10 +169,54 @@ pub enum MessageSort {
|
|||||||
Oldest,
|
Oldest,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for MessageSort {
|
/// # Message Time Period
|
||||||
fn default() -> MessageSort {
|
///
|
||||||
MessageSort::Relevance
|
/// Filter and sort messages by time
|
||||||
}
|
#[derive(Serialize, Deserialize, JsonSchema)]
|
||||||
|
#[serde(untagged)]
|
||||||
|
pub enum MessageTimePeriod {
|
||||||
|
Relative {
|
||||||
|
/// Message id to search around
|
||||||
|
///
|
||||||
|
/// Specifying 'nearby' ignores 'before', 'after' and 'sort'.
|
||||||
|
/// It will also take half of limit rounded as the limits to each side.
|
||||||
|
/// It also fetches the message ID specified.
|
||||||
|
nearby: String,
|
||||||
|
},
|
||||||
|
Absolute {
|
||||||
|
/// Message id before which messages should be fetched
|
||||||
|
before: Option<String>,
|
||||||
|
/// Message id after which messages should be fetched
|
||||||
|
after: Option<String>,
|
||||||
|
/// Message sort direction
|
||||||
|
sort: Option<MessageSort>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Message Filter
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Default)]
|
||||||
|
pub struct MessageFilter {
|
||||||
|
/// Parent channel ID
|
||||||
|
pub channel: Option<String>,
|
||||||
|
/// Message author ID
|
||||||
|
pub author: Option<String>,
|
||||||
|
/// Search query
|
||||||
|
pub query: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Message Query
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema)]
|
||||||
|
pub struct MessageQuery {
|
||||||
|
/// Maximum number of messages to fetch
|
||||||
|
///
|
||||||
|
/// For fetching nearby messages, this is \`(limit + 1)\`.
|
||||||
|
pub limit: Option<i64>,
|
||||||
|
/// Filter to apply
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub filter: MessageFilter,
|
||||||
|
/// Time period to fetch
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub time_period: MessageTimePeriod,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// # Bulk Message Response
|
/// # Bulk Message Response
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
/// Metadata associated with file
|
/// Metadata associated with file
|
||||||
#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone)]
|
#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, Default)]
|
||||||
#[serde(tag = "type")]
|
#[serde(tag = "type")]
|
||||||
pub enum Metadata {
|
pub enum Metadata {
|
||||||
/// File is just a generic uncategorised file
|
/// File is just a generic uncategorised file
|
||||||
|
#[default]
|
||||||
File,
|
File,
|
||||||
/// File contains textual data and should be displayed as such
|
/// File contains textual data and should be displayed as such
|
||||||
Text,
|
Text,
|
||||||
@@ -16,12 +17,6 @@ pub enum Metadata {
|
|||||||
Audio,
|
Audio,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Metadata {
|
|
||||||
fn default() -> Metadata {
|
|
||||||
Metadata::File
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Representation of a File on Revolt
|
/// Representation of a File on Revolt
|
||||||
/// Generated by Autumn
|
/// Generated by Autumn
|
||||||
#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, Default)]
|
#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, Default)]
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
mod admin {
|
mod admin {
|
||||||
pub mod migrations;
|
pub mod migrations;
|
||||||
pub mod simple;
|
pub mod simple;
|
||||||
|
pub mod stats;
|
||||||
}
|
}
|
||||||
|
|
||||||
mod media {
|
mod media {
|
||||||
@@ -27,9 +28,15 @@ mod users {
|
|||||||
pub mod user_settings;
|
pub mod user_settings;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
mod safety {
|
||||||
|
pub mod report;
|
||||||
|
pub mod snapshot;
|
||||||
|
}
|
||||||
|
|
||||||
pub use admin::*;
|
pub use admin::*;
|
||||||
pub use channels::*;
|
pub use channels::*;
|
||||||
pub use media::*;
|
pub use media::*;
|
||||||
|
pub use safety::*;
|
||||||
pub use servers::*;
|
pub use servers::*;
|
||||||
pub use users::*;
|
pub use users::*;
|
||||||
|
|
||||||
@@ -41,9 +48,11 @@ pub use channel_unread::ChannelUnread;
|
|||||||
pub use emoji::Emoji;
|
pub use emoji::Emoji;
|
||||||
pub use message::Message;
|
pub use message::Message;
|
||||||
pub use migrations::MigrationInfo;
|
pub use migrations::MigrationInfo;
|
||||||
|
pub use report::Report;
|
||||||
pub use server::Server;
|
pub use server::Server;
|
||||||
pub use server_ban::ServerBan;
|
pub use server_ban::ServerBan;
|
||||||
pub use server_member::Member;
|
pub use server_member::Member;
|
||||||
pub use simple::SimpleModel;
|
pub use simple::SimpleModel;
|
||||||
|
pub use snapshot::Snapshot;
|
||||||
pub use user::User;
|
pub use user::User;
|
||||||
pub use user_settings::UserSettings;
|
pub use user_settings::UserSettings;
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Reason for reporting content (message or server)
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone)]
|
||||||
|
pub enum ContentReportReason {
|
||||||
|
/// No reason has been specified
|
||||||
|
NoneSpecified,
|
||||||
|
|
||||||
|
/// Blatantly illegal content
|
||||||
|
Illegal,
|
||||||
|
|
||||||
|
/// Content that promotes harm to others / self
|
||||||
|
PromotesHarm,
|
||||||
|
|
||||||
|
/// Spam or platform abuse
|
||||||
|
SpamAbuse,
|
||||||
|
|
||||||
|
/// Distribution of malware
|
||||||
|
Malware,
|
||||||
|
|
||||||
|
/// Harassment or abuse targeted at another user
|
||||||
|
Harassment,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reason for reporting a user
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone)]
|
||||||
|
pub enum UserReportReason {
|
||||||
|
/// No reason has been specified
|
||||||
|
NoneSpecified,
|
||||||
|
|
||||||
|
/// User is sending spam or otherwise abusing the platform
|
||||||
|
SpamAbuse,
|
||||||
|
|
||||||
|
/// User's profile contains inappropriate content for a general audience
|
||||||
|
InappropriateProfile,
|
||||||
|
|
||||||
|
/// User is impersonating another user
|
||||||
|
Impersonation,
|
||||||
|
|
||||||
|
/// User is evading a ban
|
||||||
|
BanEvasion,
|
||||||
|
|
||||||
|
/// User is not of minimum age to use the platform
|
||||||
|
Underage,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The content being reported
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone)]
|
||||||
|
#[serde(tag = "type")]
|
||||||
|
pub enum ReportedContent {
|
||||||
|
/// Report a message
|
||||||
|
Message {
|
||||||
|
/// ID of the message
|
||||||
|
id: String,
|
||||||
|
/// Reason for reporting message
|
||||||
|
report_reason: ContentReportReason,
|
||||||
|
},
|
||||||
|
/// Report a server
|
||||||
|
Server {
|
||||||
|
/// ID of the server
|
||||||
|
id: String,
|
||||||
|
/// Reason for reporting server
|
||||||
|
report_reason: ContentReportReason,
|
||||||
|
},
|
||||||
|
/// Report a user
|
||||||
|
User {
|
||||||
|
/// ID of the user
|
||||||
|
id: String,
|
||||||
|
/// Reason for reporting a user
|
||||||
|
report_reason: UserReportReason,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Status of the report
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone)]
|
||||||
|
#[serde(tag = "status")]
|
||||||
|
pub enum ReportStatus {
|
||||||
|
/// Report is waiting for triage / action
|
||||||
|
Created {},
|
||||||
|
|
||||||
|
/// Report was rejected
|
||||||
|
Rejected { rejection_reason: String },
|
||||||
|
|
||||||
|
/// Report was actioned and resolved
|
||||||
|
Resolved {},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// User-generated platform moderation report.
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug, OptionalStruct, Clone)]
|
||||||
|
#[optional_derive(Serialize, Deserialize, JsonSchema, Debug, Default, Clone)]
|
||||||
|
#[optional_name = "PartialReport"]
|
||||||
|
#[opt_skip_serializing_none]
|
||||||
|
pub struct Report {
|
||||||
|
/// Unique Id
|
||||||
|
#[serde(rename = "_id")]
|
||||||
|
pub id: String,
|
||||||
|
/// Id of the user creating this report
|
||||||
|
pub author_id: String,
|
||||||
|
/// Reported content
|
||||||
|
pub content: ReportedContent,
|
||||||
|
/// Additional report context
|
||||||
|
pub additional_context: String,
|
||||||
|
/// Status of the report
|
||||||
|
#[opt_passthrough]
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub status: ReportStatus,
|
||||||
|
/// Additional notes included on the report
|
||||||
|
#[serde(default)]
|
||||||
|
pub notes: String,
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::models::{Channel, Message, Server, User};
|
||||||
|
|
||||||
|
/// Enum to map into different models
|
||||||
|
/// that can be saved in a snapshot
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug)]
|
||||||
|
#[serde(tag = "_type")]
|
||||||
|
pub enum SnapshotContent {
|
||||||
|
Message {
|
||||||
|
/// Context before the message
|
||||||
|
#[serde(rename = "_prior_context", default)]
|
||||||
|
prior_context: Vec<Message>,
|
||||||
|
|
||||||
|
/// Context after the message
|
||||||
|
#[serde(rename = "_leading_context", default)]
|
||||||
|
leading_context: Vec<Message>,
|
||||||
|
|
||||||
|
/// Message
|
||||||
|
#[serde(flatten)]
|
||||||
|
message: Message,
|
||||||
|
},
|
||||||
|
Server(Server),
|
||||||
|
User(User),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Snapshot of some content
|
||||||
|
#[derive(Serialize, Deserialize, JsonSchema, Debug)]
|
||||||
|
pub struct Snapshot {
|
||||||
|
/// Unique Id
|
||||||
|
#[serde(rename = "_id")]
|
||||||
|
pub id: String,
|
||||||
|
/// Report parent Id
|
||||||
|
pub report_id: String,
|
||||||
|
/// Snapshot of content
|
||||||
|
pub content: SnapshotContent,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Snapshot of some content with required data to render
|
||||||
|
#[derive(Serialize, JsonSchema, Debug)]
|
||||||
|
pub struct SnapshotWithContext {
|
||||||
|
/// Snapshot itself
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub snapshot: Snapshot,
|
||||||
|
/// Users involved in snapshot
|
||||||
|
#[serde(rename = "_users", skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub users: Vec<User>,
|
||||||
|
/// Channels involved in snapshot
|
||||||
|
#[serde(rename = "_channels", skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub channels: Vec<Channel>,
|
||||||
|
/// Server involved in snapshot
|
||||||
|
#[serde(rename = "_server", skip_serializing_if = "Option::is_none")]
|
||||||
|
pub server: Option<Server>,
|
||||||
|
}
|
||||||
@@ -118,7 +118,7 @@ pub struct Server {
|
|||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub banner: Option<File>,
|
pub banner: Option<File>,
|
||||||
|
|
||||||
/// Enum of server flags
|
/// Bitfield of server flags
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub flags: Option<i32>,
|
pub flags: Option<i32>,
|
||||||
|
|
||||||
|
|||||||
@@ -105,6 +105,8 @@ pub enum Flags {
|
|||||||
Deleted = 2,
|
Deleted = 2,
|
||||||
/// User was banned off the platform
|
/// User was banned off the platform
|
||||||
Banned = 4,
|
Banned = 4,
|
||||||
|
/// User was marked as spam and removed from platform
|
||||||
|
Spam = 8,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Bot information for if the user is a bot
|
/// Bot information for if the user is a bot
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ impl From<i64> for PermissionValue {
|
|||||||
|
|
||||||
impl From<u64> for PermissionValue {
|
impl From<u64> for PermissionValue {
|
||||||
fn from(v: u64) -> Self {
|
fn from(v: u64) -> Self {
|
||||||
Self(v as u64)
|
Self(v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use num_enum::TryFromPrimitive;
|
use num_enum::TryFromPrimitive;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::ops;
|
use once_cell::sync::Lazy;
|
||||||
|
use std::ops::{self, Add};
|
||||||
|
|
||||||
/// Permission value on Revolt
|
/// Permission value on Revolt
|
||||||
///
|
///
|
||||||
@@ -24,7 +25,7 @@ pub enum Permission {
|
|||||||
/// Manage server customisation (includes emoji)
|
/// Manage server customisation (includes emoji)
|
||||||
ManageCustomisation = 1 << 4,
|
ManageCustomisation = 1 << 4,
|
||||||
|
|
||||||
// % 1 bits reserved
|
// % 1 bit reserved
|
||||||
|
|
||||||
// * Member permissions
|
// * Member permissions
|
||||||
/// Kick other members below their ranking
|
/// Kick other members below their ranking
|
||||||
@@ -97,23 +98,18 @@ pub enum Permission {
|
|||||||
impl_op_ex!(+ |a: &Permission, b: &Permission| -> u64 { *a as u64 | *b as u64 });
|
impl_op_ex!(+ |a: &Permission, b: &Permission| -> u64 { *a as u64 | *b as u64 });
|
||||||
impl_op_ex_commutative!(+ |a: &u64, b: &Permission| -> u64 { *a | *b as u64 });
|
impl_op_ex_commutative!(+ |a: &u64, b: &Permission| -> u64 { *a | *b as u64 });
|
||||||
|
|
||||||
lazy_static! {
|
pub static ALLOW_IN_TIMEOUT: Lazy<u64> = Lazy::new(|| Permission::ViewChannel + Permission::ReadMessageHistory);
|
||||||
pub static ref ALLOW_IN_TIMEOUT: u64 = Permission::ViewChannel + Permission::ReadMessageHistory;
|
pub static DEFAULT_PERMISSION_VIEW_ONLY: Lazy<u64> = Lazy::new(|| Permission::ViewChannel + Permission::ReadMessageHistory);
|
||||||
pub static ref DEFAULT_PERMISSION_VIEW_ONLY: u64 =
|
pub static DEFAULT_PERMISSION: Lazy<u64> = Lazy::new(|| DEFAULT_PERMISSION_VIEW_ONLY.add(
|
||||||
Permission::ViewChannel + Permission::ReadMessageHistory;
|
Permission::SendMessage
|
||||||
pub static ref DEFAULT_PERMISSION: u64 = *DEFAULT_PERMISSION_VIEW_ONLY
|
+ Permission::InviteOthers
|
||||||
+ Permission::SendMessage
|
+ Permission::SendEmbeds
|
||||||
+ Permission::InviteOthers
|
+ Permission::UploadFiles
|
||||||
+ Permission::SendEmbeds
|
+ Permission::Connect
|
||||||
+ Permission::UploadFiles
|
+ Permission::Speak));
|
||||||
+ Permission::Connect
|
pub static DEFAULT_PERMISSION_SAVED_MESSAGES: u64 = Permission::GrantAllSafe as u64;
|
||||||
+ Permission::Speak;
|
pub static DEFAULT_PERMISSION_DIRECT_MESSAGE: Lazy<u64> = Lazy::new(|| DEFAULT_PERMISSION.add(Permission::ManageChannel + Permission::React));
|
||||||
pub static ref DEFAULT_PERMISSION_SAVED_MESSAGES: u64 = Permission::GrantAllSafe as u64;
|
pub static DEFAULT_PERMISSION_SERVER: Lazy<u64> = Lazy::new(|| DEFAULT_PERMISSION.add(Permission::React + Permission::ChangeNickname + Permission::ChangeAvatar));
|
||||||
pub static ref DEFAULT_PERMISSION_DIRECT_MESSAGE: u64 =
|
|
||||||
*DEFAULT_PERMISSION + Permission::ManageChannel;
|
|
||||||
pub static ref DEFAULT_PERMISSION_SERVER: u64 =
|
|
||||||
*DEFAULT_PERMISSION + Permission::ChangeNickname + Permission::ChangeAvatar;
|
|
||||||
}
|
|
||||||
|
|
||||||
bitfield! {
|
bitfield! {
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
|
|||||||
@@ -113,7 +113,7 @@ async fn calculate_channel_permission(
|
|||||||
let value: PermissionValue = match channel {
|
let value: PermissionValue = match channel {
|
||||||
Channel::SavedMessages { user, .. } => {
|
Channel::SavedMessages { user, .. } => {
|
||||||
if user == &data.perspective.id {
|
if user == &data.perspective.id {
|
||||||
(*DEFAULT_PERMISSION_SAVED_MESSAGES).into()
|
DEFAULT_PERMISSION_SAVED_MESSAGES.into()
|
||||||
} else {
|
} else {
|
||||||
0_u64.into()
|
0_u64.into()
|
||||||
}
|
}
|
||||||
|
|||||||
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user