├── .github └── workflows │ ├── docker.yml │ ├── release.yml │ └── rust.yml ├── .gitignore ├── .gitpod.yml ├── .releaserc.yml ├── .vscode ├── extensions.json └── settings.json ├── CHANGELOG.md ├── Cargo.lock ├── Cargo.toml ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── assets ├── migrations │ ├── 00001_init.sql │ ├── 00002_attachments.sql │ ├── 00003_attachments.sql │ └── 00004_messages.sql └── templates │ ├── password-reset.html │ └── verify.html └── src ├── config.rs ├── database ├── mod.rs ├── postgres.rs └── redis.rs ├── extractors ├── mod.rs └── validate.rs ├── gateway ├── client │ ├── config.rs │ ├── connection.rs │ ├── handler.rs │ ├── mod.rs │ └── state.rs ├── events │ ├── authenticate.rs │ ├── mod.rs │ └── ping.rs ├── mod.rs ├── payload.rs └── server │ ├── mod.rs │ └── state.rs ├── main.rs ├── middlewares ├── auth.rs ├── captcha.rs ├── compression.rs ├── cors.rs ├── mod.rs └── ratelimit.rs ├── routes ├── auth │ ├── accounts │ │ ├── login.rs │ │ ├── mod.rs │ │ ├── register.rs │ │ └── verify.rs │ ├── mod.rs │ └── sessions │ │ ├── create.rs │ │ ├── delete.rs │ │ ├── fetch.rs │ │ └── mod.rs ├── bots │ ├── create.rs │ ├── delete.rs │ ├── fetch.rs │ └── mod.rs ├── channels │ ├── create.rs │ ├── delete.rs │ ├── edit.rs │ ├── fetch.rs │ ├── kick.rs │ └── mod.rs ├── docs.rs ├── messages │ ├── create.rs │ ├── delete.rs │ ├── edit.rs │ ├── fetch.rs │ └── mod.rs ├── mod.rs └── users │ ├── fetch.rs │ ├── mod.rs │ ├── open_dm.rs │ └── relationships │ ├── add.rs │ ├── block.rs │ ├── delete.rs │ └── mod.rs ├── structures ├── attachment.rs ├── base.rs ├── bot.rs ├── channel.rs ├── message.rs ├── mod.rs ├── session.rs └── user.rs └── utils ├── badges.rs ├── email.rs ├── error.rs ├── mod.rs ├── permissions.rs ├── ref.rs ├── snowflake.rs └── types.rs /.github/workflows/docker.yml: -------------------------------------------------------------------------------- 1 | name: Create and publish a Docker image 2 | on: 3 | push: 4 | branches: 5 | - master 6 | tags: 7 | - "*" 8 | paths-ignore: 9 | - ".github/**" 10 | - "!.github/workflows/docker.yml" 11 | - ".vscode/**" 12 | - ".gitignore" 13 | - ".gitpod.yml" 14 | - "LICENSE" 15 | - "README.md" 16 | workflow_dispatch: 17 | env: 18 | REGISTRY: ghcr.io 19 | IMAGE_NAME: ${{ github.repository }} 20 | 21 | jobs: 22 | build-and-push-image: 23 | runs-on: ubuntu-latest 24 | permissions: 25 | contents: read 26 | packages: write 27 | 28 | steps: 29 | - name: Checkout repository 30 | uses: actions/checkout@v3 31 | 32 | - name: Log in to the Container registry 33 | uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9 34 | with: 35 | registry: ${{ env.REGISTRY }} 36 | username: ${{ github.actor }} 37 | password: ${{ secrets.GITHUB_TOKEN }} 38 | - name: Extract metadata (tags, labels) for Docker 39 | id: meta 40 | uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38 41 | with: 42 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 43 | 44 | - name: Build and push Docker image 45 | uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc 46 | with: 47 | context: . 48 | push: true 49 | tags: ${{ steps.meta.outputs.tags }} 50 | labels: ${{ steps.meta.outputs.labels }} 51 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | push: 4 | branches: [master] 5 | workflow_dispatch: 6 | jobs: 7 | release: 8 | name: Release 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v2 13 | - name: Setup Node.js 14 | uses: actions/setup-node@v3 15 | with: 16 | node-version: "18.x" 17 | - name: Install Semantic release packages 18 | run: npm install -g semantic-release @semantic-release/git @semantic-release/changelog @semantic-release/exec -D 19 | - name: Release 20 | env: 21 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 22 | run: npx semantic-release 23 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | on: 3 | push: 4 | branches: [master, dev, next] 5 | paths-ignore: 6 | - ".github/**" 7 | - "!.github/workflows/rust.yml" 8 | - ".vscode/**" 9 | - ".gitignore" 10 | - ".gitpod.yml" 11 | - "LICENSE" 12 | - "README.md" 13 | pull_request: 14 | branches: [master, dev, next] 15 | paths-ignore: 16 | - ".github/**" 17 | - "!.github/workflows/rust.yml" 18 | - ".vscode/**" 19 | - ".gitignore" 20 | - ".gitpod.yml" 21 | - "LICENSE" 22 | - "README.md" 23 | 24 | env: 25 | CARGO_TERM_COLOR: always 26 | RUST_LOG: debug 27 | 28 | jobs: 29 | run: 30 | runs-on: ubuntu-latest 31 | services: 32 | postgres: 33 | image: postgres:14 34 | env: 35 | POSTGRES_PASSWORD: postgres 36 | options: >- 37 | --health-cmd pg_isready 38 | --health-interval 10s 39 | --health-timeout 5s 40 | --health-retries 5 41 | ports: 42 | - 5432:5432 43 | redis: 44 | image: redis 45 | options: >- 46 | --health-cmd "redis-cli ping" 47 | --health-interval 10s 48 | --health-timeout 5s 49 | --health-retries 5 50 | ports: 51 | - 6379:6379 52 | 53 | steps: 54 | - uses: actions/checkout@v3 55 | - uses: actions-rs/toolchain@v1 56 | with: 57 | profile: minimal 58 | toolchain: stable 59 | - uses: Swatinem/rust-cache@v1 60 | - name: Build 61 | run: cargo build --verbose 62 | - name: Run unit tests 63 | run: cargo test --verbose 64 | - name: Run fmt 65 | run: cargo fmt -- --check 66 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | .env -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | tasks: 2 | - init: make dev 3 | command: make setup && make test 4 | vscode: 5 | extensions: 6 | - streetsidesoftware.code-spell-checker 7 | - tamasfe.even-better-toml 8 | - matklad.rust-analyzer 9 | ports: 10 | - port: 8080 11 | visibility: public 12 | -------------------------------------------------------------------------------- /.releaserc.yml: -------------------------------------------------------------------------------- 1 | branches: ['master'] 2 | plugins: 3 | - '@semantic-release/commit-analyzer' 4 | - '@semantic-release/release-notes-generator' 5 | - '@semantic-release/github' 6 | - - '@semantic-release/git' 7 | - assets: ['CHANGELOG.md'] -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "tamasfe.even-better-toml", 4 | "matklad.rust-analyzer", 5 | "streetsidesoftware.code-spell-checker" 6 | ] 7 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "rust-analyzer.checkOnSave.command": "clippy", 3 | "cSpell.words": [ 4 | "itchat", 5 | "dotenv", 6 | "middlewares", 7 | "ratelimit", 8 | "rbatis" 9 | ] 10 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [1.12.4](https://github.com/itchatapp/api/compare/v1.12.3...v1.12.4) (2022-06-22) 2 | 3 | 4 | ### Bug Fixes 5 | 6 | * serialize permissions/badges ([391e802](https://github.com/itchatapp/api/commit/391e802bb7a668f20052b1c5e071530b043f9bf1)) 7 | 8 | ## [1.12.3](https://github.com/itchatapp/api/compare/v1.12.2...v1.12.3) (2022-06-21) 9 | 10 | 11 | ### Bug Fixes 12 | 13 | * bug fixes ([8556a55](https://github.com/itchatapp/api/commit/8556a55aba5ef9de5183c7cda62d06409adb8313)) 14 | 15 | ## [1.12.2](https://github.com/itchatapp/api/compare/v1.12.1...v1.12.2) (2022-06-20) 16 | 17 | 18 | ### Bug Fixes 19 | 20 | * **user:** refactor #fetch_by_token query ([c7fbee7](https://github.com/itchatapp/api/commit/c7fbee7aa3651dacafb80b17764a539b9095eb10)) 21 | 22 | ## [1.12.1](https://github.com/itchatapp/api/compare/v1.12.0...v1.12.1) (2022-06-20) 23 | 24 | 25 | ### Bug Fixes 26 | 27 | * deserialize permissions/badges ([5040776](https://github.com/itchatapp/api/commit/5040776ccfa85ef6d0536104bace8b241a242452)) 28 | 29 | # [1.12.0](https://github.com/itchatapp/api/compare/v1.11.1...v1.12.0) (2022-06-19) 30 | 31 | 32 | ### Bug Fixes 33 | 34 | * subscribe to server channels ([b594257](https://github.com/itchatapp/api/commit/b5942575ef7c1a20e7684d0c0bfe494e49a40c8a)) 35 | * typo ([067bf2e](https://github.com/itchatapp/api/commit/067bf2e5981c252b9a23da35b4d982a202882236)) 36 | * unsubsribe from deleted objects ([49ac9a9](https://github.com/itchatapp/api/commit/49ac9a91ee2ca0a30da8a9f100d59e76376e1335)) 37 | * Update cached permissions ([417e5c1](https://github.com/itchatapp/api/commit/417e5c196c842a2504eb0647238416139fe39b90)) 38 | 39 | 40 | ### Features 41 | 42 | * Add redis connection ([ec7ec16](https://github.com/itchatapp/api/commit/ec7ec162ba3ba2c62631bd5a49da54a419423240)) 43 | * Add server edit route ([217461a](https://github.com/itchatapp/api/commit/217461a118218c2bbd10f4a0afdfe67f93d4e36e)) 44 | * basic events ([f4a0475](https://github.com/itchatapp/api/commit/f4a047541055482fd39600283eeaae2a0e246678)) 45 | * Cache permissions ([a9aed37](https://github.com/itchatapp/api/commit/a9aed371dbef969b3b7d5033582bb6804402ce0e)) 46 | * Emit server/channel creation events ([6a15173](https://github.com/itchatapp/api/commit/6a151735fa7ca8a5197fcceb7865bb661a6d3a36)) 47 | * handle outcoming data ([3e465d8](https://github.com/itchatapp/api/commit/3e465d8f4f46e0d19efc4a2ad9eda57be02dc398)) 48 | * Payload struct ([361e0d1](https://github.com/itchatapp/api/commit/361e0d12a3a06cc9fa883f7b6ae390ba5d7a2b63)) 49 | * **Permissions:** Add #fetch_cached ([c866874](https://github.com/itchatapp/api/commit/c86687430b1c0b0ccbee6fcd69740f4424e2be35)) 50 | * Publish other events ([18aa87a](https://github.com/itchatapp/api/commit/18aa87aed1a3184a3068ddb90dd86c06bfbad1d2)) 51 | * Send channel deletion events ([7377c0a](https://github.com/itchatapp/api/commit/7377c0a26e1c987ad36dab8a9f47e0522d28aba3)) 52 | * Send message events! ([a77faaa](https://github.com/itchatapp/api/commit/a77faaa53728266e08ad1b2e7c66de3441e24f0c)) 53 | * subsribe to servers & channels ([e7fa71e](https://github.com/itchatapp/api/commit/e7fa71e30a745c3cfa363a57adbcb72e8a0f4d3f)) 54 | 55 | ## [1.11.1](https://github.com/itchatapp/api/compare/v1.11.0...v1.11.1) (2022-06-16) 56 | 57 | 58 | ### Bug Fixes 59 | 60 | * replaced utoipa to opg as openapi generator and much more changes that i can't commit ([04e6657](https://github.com/itchatapp/api/commit/04e66577624fb4f30edae79ae0c9e4010a7b118f)) 61 | 62 | # [1.11.0](https://github.com/itchatapp/api/compare/v1.10.0...v1.11.0) (2022-06-14) 63 | 64 | 65 | ### Features 66 | 67 | * Apply limitation of creation of x ([01d6ab0](https://github.com/itchatapp/api/commit/01d6ab04886d73f483bbce93c8c33ff39c433ddd)) 68 | 69 | # [1.10.0](https://github.com/itchatapp/api/compare/v1.9.1...v1.10.0) (2022-06-14) 70 | 71 | 72 | ### Bug Fixes 73 | 74 | * **cors:** explicitly allowed headers ([778b195](https://github.com/itchatapp/api/commit/778b19541c4a6619f2faea510aab4e59291f69b6)) 75 | * **cors:** use from_str instead of from_static ([1c1ba35](https://github.com/itchatapp/api/commit/1c1ba35156e398507b9220de22b9db5e1b1c92cd)) 76 | * Remove support of HTTPs ([26fba0a](https://github.com/itchatapp/api/commit/26fba0a093d7656c245670f9e347327d1bfdba92)) 77 | 78 | 79 | ### Features 80 | 81 | * **base:** Add #count method ([d0fd90a](https://github.com/itchatapp/api/commit/d0fd90a66874ffd96391b61e139804784115b404)) 82 | * **error:** Provide more information about the occuret error ([a9f9a6b](https://github.com/itchatapp/api/commit/a9f9a6bcdba97011403cfecb8e7cc3389023ceaf)) 83 | * **routes:** limit creation of servers ([349b87d](https://github.com/itchatapp/api/commit/349b87de11d9dc04ea68b3010e5178ff33711fe2)) 84 | 85 | ## [1.9.1](https://github.com/itchatapp/api/compare/v1.9.0...v1.9.1) (2022-06-13) 86 | 87 | 88 | ### Bug Fixes 89 | 90 | * **ssl:** deal with http-1 challenge ([580efd0](https://github.com/itchatapp/api/commit/580efd0459537b220835a80959bdf8fd1b6dda93)) 91 | 92 | # [1.9.0](https://github.com/itchatapp/api/compare/v1.8.4...v1.9.0) (2022-06-13) 93 | 94 | 95 | ### Features 96 | 97 | * HTTPs Support ([e8c25b2](https://github.com/itchatapp/api/commit/e8c25b2d650a73dff4163442b64a44c14c7014db)) 98 | 99 | ## [1.8.4](https://github.com/itchatapp/api/compare/v1.8.3...v1.8.4) (2022-06-12) 100 | 101 | 102 | ### Bug Fixes 103 | 104 | * bug fixes ([b4246b3](https://github.com/itchatapp/api/commit/b4246b3bff7b1d3d72f3a4ab4983b5a01d7766f6)) 105 | 106 | ## [1.8.3](https://github.com/itchatapp/api/compare/v1.8.2...v1.8.3) (2022-06-12) 107 | 108 | 109 | ### Bug Fixes 110 | 111 | * **auth:** Remove swagger endpoint ([57babd5](https://github.com/itchatapp/api/commit/57babd5b008703802682fc4cc4d60a9b8b11d35d)) 112 | * **captcha:** Should return error instead of status code ([6b42a3b](https://github.com/itchatapp/api/commit/6b42a3b44587ec875eaf48a684e573884cef5dd7)) 113 | 114 | ## [1.8.2](https://github.com/itchatapp/api/compare/v1.8.1...v1.8.2) (2022-06-11) 115 | 116 | 117 | ### Bug Fixes 118 | 119 | * **routes:** Increase maiumum requests for auth routes ([92e16f9](https://github.com/itchatapp/api/commit/92e16f9fc2277accd6eb4ce8dcceff8ad43ab3c8)) 120 | 121 | ## [1.8.1](https://github.com/itchatapp/api/compare/v1.8.0...v1.8.1) (2022-06-11) 122 | 123 | 124 | ### Bug Fixes 125 | 126 | * **docker:** Remove old rocket options ([42ba75b](https://github.com/itchatapp/api/commit/42ba75be54ec78f5490e4f419a88b0dd3915442a)) 127 | 128 | # [1.8.0](https://github.com/itchatapp/api/compare/v1.7.0...v1.8.0) (2022-06-11) 129 | 130 | 131 | ### Features 132 | 133 | * **docs:** document session/account routes ([83170a0](https://github.com/itchatapp/api/commit/83170a08adc8281873c31522a8e2527a54ab0e60)) 134 | 135 | # [1.7.0](https://github.com/itchatapp/api/compare/v1.6.0...v1.7.0) (2022-06-11) 136 | 137 | 138 | ### Features 139 | 140 | * Add trust cloudflare option ([51f4205](https://github.com/itchatapp/api/commit/51f4205cd1963dcc7f4e7190b48430dd0e9d8ddc)) 141 | * **docs:** readd openapi & swagger ui ([f098ccd](https://github.com/itchatapp/api/commit/f098ccde44123c42af3602490b02d94849b1f74c)) 142 | 143 | # [1.6.0](https://github.com/itchatapp/api/compare/v1.5.1...v1.6.0) (2022-06-11) 144 | 145 | 146 | ### Features 147 | 148 | * Move on to axum instead of rocket ([9d66431](https://github.com/itchatapp/api/commit/9d664316c54e6a0cebab0d3b58d50d6f210133de)) 149 | 150 | ## [1.5.1](https://github.com/itchatapp/api/compare/v1.5.0...v1.5.1) (2022-06-10) 151 | 152 | 153 | ### Bug Fixes 154 | 155 | * Remove bloated code ([e3ae67a](https://github.com/itchatapp/api/commit/e3ae67ac1a7433179cdad88a0965d5b18455ffc9)) 156 | * Remove unneeded header ([b6045c3](https://github.com/itchatapp/api/commit/b6045c30962f6073909d61c193ddde9c625b1c4e)) 157 | * **route:** mount routes the right way ([15df39e](https://github.com/itchatapp/api/commit/15df39e930c1bd9180b6a78a399edcb02dca5fa4)) 158 | * Save the channel ([c2d4732](https://github.com/itchatapp/api/commit/c2d4732e2886163e2e422814b53f4663a2e9488e)) 159 | 160 | # [1.5.0](https://github.com/itchatapp/api/compare/v1.4.0...v1.5.0) (2022-06-10) 161 | 162 | 163 | ### Features 164 | 165 | * **migrations:** Add account invites table ([c49f33f](https://github.com/itchatapp/api/commit/c49f33f4ad21d600b11aeafa52a5a9633e900b1c)) 166 | 167 | # [1.4.0](https://github.com/itchatapp/api/compare/v1.3.3...v1.4.0) (2022-06-10) 168 | 169 | 170 | ### Features 171 | 172 | * **routes:** Implement inviteation requirement ([fc94366](https://github.com/itchatapp/api/commit/fc94366ca555c98c5005f84df6c64060533e2bce)) 173 | 174 | ## [1.3.3](https://github.com/itchatapp/api/compare/v1.3.2...v1.3.3) (2022-06-10) 175 | 176 | 177 | ### Bug Fixes 178 | 179 | * **docker:** Use stable version of rust ([929caae](https://github.com/itchatapp/api/commit/929caae73cfd49ee3a2844ece283c644716ea8ed)) 180 | * **migration:** syntax error ([5d67550](https://github.com/itchatapp/api/commit/5d6755008d8f6e28faf489ac9752c16d3974f204)) 181 | * use include_str instead of std::fs ([fe1d2ad](https://github.com/itchatapp/api/commit/fe1d2adb5a818b9ffc142ac19fedd249a2e63836)) 182 | 183 | ## [1.3.2](https://github.com/itchatapp/api/compare/v1.3.1...v1.3.2) (2022-06-09) 184 | 185 | 186 | ### Bug Fixes 187 | 188 | * **docker:** Move assets to working dir ([6375162](https://github.com/itchatapp/api/commit/6375162d05d12bb744ddfdfb522756329f89bcb2)) 189 | * Follow clippy guide ([049b085](https://github.com/itchatapp/api/commit/049b085c3f1d28e78063bb3cbaaa8d0d9bce525a)) 190 | 191 | ## [1.3.1](https://github.com/itchatapp/api/compare/v1.3.0...v1.3.1) (2022-06-09) 192 | 193 | 194 | ### Bug Fixes 195 | 196 | * **docker:** Set default port to 8080 ([18b3d5d](https://github.com/itchatapp/api/commit/18b3d5d057d491d2f226792985531da6ac338afe)) 197 | 198 | # [1.3.0](https://github.com/itchatapp/api/compare/v1.2.1...v1.3.0) (2022-06-09) 199 | 200 | 201 | ### Features 202 | 203 | * **docker:** Add Dockerfile ([5fdd09c](https://github.com/itchatapp/api/commit/5fdd09c439b41c843ba1f610ecaf890124f3b70a)) 204 | 205 | ## [1.2.1](https://github.com/itchatapp/api/compare/v1.2.0...v1.2.1) (2022-06-09) 206 | 207 | 208 | ### Bug Fixes 209 | 210 | * Permissions & Badges as integer ([917f327](https://github.com/itchatapp/api/commit/917f327e37c62156eaccdffb505a2d7dec072d04)) 211 | 212 | # [1.2.0](https://github.com/itchatapp/api/compare/v1.1.3...v1.2.0) (2022-06-09) 213 | 214 | 215 | ### Bug Fixes 216 | 217 | * **Auth:** Ignore paths correctly ([236124e](https://github.com/itchatapp/api/commit/236124e93604fafb8bcf17925dea47e98c7aa565)) 218 | * serialize nullable property on structs ([52cbea9](https://github.com/itchatapp/api/commit/52cbea97e5d5730db3cdea08f0006a97d48e765f)) 219 | 220 | 221 | ### Features 222 | 223 | * OpenAPI v3 is here! ([3711d6a](https://github.com/itchatapp/api/commit/3711d6aa1bcb603849b230f04c44d1f54f9888f2)) 224 | 225 | ## [1.1.3](https://github.com/itchatapp/api/compare/v1.1.2...v1.1.3) (2022-06-09) 226 | 227 | 228 | ### Bug Fixes 229 | 230 | * use correct version of rocket_cors ([0328172](https://github.com/itchatapp/api/commit/0328172072156e6d3b63b01345e02ce5e1a8fe4f)) 231 | 232 | ## [1.1.2](https://github.com/itchatapp/api/compare/v1.1.1...v1.1.2) (2022-06-09) 233 | 234 | 235 | ### Bug Fixes 236 | 237 | * use correct version of rocket_cors ([9a46006](https://github.com/itchatapp/api/commit/9a46006929e12d48b6a1caa8ff5e4d901ac18e44)) 238 | 239 | ## [1.1.1](https://github.com/itchatapp/api/compare/v1.1.0...v1.1.1) (2022-06-09) 240 | 241 | 242 | ### Bug Fixes 243 | 244 | * Remove un-needed lifetimes ([39a27e5](https://github.com/itchatapp/api/commit/39a27e5d70b6a04397e572b14a82295bd77755ef)) 245 | 246 | # [1.1.0](https://github.com/itchatapp/api/compare/v1.0.1...v1.1.0) (2022-06-09) 247 | 248 | 249 | ### Features 250 | 251 | * **fairings:** Add cors ([eca952b](https://github.com/itchatapp/api/commit/eca952b3edd1150ba5ebc05aed1c11afd0c9d37d)) 252 | 253 | ## [1.0.1](https://github.com/itchatapp/api/compare/v1.0.0...v1.0.1) (2022-06-09) 254 | 255 | 256 | ### Bug Fixes 257 | 258 | * bumping versions ([ccec7b7](https://github.com/itchatapp/api/commit/ccec7b74243d9f11d6151ee1290c5548642ec115)) 259 | 260 | # 1.0.0 (2022-06-09) 261 | 262 | 263 | ### Bug Fixes 264 | 265 | * **accounts:** remove un-needed pub keywords ([c7062cd](https://github.com/itchatapp/api/commit/c7062cd9f579be27a211a301399dcefd322dee49)) 266 | * all kinds of bugs ([e1ef258](https://github.com/itchatapp/api/commit/e1ef25864a90024f0c4970a6ec50f1b634b93bac)) 267 | * **Channel:** Add missing property ([0387189](https://github.com/itchatapp/api/commit/0387189aba1b9a78ae7eb2fa7f4ed84c91d94080)) 268 | * **Permissions:** #fetch returns Result ([68ca42c](https://github.com/itchatapp/api/commit/68ca42c4715af88ac1e74a4f0660400e1f4b7443)) 269 | * **permissions:** Check group permissions ([006fa04](https://github.com/itchatapp/api/commit/006fa041efc3ae8ff765f1b3de7496b44be4e9dd)) 270 | * **permissions:** No casting needed ([a981e26](https://github.com/itchatapp/api/commit/a981e267b95f5975c451b5eda5a48b9e1adcbc94)) 271 | * **ratelimiter:** Send status code ([749c34c](https://github.com/itchatapp/api/commit/749c34ca4863bfe70226198a28c6ec4b90110f4d)) 272 | * **Ref:** Ensure the fatched role belongs to server ([797838f](https://github.com/itchatapp/api/commit/797838fe061e47b46d3ab2908b040bae9941c824)) 273 | * **Ref:** Make id public ([77feca5](https://github.com/itchatapp/api/commit/77feca508c021a2a6cb59e644e3576b68cfbf590)) 274 | * Remove some bloat here and there ([670062f](https://github.com/itchatapp/api/commit/670062fc1e3fdc1bbb65759182c8f2a745301bd5)) 275 | * **routes:** Mount /channels ([9bf1d29](https://github.com/itchatapp/api/commit/9bf1d2988605fccf5cd5dd0c6712e021e9942f72)) 276 | * separate guards from fairings ([cbd4f1a](https://github.com/itchatapp/api/commit/cbd4f1a09e18f32a2ca69184192c0a0d20b6cd8a)) 277 | * Use "Permissions" instead of u64 ([43c863b](https://github.com/itchatapp/api/commit/43c863b5222a8213aa7acf33c4d1b80814fc1c3a)) 278 | * Use once_cell instead of lazy_static ([3a9f4b7](https://github.com/itchatapp/api/commit/3a9f4b74b64b57c3e41eb7e8187abab1b7ef4070)) 279 | * Use u64 instead i64 ([b9152b4](https://github.com/itchatapp/api/commit/b9152b41a9e8ad444e7a1bcd4fa8fed3f803e9cd)) 280 | * **User#fetch_by_token:** Returns Result ([e3c39ba](https://github.com/itchatapp/api/commit/e3c39ba60c32d55b7a01e8de68cfe95bb0bdeca2)) 281 | * **utils:** Add unknown keyword for items that's not found ([60459cf](https://github.com/itchatapp/api/commit/60459cfa95f17a33111c67684ebedb3a5b42cf9d)) 282 | 283 | 284 | ### Features 285 | 286 | * Add global config ([63e781c](https://github.com/itchatapp/api/commit/63e781c6bfd7524077885a0186bd15cb3c3dda3e)) 287 | * Add user guard ([fee3322](https://github.com/itchatapp/api/commit/fee332240ec9af17652443a61be405323e6bc567)) 288 | * **Badges:** Implement (De)serialize & Default ([ef78aed](https://github.com/itchatapp/api/commit/ef78aede19034408a58172b9a9a6c3a306914f5b)) 289 | * **Base:** Add #delete ([f0eb856](https://github.com/itchatapp/api/commit/f0eb856ef506edcf8cf5321e3504bbf77e721f15)) 290 | * **Base:** Add #update ([db506a8](https://github.com/itchatapp/api/commit/db506a8b88b31e853dd682445c6c663a053648f2)) 291 | * Email verification ([87f35bb](https://github.com/itchatapp/api/commit/87f35bbd38509146d3a57683a04987da3b3ebaf1)) 292 | * **fairings:** Add rate limiter ([c9b9adf](https://github.com/itchatapp/api/commit/c9b9adffdc60be8746fbc7b95d6e874f08dd29e4)) 293 | * **guards:** Add authentication guard ([e7e3238](https://github.com/itchatapp/api/commit/e7e3238eeef3b05b64809d370c501982ff01846b)) 294 | * **guards:** Add captcha ([42abf12](https://github.com/itchatapp/api/commit/42abf12817fbed51e864451fa0add670c6a81951)) 295 | * **guards:** Add Ref guard ([7c93fa6](https://github.com/itchatapp/api/commit/7c93fa60231b7bed043117b630fa6ca01a5a1a22)) 296 | * Implement the rate limiter ([64a8907](https://github.com/itchatapp/api/commit/64a89079d4a842c49f527c12a9d391de6b5f19cb)) 297 | * **Permissions:** Add Manage Invites flag ([4095ca9](https://github.com/itchatapp/api/commit/4095ca9384d8f5068e35505008897d06bd0aad41)) 298 | * **Ref:** Add #invite ([bf756d4](https://github.com/itchatapp/api/commit/bf756d42edea7bdec0b2771b13bba89dd4097200)) 299 | * **Ref:** Add #member ([e78f286](https://github.com/itchatapp/api/commit/e78f2863bcbaa80c20d4326da358aa79e8327668)) 300 | * **Ref:** Add #session ([ce10dae](https://github.com/itchatapp/api/commit/ce10daec9bd1cdb27e2f4a200fb18172a7f9dfd7)) 301 | * **Ref:** Add more methods ([2b47cd7](https://github.com/itchatapp/api/commit/2b47cd7ea421bf4c15ba68403d86d295c0a3d937)) 302 | * **Ref:** Add option to fetch group/dm channel ([aebab44](https://github.com/itchatapp/api/commit/aebab44c7fe45f8e9df6200ec21f85a17803ed27)) 303 | * Replace snowflake module to rbatis built-in plugin ([752f915](https://github.com/itchatapp/api/commit/752f9150368c3f0d04974252776dfad23e4dce99)) 304 | * **routes:** Ability to create invites in servers ([c54aaf4](https://github.com/itchatapp/api/commit/c54aaf44cbf5ebaa8774396cfdb92cca908a1f6f)) 305 | * **routes:** Add accounts ([9b13fe9](https://github.com/itchatapp/api/commit/9b13fe97d70dbd02eb2b13584993c5dedce366fb)) 306 | * **routes:** Add basic server routes ([548f148](https://github.com/itchatapp/api/commit/548f148d2dc2edd07eb6eede1dea0a2f9c4aae6f)) 307 | * **routes:** Add basic user routes ([d2173e6](https://github.com/itchatapp/api/commit/d2173e645e428224f379afd955f3619b5fef4241)) 308 | * **routes:** Add bots routes ([01de32c](https://github.com/itchatapp/api/commit/01de32c50b790395970573b8064295e51e789e47)) 309 | * **routes:** Add DM/Group channel routes ([f932783](https://github.com/itchatapp/api/commit/f932783dbfc34cf2501640a7bb3cec2e94256291)) 310 | * **routes:** Add messages route ([c7cf19a](https://github.com/itchatapp/api/commit/c7cf19a6c89893fa04bae62d3cd249d35d272715)) 311 | * **routes:** Add server invite routes ([e203d92](https://github.com/itchatapp/api/commit/e203d92fd1350257c17abc8927f2b0cf095f6b27)) 312 | * **routes:** Add server members routes ([9b74e22](https://github.com/itchatapp/api/commit/9b74e22e0b3f8e09055f781613661f4c58daeb79)) 313 | * **routes:** Add server members routes ([b4d7e87](https://github.com/itchatapp/api/commit/b4d7e870c4fc4a71ecce939dc9c47cd9bb8b3c97)) 314 | * **routes:** Add server roles routes ([0de6d43](https://github.com/itchatapp/api/commit/0de6d43a5bfe0991c6f791e9e17b72b2083081ba)) 315 | * **routes:** Add sessions ([f023a3f](https://github.com/itchatapp/api/commit/f023a3f48e907b042a33b288e84117fcdb0de6fa)) 316 | * **routes:** Completely finish servers routes ([fb13767](https://github.com/itchatapp/api/commit/fb13767ca31b1853f71ef3d8a6a6a5df125c85c1)) 317 | * **routes:** Implement Invite routes ([c01b6e8](https://github.com/itchatapp/api/commit/c01b6e80319795ecc82df98dd5cb62f9884a1783)) 318 | * **routes:** mount everything ([4a9fd8e](https://github.com/itchatapp/api/commit/4a9fd8ec2dc6c6be5ca51e2618aa3e67bb125be9)) 319 | * **User:** Add #is_in_server helper ([736c561](https://github.com/itchatapp/api/commit/736c561b0ec44c836631c1ac5571b96ba039f01b)) 320 | * **util:** Implement migration system ([126ad38](https://github.com/itchatapp/api/commit/126ad387a318b0d0a5cbb51158ddc3b9592eadb7)) 321 | * **util:** Implement Permissions ([036ca89](https://github.com/itchatapp/api/commit/036ca89ce714ee823e2b266bbb3145c84d9a3e41)) 322 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "api" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | # Async 8 | tokio = { version = "1.19.2", features = ["full"] } 9 | async-trait = "0.1.56" 10 | 11 | 12 | # Database 13 | sqlx = { version = "0.6.3", features = [ 14 | "runtime-tokio-rustls", 15 | "postgres", 16 | "json", 17 | "time", 18 | "chrono", 19 | "uuid" 20 | ] } 21 | fred = { version = "5.1.0", features = ["subscriber-client", "serde-json"] } 22 | 23 | # HTTP 24 | axum = { version = "0.6.0-rc.4", features = ["ws", "headers"] } 25 | reqwest = { version = "0.11", features = ["json"] } 26 | 27 | # Serde 28 | serde = { version = "1", features = ["derive"] } 29 | serde_json = "1.0.81" 30 | serde_repr = "0.1.8" 31 | serde_with = { version = "1.14.0", features = ["json"] } 32 | uuid = { version = "1.0", features = ["serde", "v4"] } 33 | 34 | # Logging 35 | log = "0.4.17" 36 | env_logger = "0.9.0" 37 | 38 | 39 | # Security 40 | tower-http = { version = "0.3.0", features = ["cors", "compression-full"] } 41 | rust-argon2 = "1.0.0" 42 | governor = "0.4.2" 43 | validator = { version = "0.15", features = ["derive"] } 44 | 45 | # Utility 46 | dotenv = "0.15.0" 47 | lazy_static = "1.4.0" 48 | once_cell = "1.12.0" 49 | nanoid = "0.4.0" 50 | bitflags = "1.3.2" 51 | regex = "1.5.6" 52 | quick-error = "2.0.1" 53 | futures = "0.3" 54 | ctor = "0.1.22" 55 | rs-snowflake = "0.6.0" 56 | chrono = { version = "0.4.19", features = ["serde"] } 57 | inter-struct = "0.2.0" 58 | dashmap = "5.4.0" 59 | rmp-serde = "1.1.1" 60 | lazy-regex = "2.3.0" 61 | 62 | # Docs 63 | opg = { git = "https://github.com/abdulrahman1s/opg", rev = "0a9f7f8c791d522fc9bd25bda8e63cb4f270ecc8", features = ["chrono"] } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM rust:1-slim AS builder 2 | USER 0:0 3 | WORKDIR /home/rust/src 4 | 5 | RUN USER=root cargo new --bin api 6 | WORKDIR /home/rust/src/api 7 | RUN apt-get update && apt-get install -y libssl-dev pkg-config 8 | 9 | COPY Cargo.toml Cargo.lock ./ 10 | COPY assets ./assets 11 | COPY src ./src 12 | RUN cargo install --locked --path . 13 | 14 | FROM debian:bullseye-slim 15 | RUN apt-get update && apt-get install -y ca-certificates 16 | 17 | COPY --from=builder /usr/local/cargo/bin/api ./ 18 | 19 | EXPOSE 8080 20 | 21 | CMD ["./api"] 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 2022 Abdulrahman Salah 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | start: 2 | cargo run -r 3 | 4 | dev: 5 | cargo run 6 | 7 | test: 8 | cargo test -- 9 | 10 | setup: 11 | docker run -e POSTGRES_PASSWORD=postgres -p 5432:5432 -d postgres 12 | docker run -p 6379:6379 -d eqalpha/keydb -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/itchatapp/api) 2 | 3 | # Zaun API 4 | Core Backend API 5 | 6 | ### 🔗 Resources 7 | - [Docs](https://docs.zaun.world) 8 | - [Javascript Client](https://github.com/zaunchat/zaun.js) 9 | - [Python Client](https://github.com/zaunchat/zaun.py) 10 | 11 | ### 📝 License 12 | Refer to the [LICENSE](LICENSE) file. 13 | -------------------------------------------------------------------------------- /assets/migrations/00001_init.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS users ( 2 | id BIGINT PRIMARY KEY, 3 | username VARCHAR(32) NOT NULL, 4 | password TEXT NOT NULL, 5 | email VARCHAR(255) NOT NULL UNIQUE, 6 | avatar VARCHAR(64), 7 | badges BIGINT NOT NULL DEFAULT 0, 8 | presence JSONB NOT NULL DEFAULT '{}'::jsonb, 9 | relations JSONB NOT NULL DEFAULT '{}'::jsonb, 10 | verified BOOLEAN DEFAULT FALSE 11 | ); 12 | 13 | CREATE TABLE IF NOT EXISTS sessions ( 14 | id BIGINT PRIMARY KEY, 15 | token VARCHAR(64) NOT NULL, 16 | user_id BIGINT NOT NULL, 17 | info JSONB DEFAULT '{}'::jsonb, 18 | FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE 19 | ); 20 | 21 | 22 | CREATE TABLE IF NOT EXISTS channels ( 23 | id BIGINT PRIMARY KEY, 24 | type INTEGER NOT NULL, 25 | name VARCHAR(50), 26 | permissions BIGINT, 27 | recipients BIGINT[], 28 | owner_id BIGINT, 29 | FOREIGN KEY (owner_id) REFERENCES users(id) ON DELETE CASCADE 30 | ); 31 | 32 | 33 | 34 | CREATE TABLE IF NOT EXISTS messages ( 35 | id BIGINT PRIMARY KEY, 36 | created_at TIMESTAMP DEFAULT current_timestamp, 37 | edited_at TIMESTAMP, 38 | content VARCHAR(2000), 39 | channel_id BIGINT NOT NULL, 40 | author_id BIGINT NOT NULL, 41 | FOREIGN KEY (channel_id) REFERENCES channels(id) ON DELETE CASCADE, 42 | FOREIGN KEY (author_id) REFERENCES users(id) ON DELETE CASCADE 43 | ); 44 | 45 | CREATE TABLE IF NOT EXISTS bots ( 46 | id BIGINT PRIMARY KEY, 47 | username VARCHAR(32) NOT NULL, 48 | owner_id BIGINT NOT NULL, 49 | avatar VARCHAR(64), 50 | presence JSONB, 51 | verified BOOLEAN DEFAULT FALSE, 52 | FOREIGN KEY (owner_id) REFERENCES users(id) ON DELETE CASCADE 53 | ); 54 | 55 | CREATE TABLE IF NOT EXISTS account_invites ( 56 | code TEXT NOT NULL, 57 | used BOOLEAN DEFAULT FALSE, 58 | taken_by BIGINT 59 | ); 60 | 61 | CREATE TABLE IF NOT EXISTS attachments ( 62 | id BIGINT PRIMARY KEY, 63 | uploader_id BIGINT NOT NULL, 64 | name TEXT NOT NULL, 65 | meta JSONB NOT NULL DEFAULT '{}'::jsonb, 66 | tag TEXT, 67 | size INTEGER NOT NULL, 68 | FOREIGN KEY (uploader_id) REFERENCES users(id) ON DELETE CASCADE 69 | ); 70 | -------------------------------------------------------------------------------- /assets/migrations/00002_attachments.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE attachments 2 | DROP COLUMN uploader_id, 3 | ADD COLUMN content_type VARCHAR(64) NOT NULL; -------------------------------------------------------------------------------- /assets/migrations/00003_attachments.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE attachments 2 | DROP COLUMN meta, 3 | DROP COLUMN tag, 4 | DROP COLUMN name, 5 | ADD COLUMN filename VARCHAR(64) NOT NULL DEFAULT 'Unknown', 6 | ADD COLUMN height INTEGER, 7 | ADD COLUMN width INTEGER; -------------------------------------------------------------------------------- /assets/migrations/00004_messages.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE attachments 2 | ADD COLUMN deleted BOOLEAN NOT NULL DEFAULT FALSE; 3 | 4 | ALTER TABLE messages 5 | ADD COLUMN attachments JSONB NOT NULL DEFAULT '[]'::JSONB; -------------------------------------------------------------------------------- /assets/templates/password-reset.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zaunchat/api/a92248049032b9b822b06e8b9ad11d904d7137ab/assets/templates/password-reset.html -------------------------------------------------------------------------------- /assets/templates/verify.html: -------------------------------------------------------------------------------- 1 | Hi there, 2 | 3 | Your email address %%EMAIL%% has been added to your ItChat account. But wait, we're not done yet... 4 | To finish verifying your email address and securing your account, click the button below. 5 | 6 | https://api.itchat.world/auth/verify/?user_id=%%USER_ID%%&code=%%CODE%% -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | macro_rules! config { 2 | ($($name:ident $t:tt $($default:expr)?),+) => { 3 | lazy_static! { 4 | $( 5 | pub static ref $name: $t = std::env::var(stringify!($name)) 6 | .unwrap_or_else(|_| { 7 | $( if true { return $default.to_string(); } )? 8 | panic!("{} is required", stringify!($name)); 9 | }) 10 | .parse::<$t>() 11 | .expect("Failed to parse value"); 12 | )+ 13 | } 14 | }; 15 | } 16 | 17 | config! { 18 | // Networking 19 | PORT u16 8080, 20 | TRUST_CLOUDFLARE bool false, 21 | 22 | // Database 23 | DATABASE_URI String "postgres://postgres:postgres@localhost", 24 | REDIS_URI String "redis://localhost:6379", 25 | REDIS_POOL_SIZE usize 100, 26 | DATABASE_POOL_SIZE u32 100, 27 | 28 | // Captcha 29 | CAPTCHA_ENABLED bool false, 30 | CAPTCHA_TOKEN String, 31 | CAPTCHA_KEY String, 32 | 33 | // Email 34 | SENDINBLUE_API_KEY String, 35 | EMAIL_VERIFICATION bool false, 36 | REQUIRE_INVITE_TO_REGISTER bool false, 37 | 38 | // User related 39 | MAX_FRIENDS u64 1000, 40 | MAX_BLOCKED u64 1000, 41 | MAX_FRIEND_REQUESTS u64 100, 42 | 43 | // Group related 44 | MAX_GROUPS u64 100, 45 | MAX_GROUP_MEMBERS u64 50 46 | } 47 | -------------------------------------------------------------------------------- /src/database/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod postgres; 2 | pub mod redis; 3 | pub use postgres::pool; 4 | -------------------------------------------------------------------------------- /src/database/postgres.rs: -------------------------------------------------------------------------------- 1 | use crate::config::*; 2 | use once_cell::sync::OnceCell; 3 | use sqlx::{postgres::PgPoolOptions, Pool, Postgres}; 4 | 5 | static POOL: OnceCell> = OnceCell::new(); 6 | 7 | pub async fn connect() { 8 | let pool = PgPoolOptions::new() 9 | .max_connections(*DATABASE_POOL_SIZE) 10 | .connect(&DATABASE_URI) 11 | .await 12 | .expect("Couldn't connect to database"); 13 | 14 | log::debug!("Run database migration"); 15 | 16 | sqlx::migrate!("assets/migrations") 17 | .run(&pool) 18 | .await 19 | .expect("Failed to run the migration"); 20 | 21 | POOL.set(pool).unwrap(); 22 | } 23 | 24 | pub fn pool() -> &'static Pool { 25 | POOL.get().unwrap() 26 | } 27 | -------------------------------------------------------------------------------- /src/database/redis.rs: -------------------------------------------------------------------------------- 1 | use crate::config::{REDIS_POOL_SIZE, REDIS_URI}; 2 | pub use fred::prelude::*; 3 | use fred::{bytes_utils::Str, clients::SubscriberClient, pool::RedisPool}; 4 | use once_cell::sync::Lazy; 5 | use rmp_serde as MsgPack; 6 | use serde::Serialize; 7 | 8 | pub static REDIS: Lazy = Lazy::new(|| { 9 | let config = RedisConfig::from_url(&REDIS_URI).expect("Invalid redis url"); 10 | RedisPool::new(config, *REDIS_POOL_SIZE).expect("Failed initialize redis pool") 11 | }); 12 | 13 | pub async fn connect() { 14 | let client = &REDIS; 15 | let policy = ReconnectPolicy::default(); 16 | let _ = client.connect(Some(policy)); 17 | client 18 | .wait_for_connect() 19 | .await 20 | .expect("Failed to connect to redis"); 21 | } 22 | 23 | pub async fn pubsub() -> SubscriberClient { 24 | let config = RedisConfig::from_url(&REDIS_URI).unwrap(); 25 | let client = SubscriberClient::new(config); 26 | 27 | let policy = ReconnectPolicy::default(); 28 | client.connect(Some(policy)); 29 | client.wait_for_connect().await.unwrap(); 30 | 31 | client 32 | } 33 | 34 | pub async fn publish, V: Serialize>(channel: K, data: V) { 35 | let payload = match MsgPack::encode::to_vec_named(&data) { 36 | Ok(p) => p, 37 | Err(e) => { 38 | log::error!("Failed to encode payload: {e:?}"); 39 | return; 40 | } 41 | }; 42 | 43 | if let Err(error) = REDIS.publish::<(), _, _>(channel, payload.as_slice()).await { 44 | log::error!("Publish error: {error:?}"); 45 | } 46 | } 47 | 48 | #[cfg(test)] 49 | mod tests { 50 | use super::*; 51 | use crate::tests::run; 52 | use futures::StreamExt; 53 | 54 | #[test] 55 | fn simple() -> Result<(), RedisError> { 56 | run(async { 57 | REDIS.set("hello", "world", None, None, false).await?; 58 | 59 | let value: String = REDIS.get("hello").await?; 60 | 61 | assert_eq!(value, "world"); 62 | 63 | Ok(()) 64 | }) 65 | } 66 | 67 | #[test] 68 | fn subscriber() -> Result<(), RedisError> { 69 | run(async { 70 | let subscriber = pubsub().await; 71 | 72 | subscriber.subscribe("test").await?; 73 | 74 | let task = tokio::spawn(async move { 75 | if let Some((channel, message)) = subscriber.on_message().next().await { 76 | log::debug!("Recv {:?} on channel {}", message, channel); 77 | } 78 | }); 79 | 80 | publish("test", "hi").await; 81 | 82 | task.await?; 83 | 84 | REDIS.set("hello", "world", None, None, false).await?; 85 | 86 | let value: String = REDIS.get("hello").await?; 87 | 88 | assert_eq!(value, "world"); 89 | 90 | Ok(()) 91 | }) 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/extractors/mod.rs: -------------------------------------------------------------------------------- 1 | mod validate; 2 | pub use axum::extract::{Extension, Json, Path, Query}; 3 | pub use validate::*; 4 | -------------------------------------------------------------------------------- /src/extractors/validate.rs: -------------------------------------------------------------------------------- 1 | use crate::utils::error::Error; 2 | use axum::{ 3 | extract::{FromRequest, Json}, 4 | http::Request, 5 | response::{IntoResponse, Response}, 6 | }; 7 | use serde::de::DeserializeOwned; 8 | use validator::Validate; 9 | 10 | #[derive(Debug, Clone, Copy, Default)] 11 | pub struct ValidatedJson(pub T); 12 | 13 | #[async_trait] 14 | impl FromRequest for ValidatedJson 15 | where 16 | T: DeserializeOwned + Validate, 17 | B: Send + 'static, 18 | S: Send + Sync, 19 | Json: FromRequest, 20 | { 21 | type Rejection = Response; 22 | 23 | async fn from_request(req: Request, state: &S) -> Result { 24 | let data = Json::from_request(req, state) 25 | .await 26 | .map_err(IntoResponse::into_response)?; 27 | 28 | data.validate() 29 | .map_err(|_| IntoResponse::into_response(Error::InvalidBody))?; 30 | 31 | Ok(Self(data.0)) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/gateway/client/config.rs: -------------------------------------------------------------------------------- 1 | use crate::gateway::{ClientPayload, Payload}; 2 | use axum::extract::ws; 3 | use rmp_serde as MsgPack; 4 | use serde::Deserialize; 5 | use serde_json as JSON; 6 | 7 | #[derive(Debug, Deserialize)] 8 | #[serde(rename_all = "lowercase")] 9 | pub enum EncodingFormat { 10 | Json, 11 | MsgPack, 12 | } 13 | 14 | impl Default for EncodingFormat { 15 | fn default() -> Self { 16 | Self::Json 17 | } 18 | } 19 | 20 | #[derive(Debug, Deserialize)] 21 | pub struct SocketClientConfig { 22 | #[serde(default)] 23 | pub format: EncodingFormat, 24 | } 25 | 26 | impl Default for SocketClientConfig { 27 | fn default() -> Self { 28 | Self { 29 | format: EncodingFormat::Json, 30 | } 31 | } 32 | } 33 | 34 | impl SocketClientConfig { 35 | pub fn encode(&self, payload: Payload) -> ws::Message { 36 | match self.format { 37 | EncodingFormat::Json => { 38 | ws::Message::Text(JSON::to_string(&payload).expect("Cannot serialise data (json)")) 39 | } 40 | EncodingFormat::MsgPack => ws::Message::Binary( 41 | MsgPack::encode::to_vec_named(&payload).expect("Cannot serialise data (msgpack)"), 42 | ), 43 | } 44 | } 45 | 46 | pub fn decode(&self, payload: ws::Message) -> Option { 47 | match payload { 48 | ws::Message::Text(content) => match self.format { 49 | EncodingFormat::Json => JSON::from_str(&content).ok(), 50 | _ => None, 51 | }, 52 | ws::Message::Binary(buf) => match self.format { 53 | EncodingFormat::MsgPack => MsgPack::from_slice(&buf).ok(), 54 | _ => None, 55 | }, 56 | _ => None, 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/gateway/client/connection.rs: -------------------------------------------------------------------------------- 1 | use axum::extract::ws::{Message, WebSocket}; 2 | use futures::SinkExt; 3 | use std::sync::Arc; 4 | use tokio::sync::Mutex; 5 | 6 | use futures::stream::SplitSink; 7 | 8 | pub struct Sender(Arc>>); 9 | 10 | impl Clone for Sender { 11 | fn clone(&self) -> Self { 12 | Self(self.0.clone()) 13 | } 14 | } 15 | 16 | impl Sender { 17 | pub fn new(stream: SplitSink) -> Self { 18 | Self(Arc::new(Mutex::new(stream))) 19 | } 20 | 21 | pub async fn send(&self, message: Message) -> Result<(), axum::Error> { 22 | self.0.lock().await.send(message).await 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/gateway/client/handler.rs: -------------------------------------------------------------------------------- 1 | use crate::gateway::*; 2 | use crate::utils::{bits, Error, Permissions}; 3 | use fred::interfaces::PubsubInterface; 4 | use futures::StreamExt; 5 | use rmp_serde as MsgPack; 6 | use std::sync::Arc; 7 | 8 | pub async fn handle_incoming(client: Arc, conn: Sender, receiver: &mut Receiver) { 9 | let mut errors = 0u8; 10 | 11 | while let Some(Ok(msg)) = receiver.next().await { 12 | let Some(payload) = client.config.decode(msg) else { 13 | log::debug!("Socket sent an invalid body"); 14 | continue; 15 | }; 16 | 17 | let res = match &payload { 18 | ClientPayload::Ping => events::ping::run(client.clone(), conn.clone()).await, 19 | // ClientPayload::Authenticate 20 | _ => { 21 | log::warn!("Unhandled event"); 22 | Ok(()) 23 | } 24 | }; 25 | 26 | if let Err(err) = res { 27 | log::error!("Socket error: {err}"); 28 | 29 | errors += 1; 30 | 31 | if errors == 5 { 32 | break; 33 | } 34 | } 35 | } 36 | } 37 | 38 | pub async fn handle_outgoing(client: Arc) -> Result<(), Error> { 39 | while let Some((target_id, payload)) = client.subscriptions.on_message().next().await { 40 | let Ok(target_id) = target_id.clone().try_into() else { 41 | log::warn!("Received non-parsable target id: {target_id:?}"); 42 | continue; 43 | }; 44 | 45 | let Some(payload) = payload.as_bytes().and_then(|buf| MsgPack::decode::from_slice(buf).ok()) else { 46 | log::warn!("Received non-bytes redis value: {payload:?}"); 47 | continue; 48 | }; 49 | 50 | log::debug!("Processing payload: {payload:?}"); 51 | 52 | let user_id = client.state.user_id; 53 | 54 | let permissions = &client.state.permissions; 55 | let p = permissions 56 | .get(&target_id) 57 | .map(|x| *x.value()) 58 | .unwrap_or(Permissions::all()); 59 | 60 | match &payload { 61 | Payload::MessageCreate(_) | Payload::MessageUpdate(_) | Payload::MessageDelete(_) => { 62 | if !p.contains(bits![VIEW_CHANNEL]) { 63 | continue; 64 | } 65 | } 66 | 67 | Payload::ChannelDelete(Empty::Default { id }) => { 68 | client.subscriptions.unsubscribe(id.to_string()).await.ok(); 69 | } 70 | 71 | Payload::ChannelUpdate(channel) => { 72 | let p = Permissions::fetch_cached(&*client.state.user.lock().await, channel.into()) 73 | .await?; 74 | 75 | permissions.insert(channel.id, p); 76 | } 77 | 78 | Payload::ChannelCreate(channel) => { 79 | client 80 | .subscriptions 81 | .subscribe(channel.id.to_string()) 82 | .await 83 | .ok(); 84 | } 85 | Payload::UserUpdate(u) => { 86 | // Newly friend, blocked, request 87 | if u.id != target_id && u.id != user_id { 88 | client.subscriptions.subscribe(u.id.to_string()).await.ok(); 89 | } 90 | } 91 | _ => {} 92 | } 93 | 94 | if let Err(err) = client.broadcast(payload).await { 95 | log::warn!("Couldn't send payload: {err:?}"); 96 | break; // probably the client disconnected 97 | } 98 | } 99 | 100 | Ok(()) 101 | } 102 | -------------------------------------------------------------------------------- /src/gateway/client/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod config; 2 | pub mod connection; 3 | pub mod handler; 4 | mod state; 5 | use crate::gateway::Payload; 6 | use crate::structures::User; 7 | use config::*; 8 | use connection::Sender; 9 | use dashmap::DashMap; 10 | use fred::clients::SubscriberClient; 11 | use state::SocketClientState; 12 | 13 | pub struct SocketClient { 14 | pub state: SocketClientState, 15 | pub config: SocketClientConfig, 16 | pub connections: DashMap, 17 | pub subscriptions: SubscriberClient, 18 | } 19 | 20 | impl SocketClient { 21 | pub fn new(user: User, config: SocketClientConfig, subscriptions: SubscriberClient) -> Self { 22 | Self { 23 | state: SocketClientState::new(user), 24 | connections: DashMap::new(), 25 | subscriptions, 26 | config, 27 | } 28 | } 29 | 30 | pub async fn broadcast(&self, payload: Payload) -> Result<(), axum::Error> { 31 | let payload = self.config.encode(payload); 32 | 33 | log::debug!("Payload encoded: {payload:?}"); 34 | 35 | log::debug!("Connections found: {}", self.connections.len()); 36 | 37 | for conn in &self.connections { 38 | log::debug!("Sending payload bytes..."); 39 | conn.value().send(payload.clone()).await?; 40 | log::debug!("Sent payload to connection node"); 41 | } 42 | 43 | Ok(()) 44 | } 45 | 46 | pub async fn send(&self, connection: &Sender, payload: Payload) -> Result<(), axum::Error> { 47 | connection.send(self.config.encode(payload)).await 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/gateway/client/state.rs: -------------------------------------------------------------------------------- 1 | use crate::structures::User; 2 | use crate::utils::Permissions; 3 | use crate::utils::Snowflake; 4 | use dashmap::DashMap; 5 | use tokio::sync::Mutex; 6 | 7 | pub struct SocketClientState { 8 | pub permissions: DashMap, 9 | pub user: Mutex, 10 | pub user_id: Snowflake, 11 | } 12 | 13 | impl SocketClientState { 14 | pub fn new(user: User) -> Self { 15 | Self { 16 | permissions: DashMap::new(), 17 | user_id: user.id, 18 | user: Mutex::new(user), 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/gateway/events/authenticate.rs: -------------------------------------------------------------------------------- 1 | use crate::gateway::{Payload, Sender, SocketClient}; 2 | use crate::utils::{Error, Permissions, Snowflake}; 3 | use fred::interfaces::PubsubInterface; 4 | use std::sync::Arc; 5 | 6 | pub async fn run(client: Arc, conn: Sender) -> Result<(), Error> { 7 | client.send(&conn, Payload::Authenticated).await?; 8 | 9 | let user = client.state.user.lock().await.clone(); 10 | let permissions = &client.state.permissions; 11 | let mut subscriptions: Vec = vec![user.id]; 12 | let channels = user.fetch_channels().await?; 13 | let mut additional_ids = channels 14 | .iter() 15 | .flat_map(|c| c.recipients.clone().unwrap_or_default().to_vec()) 16 | .collect::>(); 17 | 18 | let users = user 19 | .fetch_relations(&mut additional_ids) 20 | .await? 21 | .into_iter() 22 | .map(|mut u| { 23 | subscriptions.push(user.id); 24 | u.relationship = user.relations.0.get(&u.id).copied(); 25 | u 26 | }) 27 | .collect::>(); 28 | 29 | for channel in &channels { 30 | subscriptions.push(channel.id); 31 | permissions.insert( 32 | channel.id, 33 | Permissions::fetch_cached(&user, channel.into()).await?, 34 | ); 35 | } 36 | 37 | for id in subscriptions { 38 | client.subscriptions.subscribe(id.to_string()).await.ok(); 39 | } 40 | 41 | client 42 | .send( 43 | &conn, 44 | Payload::Ready { 45 | user, 46 | users, 47 | channels, 48 | }, 49 | ) 50 | .await?; 51 | 52 | Ok(()) 53 | } 54 | -------------------------------------------------------------------------------- /src/gateway/events/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod authenticate; 2 | pub mod ping; 3 | -------------------------------------------------------------------------------- /src/gateway/events/ping.rs: -------------------------------------------------------------------------------- 1 | use crate::gateway::*; 2 | use crate::utils::Error; 3 | use std::sync::Arc; 4 | 5 | pub async fn run(client: Arc, conn: Sender) -> Result<(), Error> { 6 | client.send(&conn, Payload::Pong).await?; 7 | Ok(()) 8 | } 9 | -------------------------------------------------------------------------------- /src/gateway/mod.rs: -------------------------------------------------------------------------------- 1 | mod client; 2 | mod events; 3 | mod payload; 4 | mod server; 5 | 6 | use axum::extract::ws::WebSocket; 7 | use futures::stream::SplitStream; 8 | 9 | pub type Receiver = SplitStream; 10 | pub use client::{config::*, connection::Sender, SocketClient}; 11 | pub use payload::*; 12 | pub use server::upgrade; 13 | -------------------------------------------------------------------------------- /src/gateway/payload.rs: -------------------------------------------------------------------------------- 1 | use crate::database::redis::publish; 2 | use crate::structures::*; 3 | use crate::utils::Snowflake; 4 | use serde::{Deserialize, Serialize}; 5 | 6 | #[serde_as] 7 | #[derive(Serialize, Deserialize, Clone, Debug)] 8 | #[serde(untagged)] 9 | pub enum Empty { 10 | Default { id: Snowflake }, 11 | } 12 | 13 | impl From for Empty { 14 | fn from(id: Snowflake) -> Empty { 15 | Empty::Default { id } 16 | } 17 | } 18 | 19 | #[derive(Serialize, Deserialize, Clone, Debug)] 20 | #[serde(tag = "op", content = "d")] 21 | pub enum Payload { 22 | Pong, 23 | Authenticated, 24 | Ready { 25 | user: User, 26 | users: Vec, 27 | channels: Vec, 28 | }, 29 | ChannelCreate(Channel), 30 | ChannelDelete(Empty), 31 | ChannelUpdate(Channel), 32 | MessageCreate(Message), 33 | MessageDelete(Empty), 34 | MessageUpdate(Message), 35 | UserUpdate(User), 36 | } 37 | 38 | #[derive(Serialize, Deserialize)] 39 | #[serde(tag = "op", content = "d")] 40 | pub enum ClientPayload { 41 | Authenticate { token: String }, 42 | Ping, 43 | } 44 | 45 | impl Payload { 46 | pub async fn to(self, id: Snowflake) { 47 | publish(id.to_string(), self).await; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/gateway/server/mod.rs: -------------------------------------------------------------------------------- 1 | mod state; 2 | 3 | use crate::database::redis::pubsub; 4 | use crate::gateway::events; 5 | use crate::gateway::{ 6 | client::handler::*, ClientPayload, Receiver, Sender, SocketClient, SocketClientConfig, 7 | }; 8 | use crate::structures::User; 9 | use axum::{ 10 | extract::{ws::WebSocketUpgrade, Query}, 11 | response::IntoResponse, 12 | }; 13 | use futures::StreamExt; 14 | use nanoid::nanoid; 15 | use state::WebSocketState; 16 | use std::sync::Arc; 17 | 18 | lazy_static! { 19 | pub static ref STATE: WebSocketState = WebSocketState::new(); 20 | } 21 | 22 | pub async fn authenticate(receiver: &mut Receiver, config: &SocketClientConfig) -> Option { 23 | log::debug!("authenticate() called"); 24 | let mut retries = 0; 25 | 26 | while let Some(Ok(msg)) = receiver.next().await { 27 | log::debug!("{retries} Try authenticate..."); 28 | if retries == 3 { 29 | break; // nope 30 | } 31 | 32 | let Some(payload) = config.decode(msg) else { 33 | log::debug!("Socket sent an invalid body"); 34 | continue; 35 | }; 36 | 37 | if let ClientPayload::Authenticate { token } = payload { 38 | log::debug!("Provided token: {token}"); 39 | return User::fetch_by_token(&token).await.ok(); 40 | } 41 | 42 | retries += 1; 43 | } 44 | 45 | None 46 | } 47 | 48 | pub async fn upgrade( 49 | socket: WebSocketUpgrade, 50 | Query(config): Query, 51 | ) -> impl IntoResponse { 52 | socket.on_upgrade(|stream| async move { 53 | log::info!("New socket connection"); 54 | let (sender, mut receiver) = stream.split(); 55 | log::debug!("Connection splitted"); 56 | 57 | let sender = Sender::new(sender); 58 | 59 | log::debug!("New sender"); 60 | 61 | let Some(user) = authenticate(&mut receiver, &config).await else { 62 | log::debug!("Invalid user"); 63 | return 64 | }; 65 | 66 | log::debug!("User authenticated: {}", user.username); 67 | 68 | let connection_id = nanoid!(6); 69 | let user_id = user.id; 70 | 71 | let client = if let Some(client) = STATE.clients.get(&user_id) { 72 | client 73 | .connections 74 | .insert(connection_id.clone(), sender.clone()); 75 | Arc::clone(&client) 76 | } else { 77 | let subscriber = pubsub().await; 78 | 79 | // Resubscribe on reconnect 80 | subscriber.manage_subscriptions(); 81 | 82 | let client = Arc::new(SocketClient::new(user, config, subscriber)); 83 | 84 | client 85 | .connections 86 | .insert(connection_id.clone(), sender.clone()); 87 | 88 | STATE.clients.insert(user_id, client.clone()); 89 | 90 | let client_ref = client.clone(); 91 | 92 | log::debug!("Spawn handle_outgoing"); 93 | tokio::spawn(async { handle_outgoing(client_ref).await }); 94 | 95 | client 96 | }; 97 | 98 | if let Err(err) = events::authenticate::run(client.clone(), sender.clone()).await { 99 | log::error!("Couldn't send authenticate packets: {err}"); 100 | return; 101 | } 102 | 103 | let client_ref = Arc::clone(&client); 104 | 105 | let sender_ref = sender.clone(); 106 | log::debug!("Spawn handle_incoming"); 107 | let receiver_task = 108 | tokio::spawn( 109 | async move { handle_incoming(client_ref, sender_ref, &mut receiver).await }, 110 | ); 111 | 112 | // Await client disconnection 113 | receiver_task.await.ok(); 114 | 115 | log::debug!( 116 | "Socket disconnected (User ID: {} | Connection ID: {})", 117 | *user_id, 118 | connection_id 119 | ); 120 | 121 | client.connections.remove(&connection_id); 122 | 123 | if client.connections.is_empty() { 124 | STATE.clients.remove(&user_id); 125 | } 126 | }) 127 | } 128 | -------------------------------------------------------------------------------- /src/gateway/server/state.rs: -------------------------------------------------------------------------------- 1 | use crate::gateway::SocketClient; 2 | use crate::utils::Snowflake; 3 | use dashmap::DashMap; 4 | use std::sync::Arc; 5 | 6 | pub struct WebSocketState { 7 | pub clients: DashMap>, 8 | } 9 | 10 | impl Default for WebSocketState { 11 | fn default() -> Self { 12 | Self::new() 13 | } 14 | } 15 | 16 | impl WebSocketState { 17 | pub fn new() -> Self { 18 | Self { 19 | clients: DashMap::new(), 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate lazy_static; 3 | #[macro_use] 4 | extern crate async_trait; 5 | #[macro_use] 6 | extern crate opg; 7 | #[macro_use] 8 | extern crate serde_with; 9 | 10 | pub mod config; 11 | pub mod database; 12 | pub mod extractors; 13 | pub mod gateway; 14 | pub mod middlewares; 15 | pub mod routes; 16 | pub mod structures; 17 | pub mod utils; 18 | 19 | use axum::{middleware, routing::get, Router, Server}; 20 | use std::net::SocketAddr; 21 | 22 | #[tokio::main] 23 | async fn main() { 24 | dotenv::dotenv().ok(); 25 | 26 | env_logger::Builder::from_env(env_logger::Env::default().filter_or("RUST_LOG", "info")) 27 | .format_timestamp(None) 28 | .init(); 29 | 30 | log::info!("Connecting to database..."); 31 | database::postgres::connect().await; 32 | 33 | log::info!("Connecting to redis..."); 34 | database::redis::connect().await; 35 | 36 | use middlewares::*; 37 | 38 | let app = routes::mount(Router::new()) 39 | .route("/ws", get(gateway::upgrade)) 40 | .layer(middleware::from_fn(auth::handle)) 41 | .layer(middleware::from_fn(ratelimit::handle!(50, 1000 * 60))) 42 | .layer(cors::handle()) 43 | .layer(compression::handle()); 44 | 45 | let addr = SocketAddr::from(([0, 0, 0, 0], *config::PORT)); 46 | 47 | log::info!("Listening on: {}", addr.port()); 48 | 49 | Server::bind(&addr) 50 | .serve(app.into_make_service_with_connect_info::()) 51 | .await 52 | .unwrap(); 53 | } 54 | 55 | #[cfg(test)] 56 | pub mod tests { 57 | use super::*; 58 | use log::LevelFilter; 59 | use once_cell::sync::Lazy; 60 | use tokio::runtime::{Builder, Runtime}; 61 | 62 | static RUNTIME: Lazy = 63 | Lazy::new(|| Builder::new_multi_thread().enable_all().build().unwrap()); 64 | 65 | pub fn run(f: F) -> F::Output { 66 | RUNTIME.block_on(f) 67 | } 68 | 69 | #[ctor::ctor] 70 | fn setup() { 71 | dotenv::dotenv().ok(); 72 | 73 | env_logger::builder() 74 | .filter_level(LevelFilter::Debug) 75 | .parse_filters("fred=off") 76 | .format_timestamp(None) 77 | .init(); 78 | 79 | run(database::postgres::connect()); 80 | run(database::redis::connect()); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/middlewares/auth.rs: -------------------------------------------------------------------------------- 1 | use crate::database::redis::*; 2 | use crate::structures::*; 3 | use crate::utils::error::Error; 4 | use axum::{ 5 | http::{header, Request}, 6 | middleware::Next, 7 | response::Response, 8 | }; 9 | use rmp_serde as MessagePack; 10 | 11 | const ONE_HOUR_IN_SECONDS: i64 = 3600; 12 | 13 | async fn fetch_from_cache(token: &str) -> Option { 14 | REDIS 15 | .get(token) 16 | .await 17 | .ok() 18 | .and_then(|buf: Vec| MessagePack::from_slice(&buf).ok()) 19 | } 20 | 21 | async fn cache_user(token: &str, user: &User) { 22 | let buf = MessagePack::to_vec_named(&user.with_hidden_fields()).unwrap(); 23 | 24 | REDIS 25 | .set::<(), _, _>( 26 | token, 27 | buf.as_slice(), 28 | Expiration::EX(ONE_HOUR_IN_SECONDS).into(), 29 | None, 30 | false, 31 | ) 32 | .await 33 | .ok(); 34 | } 35 | 36 | pub async fn handle(mut req: Request, next: Next) -> Result { 37 | let should_ignore = matches!( 38 | req.uri().path(), 39 | "/" | "/auth/accounts/register" 40 | | "/auth/accounts/login" 41 | | "/auth/accounts/verify" 42 | | "/auth/sessions" 43 | | "/openapi.json" 44 | | "/ws" 45 | ); 46 | 47 | if should_ignore { 48 | return Ok(next.run(req).await); 49 | } 50 | 51 | let Some(token) = req 52 | .headers() 53 | .get(header::AUTHORIZATION) 54 | .and_then(|header| header.to_str().ok()) else { Err(Error::MissingHeader)? }; 55 | 56 | let user = match fetch_from_cache(token).await { 57 | Some(u) => u, 58 | _ => { 59 | let Ok(u) = User::fetch_by_token(token).await else { Err(Error::InvalidToken)? }; 60 | cache_user(token, &u).await; 61 | u 62 | } 63 | }; 64 | 65 | req.extensions_mut().insert(user); 66 | 67 | Ok(next.run(req).await) 68 | } 69 | -------------------------------------------------------------------------------- /src/middlewares/captcha.rs: -------------------------------------------------------------------------------- 1 | use crate::config::*; 2 | use crate::utils::error::*; 3 | use axum::{http::Request, middleware::Next, response::Response}; 4 | use serde::Deserialize; 5 | use serde_json::json; 6 | 7 | #[derive(Deserialize)] 8 | struct CaptchaResponse { 9 | success: bool, 10 | } 11 | 12 | pub async fn handle(req: Request, next: Next) -> Result { 13 | if !*CAPTCHA_ENABLED { 14 | return Ok(next.run(req).await); 15 | } 16 | 17 | let Some(key) = req 18 | .headers() 19 | .get("X-Captcha-Key") 20 | .and_then(|v| v.to_str().ok()) else { Err(Error::MissingHeader)? }; 21 | 22 | let client = reqwest::Client::new(); 23 | let body = json!({ 24 | "response": key, 25 | "secret": *CAPTCHA_TOKEN, 26 | "sitekey": *CAPTCHA_KEY 27 | }); 28 | 29 | let res = client 30 | .post("https://hcaptcha.com/siteverify") 31 | .body(body.to_string()) 32 | .send() 33 | .await; 34 | 35 | if let Ok(res) = res { 36 | if let Ok(captcha) = res.json::().await { 37 | if captcha.success { 38 | return Ok(next.run(req).await); 39 | } 40 | } 41 | } 42 | 43 | Err(Error::FailedCaptcha) 44 | } 45 | -------------------------------------------------------------------------------- /src/middlewares/compression.rs: -------------------------------------------------------------------------------- 1 | use tower_http::compression::CompressionLayer; 2 | 3 | pub fn handle() -> CompressionLayer { 4 | CompressionLayer::new() 5 | } 6 | -------------------------------------------------------------------------------- /src/middlewares/cors.rs: -------------------------------------------------------------------------------- 1 | use axum::http::header::*; 2 | use axum::http::Method; 3 | use std::str::FromStr; 4 | use tower_http::cors::{Any, CorsLayer}; 5 | 6 | pub fn handle() -> CorsLayer { 7 | CorsLayer::new() 8 | .allow_origin(Any) 9 | .allow_methods([ 10 | Method::DELETE, 11 | Method::GET, 12 | Method::HEAD, 13 | Method::OPTIONS, 14 | Method::PATCH, 15 | Method::POST, 16 | Method::PUT, 17 | ]) 18 | .allow_headers([ 19 | ACCEPT, 20 | AUTHORIZATION, 21 | CONTENT_LENGTH, 22 | CONTENT_TYPE, 23 | HeaderName::from_str("X-Captcha-Key").unwrap(), 24 | ]) 25 | } 26 | -------------------------------------------------------------------------------- /src/middlewares/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod auth; 2 | pub mod captcha; 3 | pub mod compression; 4 | pub mod cors; 5 | pub mod ratelimit; 6 | -------------------------------------------------------------------------------- /src/middlewares/ratelimit.rs: -------------------------------------------------------------------------------- 1 | use crate::config::TRUST_CLOUDFLARE; 2 | use crate::structures::User; 3 | use crate::utils::error::Error; 4 | use axum::{extract::ConnectInfo, http::Request, middleware::Next, response::Response}; 5 | use governor::{ 6 | clock::{Clock, DefaultClock}, 7 | middleware::StateInformationMiddleware, 8 | state::keyed::DefaultKeyedStateStore, 9 | RateLimiter as Limiter, 10 | }; 11 | use serde::Serialize; 12 | use std::{ 13 | net::{IpAddr, SocketAddr}, 14 | sync::Arc, 15 | }; 16 | lazy_static! { 17 | static ref CLOCK: DefaultClock = DefaultClock::default(); 18 | } 19 | 20 | #[derive(Serialize, Clone, Copy, Debug, OpgModel)] 21 | pub struct RateLimitInfo { 22 | pub limit: u32, 23 | pub remaining: u32, 24 | pub retry_after: u64, 25 | } 26 | 27 | type RateLimiter = 28 | Limiter, DefaultClock, StateInformationMiddleware>; 29 | 30 | pub async fn ratelimit( 31 | req: Request, 32 | next: Next, 33 | limiter: Arc, 34 | ) -> Result { 35 | let key = if let Some(user) = req.extensions().get::() { 36 | user.id.to_string() 37 | } else { 38 | let header = |name| { 39 | req.headers() 40 | .get(name) 41 | .and_then(|v| v.to_str().ok()) 42 | .and_then(|v| v.split(',').find_map(|s| s.trim().parse::().ok())) 43 | }; 44 | 45 | let ip = if *TRUST_CLOUDFLARE && header("CF-Connecting-IP").is_some() { 46 | header("CF-Connecting-IP") 47 | } else { 48 | header("x-forwarded-for") 49 | .or_else(|| header("x-real-ip")) 50 | .or_else(|| { 51 | req.extensions() 52 | .get::>() 53 | .map(|ConnectInfo(addr)| addr.ip()) 54 | }) 55 | }; 56 | 57 | ip.expect("Cannot extract IP").to_string() 58 | }; 59 | 60 | let info = match limiter.check_key(&key) { 61 | Ok(snapshot) => RateLimitInfo { 62 | limit: snapshot.quota().burst_size().get(), 63 | remaining: snapshot.remaining_burst_capacity(), 64 | retry_after: 0, 65 | }, 66 | Err(negative) => RateLimitInfo { 67 | limit: negative.quota().burst_size().get(), 68 | remaining: 0, 69 | retry_after: negative.wait_time_from(CLOCK.now()).as_secs(), 70 | }, 71 | }; 72 | 73 | if info.retry_after > 0 { 74 | log::info!("IP: {key} has executed the rate limit"); 75 | return Err(Error::RateLimited(info)); 76 | } 77 | 78 | let mut res = next.run(req).await; 79 | let headers = res.headers_mut(); 80 | 81 | headers.insert("X-RateLimit-Remaining", info.remaining.into()); 82 | headers.insert("X-RateLimit-Limit", info.limit.into()); 83 | headers.insert("Retry-After", info.retry_after.into()); 84 | 85 | Ok(res) 86 | } 87 | 88 | #[macro_export] 89 | macro_rules! handle { 90 | ($max:expr,$interval:expr) => {{ 91 | let limiter = std::sync::Arc::new( 92 | governor::RateLimiter::::keyed( 93 | governor::Quota::with_period(std::time::Duration::from_millis($interval)) 94 | .unwrap() 95 | .allow_burst($max.try_into().expect("Must be a non-zero number")), 96 | ) 97 | .with_middleware::(), 98 | ); 99 | 100 | move |req: axum::http::Request, 101 | next: axum::middleware::Next| { 102 | $crate::middlewares::ratelimit::ratelimit(req, next, limiter.clone()) 103 | } 104 | }}; 105 | } 106 | 107 | pub(crate) use handle; 108 | -------------------------------------------------------------------------------- /src/routes/auth/accounts/login.rs: -------------------------------------------------------------------------------- 1 | use axum::response::Redirect; 2 | 3 | pub async fn login() -> Redirect { 4 | Redirect::permanent("/sessions") 5 | } 6 | -------------------------------------------------------------------------------- /src/routes/auth/accounts/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod login; 2 | pub mod register; 3 | pub mod verify; 4 | 5 | pub fn routes() -> axum::Router { 6 | use crate::middlewares::*; 7 | use axum::{middleware, routing::*, Router}; 8 | 9 | Router::new() 10 | .route( 11 | "/register", 12 | post(register::register).route_layer(middleware::from_fn(captcha::handle)), 13 | ) 14 | .route("/login", post(login::login)) 15 | .route("/verify", get(verify::verify)) 16 | } 17 | -------------------------------------------------------------------------------- /src/routes/auth/accounts/register.rs: -------------------------------------------------------------------------------- 1 | use crate::config::*; 2 | use crate::extractors::*; 3 | use crate::structures::*; 4 | use crate::utils::*; 5 | use argon2::Config; 6 | use serde::Deserialize; 7 | use sqlx::types::Uuid; 8 | use validator::Validate; 9 | 10 | #[derive(Deserialize, Validate, OpgModel)] 11 | pub struct RegisterAccountOptions { 12 | #[validate(length(min = 3, max = 32))] 13 | pub username: String, 14 | #[validate(length(min = 8, max = 32))] 15 | pub password: String, 16 | #[validate(email)] 17 | pub email: String, 18 | #[opg(string)] 19 | pub invite_code: Option, 20 | } 21 | 22 | #[derive(Serialize, OpgModel)] 23 | pub struct RegisterResponse { 24 | pub pending_verification: bool, 25 | } 26 | 27 | pub async fn register( 28 | ValidatedJson(mut data): ValidatedJson, 29 | ) -> Result> { 30 | data.email = email::normalize(data.email).expect("Non normalized email"); 31 | 32 | let invite = if *REQUIRE_INVITE_TO_REGISTER && data.invite_code.is_some() { 33 | email::AccountInvite::find_by_id(data.invite_code.unwrap()) 34 | .await 35 | .ok() 36 | } else { 37 | None 38 | }; 39 | 40 | if *REQUIRE_INVITE_TO_REGISTER { 41 | if let Some(invite) = &invite { 42 | if invite.used { 43 | return Err(Error::InviteAlreadyTaken); 44 | } 45 | } else { 46 | return Err(Error::RequireInviteCode); 47 | } 48 | } 49 | 50 | if User::email_taken(&data.email).await { 51 | return Err(Error::EmailAlreadyInUse); 52 | } 53 | 54 | let config = Config::default(); 55 | let salt = nanoid::nanoid!(24); 56 | let hashed_password = 57 | argon2::hash_encoded(data.password.as_bytes(), salt.as_bytes(), &config).unwrap(); 58 | 59 | let mut user = User::new(data.username, data.email, hashed_password); 60 | 61 | if *EMAIL_VERIFICATION && email::send(&user).await { 62 | log::debug!("Email have been sent to: {}", *user.email); 63 | } else { 64 | user.verified = true.into(); 65 | } 66 | 67 | if let Some(mut invite) = invite { 68 | invite.used = true; 69 | invite.taken_by = Some(user.id); 70 | 71 | invite.update().await?; 72 | } 73 | 74 | user.insert().await?; 75 | 76 | Ok(RegisterResponse { 77 | pending_verification: !*user.verified, 78 | } 79 | .into()) 80 | } 81 | 82 | #[cfg(test)] 83 | mod tests { 84 | use super::*; 85 | use crate::tests::run; 86 | 87 | #[test] 88 | fn execute() -> Result<(), Error> { 89 | run(async { 90 | let email = format!("test.{}@example.com", nanoid::nanoid!(6)); 91 | let payload = RegisterAccountOptions { 92 | username: "test".to_string(), 93 | email: email.clone(), 94 | password: "passw0rd".to_string(), 95 | invite_code: None, 96 | }; 97 | 98 | let _ = register(ValidatedJson(payload)).await?; 99 | 100 | let user = User::find_one("email = $1", vec![email::normalize(email)]).await?; 101 | 102 | user.delete().await?; 103 | 104 | Ok(()) 105 | }) 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/routes/auth/accounts/verify.rs: -------------------------------------------------------------------------------- 1 | use crate::config::EMAIL_VERIFICATION; 2 | use crate::extractors::*; 3 | use crate::structures::*; 4 | use crate::utils::*; 5 | use uuid::Uuid; 6 | 7 | #[derive(Deserialize)] 8 | pub struct VerifyQuery { 9 | user_id: Snowflake, 10 | code: Uuid, 11 | } 12 | 13 | pub async fn verify(Query(opts): Query) -> Result<()> { 14 | if !*EMAIL_VERIFICATION { 15 | return Ok(()); 16 | } 17 | 18 | if email::verify(opts.user_id, opts.code).await { 19 | let mut user = opts.user_id.user().await?; 20 | 21 | user.verified = true.into(); 22 | user.update().await?; 23 | Ok(()) 24 | } else { 25 | Err(Error::UnknownAccount) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/routes/auth/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod accounts; 2 | pub mod sessions; 3 | 4 | pub fn routes() -> axum::Router { 5 | use crate::middlewares::*; 6 | use axum::{middleware, Router}; 7 | 8 | Router::new() 9 | .nest("/accounts", accounts::routes()) 10 | .nest("/sessions", sessions::routes()) 11 | .layer(middleware::from_fn(ratelimit::handle!( 12 | 10, 13 | 1000 * 60 * 60 * 3 14 | ))) 15 | } 16 | -------------------------------------------------------------------------------- /src/routes/auth/sessions/create.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::structures::*; 3 | use crate::utils::*; 4 | use serde::Deserialize; 5 | use validator::Validate; 6 | 7 | #[derive(Deserialize, Validate, OpgModel)] 8 | pub struct CreateSessionOptions { 9 | #[validate(length(min = 8, max = 32))] 10 | pub password: String, 11 | #[validate(email)] 12 | pub email: String, 13 | } 14 | 15 | pub async fn create(ValidatedJson(data): ValidatedJson) -> Result { 16 | let user = User::find_one("email = $1", vec![data.email]).await; 17 | 18 | match user { 19 | Ok(user) => { 20 | if !*user.verified { 21 | return Err(Error::AccountVerificationRequired); 22 | } 23 | 24 | let valid_password = 25 | match argon2::verify_encoded(&user.password, data.password.as_bytes()) { 26 | Ok(x) => x, 27 | _ => false, 28 | }; 29 | 30 | if !valid_password { 31 | return Err(Error::MissingAccess); 32 | } 33 | 34 | let session = Session::new(user.id); 35 | 36 | session.insert().await?; 37 | 38 | Ok(session.token) 39 | } 40 | _ => Err(Error::UnknownAccount), 41 | } 42 | } 43 | 44 | #[cfg(test)] 45 | mod tests { 46 | use super::*; 47 | use crate::tests::run; 48 | 49 | #[test] 50 | fn execute() -> Result<(), Error> { 51 | run(async { 52 | let user = User::faker(); 53 | 54 | user.insert().await?; 55 | 56 | let payload = CreateSessionOptions { 57 | email: (*user.email).clone(), 58 | password: "passw0rd".to_string(), 59 | }; 60 | 61 | create(ValidatedJson(payload)).await?; 62 | 63 | user.delete().await?; 64 | 65 | Ok(()) 66 | }) 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/routes/auth/sessions/delete.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::structures::*; 3 | use crate::utils::*; 4 | use serde::Deserialize; 5 | use validator::Validate; 6 | 7 | #[derive(Deserialize, Validate, OpgModel)] 8 | pub struct DeleteSessionOptions { 9 | token: String, 10 | } 11 | 12 | pub async fn delete( 13 | Extension(user): Extension, 14 | Path(id): Path, 15 | ValidatedJson(data): ValidatedJson, 16 | ) -> Result<()> { 17 | let session = id.session(user.id).await?; 18 | 19 | if session.token != data.token { 20 | return Err(Error::InvalidToken); 21 | } 22 | 23 | session.delete().await?; 24 | 25 | Ok(()) 26 | } 27 | 28 | #[cfg(test)] 29 | mod tests { 30 | use super::*; 31 | use crate::tests::run; 32 | 33 | #[test] 34 | fn execute() -> Result<(), Error> { 35 | run(async { 36 | let session = Session::faker().await?; 37 | session.insert().await?; 38 | let payload = DeleteSessionOptions { 39 | token: session.token.clone(), 40 | }; 41 | 42 | delete( 43 | Extension(session.user_id.unwrap().user().await?), 44 | Path(session.id), 45 | ValidatedJson(payload), 46 | ) 47 | .await?; 48 | 49 | Ok(()) 50 | }) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/routes/auth/sessions/fetch.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::structures::*; 3 | use crate::utils::*; 4 | 5 | pub async fn fetch_one( 6 | Extension(user): Extension, 7 | Path(id): Path, 8 | ) -> Result> { 9 | Ok(id.session(user.id).await?.into()) 10 | } 11 | 12 | pub async fn fetch_many(Extension(user): Extension) -> Result>> { 13 | Ok(Session::find("user_id = $1", vec![user.id]).await?.into()) 14 | } 15 | 16 | #[cfg(test)] 17 | mod tests { 18 | use super::*; 19 | use crate::tests::run; 20 | 21 | #[test] 22 | fn execute() -> Result<(), Error> { 23 | run(async { 24 | let session = Session::faker().await?; 25 | session.insert().await?; 26 | let user = session.user_id.unwrap().user().await?; 27 | 28 | let results = fetch_many(Extension(user.clone())).await?; 29 | 30 | assert_eq!(results.0.len(), 1); 31 | 32 | let _ = fetch_one(Extension(user), Path(session.id)).await?; 33 | 34 | Ok(()) 35 | }) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/routes/auth/sessions/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod create; 2 | pub mod delete; 3 | pub mod fetch; 4 | 5 | pub fn routes() -> axum::Router { 6 | use crate::middlewares::*; 7 | use axum::{middleware, routing::*, Router}; 8 | 9 | Router::new() 10 | .route( 11 | "/", 12 | get(fetch::fetch_many) 13 | .post(create::create) 14 | .route_layer(middleware::from_fn(captcha::handle)), 15 | ) 16 | .route("/:session_id", get(fetch::fetch_one).delete(delete::delete)) 17 | } 18 | -------------------------------------------------------------------------------- /src/routes/bots/create.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::structures::*; 3 | use crate::utils::*; 4 | 5 | pub async fn create() -> Result> { 6 | todo!() 7 | } 8 | -------------------------------------------------------------------------------- /src/routes/bots/delete.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::structures::*; 3 | use crate::utils::*; 4 | 5 | pub async fn delete(Extension(user): Extension, Path(id): Path) -> Result<()> { 6 | let bot = id.bot().await?; 7 | 8 | if bot.owner_id != user.id { 9 | return Err(Error::MissingAccess); 10 | } 11 | 12 | bot.delete().await?; 13 | 14 | Ok(()) 15 | } 16 | -------------------------------------------------------------------------------- /src/routes/bots/fetch.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::structures::*; 3 | use crate::utils::*; 4 | 5 | pub async fn fetch_one(Path(id): Path) -> Result> { 6 | Ok(id.bot().await?.into()) 7 | } 8 | 9 | pub async fn fetch_many(Extension(user): Extension) -> Result>> { 10 | Ok(user.fetch_bots().await?.into()) 11 | } 12 | -------------------------------------------------------------------------------- /src/routes/bots/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod create; 2 | pub mod delete; 3 | pub mod fetch; 4 | 5 | pub fn routes() -> axum::Router { 6 | use crate::middlewares::*; 7 | use axum::{middleware, routing::*, Router}; 8 | 9 | Router::new() 10 | .route("/", get(fetch::fetch_many).post(create::create)) 11 | .route("/:bot_id", get(fetch::fetch_one).delete(delete::delete)) 12 | .layer(middleware::from_fn(ratelimit::handle!(20, 1000 * 5))) 13 | } 14 | -------------------------------------------------------------------------------- /src/routes/channels/create.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::gateway::*; 3 | use crate::structures::*; 4 | use crate::utils::*; 5 | use serde::Deserialize; 6 | use validator::Validate; 7 | 8 | #[derive(Deserialize, Validate, OpgModel)] 9 | pub struct CreateGroupOptions { 10 | #[validate(length(min = 3, max = 32))] 11 | name: String, 12 | } 13 | 14 | pub async fn create( 15 | Extension(user): Extension, 16 | ValidatedJson(data): ValidatedJson, 17 | ) -> Result> { 18 | let group = Channel::new_group(user.id, data.name); 19 | 20 | group.insert().await?; 21 | 22 | for id in group.recipients.as_ref().unwrap() { 23 | Payload::ChannelCreate(group.clone()).to(*id).await; 24 | } 25 | 26 | Ok(Json(group)) 27 | } 28 | -------------------------------------------------------------------------------- /src/routes/channels/delete.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::gateway::*; 3 | use crate::structures::*; 4 | use crate::utils::*; 5 | 6 | pub async fn delete(Extension(user): Extension, Path(id): Path) -> Result<()> { 7 | let channel = id.channel(user.id.into()).await?; 8 | 9 | if channel.owner_id != Some(user.id) { 10 | return Err(Error::MissingAccess); 11 | } 12 | 13 | channel.delete().await?; 14 | 15 | Payload::ChannelDelete(id.into()).to(id).await; 16 | 17 | Ok(()) 18 | } 19 | -------------------------------------------------------------------------------- /src/routes/channels/edit.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::gateway::*; 3 | use crate::structures::*; 4 | use crate::utils::*; 5 | use inter_struct::prelude::*; 6 | use serde::Deserialize; 7 | use validator::Validate; 8 | 9 | #[derive(Deserialize, Validate, OpgModel, StructMerge)] 10 | #[struct_merge("crate::structures::channel::Channel")] 11 | pub struct EditGroupOptions { 12 | #[validate(length(min = 3, max = 32))] 13 | name: Option, 14 | } 15 | 16 | pub async fn edit( 17 | Extension(user): Extension, 18 | Path(id): Path, 19 | ValidatedJson(data): ValidatedJson, 20 | ) -> Result> { 21 | let mut group = id.channel(user.id.into()).await?; 22 | 23 | Permissions::fetch_cached(&user, Some(&group)) 24 | .await? 25 | .has(bits![MANAGE_CHANNELS])?; 26 | 27 | group.merge(data); 28 | group.update().await?; 29 | 30 | Payload::ChannelUpdate(group.clone()).to(group.id).await; 31 | 32 | Ok(Json(group)) 33 | } 34 | -------------------------------------------------------------------------------- /src/routes/channels/fetch.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::structures::*; 3 | use crate::utils::*; 4 | 5 | pub async fn fetch_many(Extension(user): Extension) -> Result>> { 6 | Ok(user.fetch_channels().await?.into()) 7 | } 8 | 9 | pub async fn fetch_one( 10 | Extension(user): Extension, 11 | Path(id): Path, 12 | ) -> Result> { 13 | Ok(id.channel(user.id.into()).await?.into()) 14 | } 15 | -------------------------------------------------------------------------------- /src/routes/channels/kick.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::gateway::*; 3 | use crate::structures::*; 4 | use crate::utils::*; 5 | 6 | pub async fn kick( 7 | Extension(user): Extension, 8 | Path((group_id, target_id)): Path<(Snowflake, Snowflake)>, 9 | ) -> Result<()> { 10 | let target = target_id.user().await?; 11 | let mut group = group_id.channel(user.id.into()).await?; 12 | 13 | Permissions::fetch_cached(&user, Some(&group)) 14 | .await? 15 | .has(bits![KICK_MEMBERS])?; 16 | 17 | if let Some(recipients) = group.recipients.as_mut() { 18 | let exists = recipients 19 | .iter() 20 | .position(|&id| id == target.id) 21 | .map(|i| recipients.remove(i)) 22 | .is_some(); 23 | 24 | if !exists { 25 | return Err(Error::UnknownMember); 26 | } 27 | } 28 | 29 | group.update().await?; 30 | 31 | Payload::ChannelUpdate(group).to(group_id).await; 32 | 33 | Ok(()) 34 | } 35 | -------------------------------------------------------------------------------- /src/routes/channels/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod create; 2 | pub mod delete; 3 | pub mod edit; 4 | pub mod fetch; 5 | pub mod kick; 6 | 7 | pub fn routes() -> axum::Router { 8 | use crate::middlewares::*; 9 | use axum::{middleware, routing::*, Router}; 10 | 11 | Router::new() 12 | .route("/", get(fetch::fetch_many).post(create::create)) 13 | .route( 14 | "/:channel_id", 15 | get(fetch::fetch_one) 16 | .patch(edit::edit) 17 | .delete(delete::delete), 18 | ) 19 | .route("/:channel_id/:target", delete(kick::kick)) 20 | .layer(middleware::from_fn(ratelimit::handle!(35, 1000 * 5))) 21 | } 22 | -------------------------------------------------------------------------------- /src/routes/docs.rs: -------------------------------------------------------------------------------- 1 | use super::auth::{accounts, sessions}; 2 | use super::{channels, messages}; 3 | use crate::structures::*; 4 | use axum::{extract::Json, routing::get, Router}; 5 | 6 | pub fn document(app: Router) -> Router { 7 | let schema = describe_api! { 8 | info: { 9 | title: "ItChat API", 10 | version: "0.0.0", 11 | }, 12 | tags: { 13 | users, 14 | servers, 15 | roles, 16 | messages, 17 | groups, 18 | channels, 19 | members, 20 | auth, 21 | invites, 22 | bots 23 | }, 24 | servers: { "https://api.itchat.world" }, 25 | security_schemes: {}, 26 | paths: { 27 | // Accounts/Sessions 28 | ("auth/accounts/login"): { 29 | POST: { 200: Session, body: sessions::create::CreateSessionOptions, tags: {auth} } }, 30 | ("auth/accounts/verify"): { 31 | GET: { 32 | 200: None, 33 | tags: {auth}, 34 | parameters: { 35 | (query user_id: u64): {}, 36 | (query code: String): {}, 37 | } 38 | } 39 | }, 40 | ("auth/accounts/register"): { 41 | POST: { 200: accounts::register::RegisterResponse, body: accounts::register::RegisterAccountOptions, tags: {auth} } 42 | }, 43 | ("auth/sessions"): { 44 | POST: { 200: String, body: sessions::create::CreateSessionOptions, tags: {auth} } 45 | }, 46 | ("auth/sessions" / { session_id: u64 }): { 47 | DELETE: { 200: None, tags: {auth} }, 48 | GET: { 200: Session, tags: {auth} } 49 | }, 50 | 51 | // Users 52 | ("users"): { GET: { 200: Vec, tags: {users}} }, 53 | ("users/@me"): { GET: { 200: User, tags: {users} } }, 54 | ("users" / { user_id: u64 }): { GET: { 200: User, tags: {users} } }, 55 | ("users" / { user_id: u64 } / "dm"): { GET: { 200: Channel, tags: {users} } }, 56 | ("users/@me/relationships" / { user_id: u64 }): { 57 | POST: { 200: None, tags: {users} }, 58 | PUT: { 200: None, tags: {users} }, 59 | DELETE: { 200: None, tags: {users} } 60 | }, 61 | 62 | // Channels 63 | ("channels"): { 64 | GET: { 200: Vec, tags:{channels} }, 65 | POST: { 200("Create a group channel"): Channel, body: channels::create::CreateGroupOptions, tags:{channels} } 66 | }, 67 | ("channels" / { channel_id: u64 }): { 68 | GET: { 200: Channel, tags:{channels} }, 69 | DELETE: { 200: None, tags:{channels} }, 70 | PATCH: { 200: Channel, body: channels::edit::EditGroupOptions, tags:{channels} } 71 | }, 72 | ("channels" / { channel_id: u64 } / { user_id: u64 }): { 73 | DELETE: { 200: None, tags:{channels} } 74 | }, 75 | 76 | // Messages 77 | ("messages" / { channel_id: u64 }): { 78 | POST: { 200: Message, body: messages::create::CreateMessageOptions, tags:{messages} }, 79 | GET: { 200: Vec, tags:{messages}, parameters: { 80 | (query limit: Option): {}, 81 | } } 82 | }, 83 | 84 | ("messages" / { channel_id: u64 } / { message_id: u64 }): { 85 | GET: { 200: Message, tags:{messages} }, 86 | PATCH: { 200: Message, body: messages::edit::EditMessageOptions, tags:{messages} }, 87 | DELETE: { 200: None, tags:{messages} } 88 | }, 89 | 90 | 91 | // Bots 92 | ("bots"): { 93 | POST: { 200: Bot, tags:{bots} }, 94 | GET: { 200: Vec, tags:{bots} } 95 | }, 96 | ("bots" / { bot_id: u64 }): { 97 | GET: { 200: Bot, tags:{bots} }, 98 | DELETE: { 200: None, tags:{bots} } 99 | } 100 | } 101 | }; 102 | 103 | app.route("/openapi.json", get(move || async { Json(schema) })) 104 | } 105 | -------------------------------------------------------------------------------- /src/routes/messages/create.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::gateway::*; 3 | use crate::structures::*; 4 | use crate::utils::*; 5 | use serde::Deserialize; 6 | use validator::Validate; 7 | 8 | #[derive(Deserialize, Validate, OpgModel)] 9 | pub struct CreateMessageOptions { 10 | #[validate(length(min = 1, max = 2000))] 11 | content: Option, 12 | #[validate(length(max = 5))] 13 | attachments: Option>, 14 | } 15 | 16 | pub async fn create( 17 | Extension(user): Extension, 18 | Path(channel_id): Path, 19 | ValidatedJson(data): ValidatedJson, 20 | ) -> Result> { 21 | Permissions::fetch(&user, channel_id.into()) 22 | .await? 23 | .has(bits![VIEW_CHANNEL, SEND_MESSAGES])?; 24 | 25 | let mut msg = Message::new(channel_id, user.id); 26 | 27 | msg.content = data.content; 28 | 29 | if let Some(attachments) = data.attachments { 30 | msg.attachments = sqlx::types::Json(attachments); 31 | } 32 | 33 | if msg.is_empty() { 34 | return Err(Error::EmptyMessage); 35 | } 36 | 37 | msg.insert().await?; 38 | 39 | Payload::MessageCreate(msg.clone()).to(channel_id).await; 40 | 41 | Ok(Json(msg)) 42 | } 43 | -------------------------------------------------------------------------------- /src/routes/messages/delete.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::gateway::*; 3 | use crate::structures::*; 4 | use crate::utils::*; 5 | 6 | pub async fn delete( 7 | Extension(user): Extension, 8 | Path((channel_id, id)): Path<(Snowflake, Snowflake)>, 9 | ) -> Result<()> { 10 | let msg = id.message().await?; 11 | let p = Permissions::fetch(&user, channel_id.into()).await?; 12 | 13 | if msg.author_id != user.id { 14 | p.has(bits![MANAGE_MESSAGES])?; 15 | } else { 16 | p.has(bits![MANAGE_MESSAGES, VIEW_CHANNEL])?; 17 | } 18 | 19 | let attachment_ids = msg 20 | .attachments 21 | .0 22 | .clone() 23 | .into_iter() 24 | .map(|a| a.id) 25 | .collect::>(); 26 | 27 | let mut tx = pool().begin().await?; 28 | 29 | sqlx::query("UPDATE attachments SET deleted = TRUE WHERE id = ANY($1)") 30 | .bind(attachment_ids) 31 | .execute(&mut tx) 32 | .await?; 33 | 34 | msg.delete_tx(&mut tx).await?; 35 | tx.commit().await?; 36 | 37 | Payload::MessageDelete(id.into()).to(channel_id).await; 38 | 39 | Ok(()) 40 | } 41 | -------------------------------------------------------------------------------- /src/routes/messages/edit.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::gateway::*; 3 | use crate::structures::*; 4 | use crate::utils::*; 5 | use chrono::Utc; 6 | use serde::Deserialize; 7 | use validator::Validate; 8 | 9 | #[derive(Deserialize, Validate, OpgModel)] 10 | pub struct EditMessageOptions { 11 | #[validate(length(min = 1, max = 2000))] 12 | content: String, 13 | } 14 | 15 | pub async fn edit( 16 | Extension(user): Extension, 17 | Path((channel_id, id)): Path<(Snowflake, Snowflake)>, 18 | ValidatedJson(data): ValidatedJson, 19 | ) -> Result> { 20 | let mut msg = id.message().await?; 21 | 22 | if msg.author_id != user.id || msg.channel_id != channel_id { 23 | return Err(Error::MissingAccess); 24 | } 25 | 26 | Permissions::fetch(&user, channel_id.into()) 27 | .await? 28 | .has(bits![VIEW_CHANNEL])?; 29 | 30 | msg.content = data.content.into(); 31 | msg.edited_at = Some(Utc::now().naive_utc()); 32 | msg.update().await?; 33 | 34 | Payload::MessageUpdate(msg.clone()).to(channel_id).await; 35 | 36 | Ok(Json(msg)) 37 | } 38 | -------------------------------------------------------------------------------- /src/routes/messages/fetch.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::structures::*; 3 | use crate::utils::*; 4 | 5 | #[derive(Deserialize)] 6 | pub struct FetchMessagesQuery { 7 | limit: Option, 8 | } 9 | 10 | pub async fn fetch_one( 11 | Extension(user): Extension, 12 | Path((channel_id, id)): Path<(Snowflake, Snowflake)>, 13 | ) -> Result> { 14 | let msg = id.message().await?; 15 | 16 | if msg.channel_id != channel_id { 17 | return Err(Error::MissingAccess); 18 | } 19 | 20 | Permissions::fetch(&user, channel_id.into()) 21 | .await? 22 | .has(bits![VIEW_CHANNEL, READ_MESSAGE_HISTORY])?; 23 | 24 | Ok(Json(msg)) 25 | } 26 | 27 | pub async fn fetch_many( 28 | Extension(user): Extension, 29 | Path(channel_id): Path, 30 | Query(opt): Query, 31 | ) -> Result>> { 32 | let channel = channel_id.channel(user.id.into()).await?; 33 | 34 | Permissions::fetch(&user, channel_id.into()) 35 | .await? 36 | .has(bits![VIEW_CHANNEL, READ_MESSAGE_HISTORY])?; 37 | 38 | let messages = channel.fetch_messages(opt.limit.unwrap_or(100)).await?; 39 | 40 | Ok(Json(messages)) 41 | } 42 | -------------------------------------------------------------------------------- /src/routes/messages/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod create; 2 | pub mod delete; 3 | pub mod edit; 4 | pub mod fetch; 5 | 6 | pub fn routes() -> axum::Router { 7 | use crate::middlewares::*; 8 | use axum::{middleware, routing::*, Router}; 9 | 10 | Router::new() 11 | .route("/", post(create::create)) 12 | .route("/", get(fetch::fetch_many)) 13 | .route( 14 | "/:message_id", 15 | get(fetch::fetch_one) 16 | .patch(edit::edit) 17 | .delete(delete::delete), 18 | ) 19 | .layer(middleware::from_fn(ratelimit::handle!(10, 1000 * 10))) 20 | } 21 | -------------------------------------------------------------------------------- /src/routes/mod.rs: -------------------------------------------------------------------------------- 1 | mod auth; 2 | mod bots; 3 | mod channels; 4 | mod docs; 5 | mod messages; 6 | mod users; 7 | 8 | async fn root() -> &'static str { 9 | "Up!" 10 | } 11 | 12 | use axum::{routing::*, Router}; 13 | 14 | pub fn mount(app: Router) -> Router { 15 | docs::document(app) 16 | .route("/", get(root)) 17 | .nest("/auth", auth::routes()) 18 | .nest("/users", users::routes()) 19 | .nest("/bots", bots::routes()) 20 | .nest("/channels", channels::routes()) 21 | .nest("/messages/:channel_id", messages::routes()) 22 | } 23 | -------------------------------------------------------------------------------- /src/routes/users/fetch.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::structures::*; 3 | use crate::utils::*; 4 | 5 | pub async fn fetch_me(Extension(user): Extension) -> Json { 6 | user.into() 7 | } 8 | 9 | pub async fn fetch_one( 10 | Extension(user): Extension, 11 | Path(id): Path, 12 | ) -> Result> { 13 | if user.id == id { 14 | return Ok(user.into()); 15 | } 16 | Ok(id.user().await?.into()) 17 | } 18 | 19 | pub async fn fetch_many(Extension(user): Extension) -> Result>> { 20 | Ok(user.fetch_relations(&mut vec![]).await?.into()) 21 | } 22 | -------------------------------------------------------------------------------- /src/routes/users/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod fetch; 2 | pub mod open_dm; 3 | pub mod relationships; 4 | 5 | pub fn routes() -> axum::Router { 6 | use crate::middlewares::*; 7 | use axum::{middleware, routing::*, Router}; 8 | 9 | Router::new() 10 | .nest("/@me/relationships", relationships::routes()) 11 | .route("/", get(fetch::fetch_many)) 12 | .route("/@me", get(fetch::fetch_me)) 13 | .route("/:user_id", get(fetch::fetch_one)) 14 | .route("/:user_id/dm", get(open_dm::open_dm)) 15 | .layer(middleware::from_fn(ratelimit::handle!(20, 1000 * 5))) 16 | } 17 | -------------------------------------------------------------------------------- /src/routes/users/open_dm.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::gateway::*; 3 | use crate::structures::*; 4 | use crate::utils::*; 5 | 6 | pub async fn open_dm( 7 | Extension(user): Extension, 8 | Path(id): Path, 9 | ) -> Result> { 10 | let channel = SqlQuery::new("type = $1 AND recipients @> ARRAY[$2, $3]::BIGINT[]") 11 | .push(ChannelTypes::Direct) 12 | .push(user.id) 13 | .push(id) 14 | .find_one::() 15 | .await; 16 | 17 | if let Ok(channel) = channel { 18 | return Ok(channel.into()); 19 | } 20 | 21 | let target = id.user().await?; 22 | let channel = Channel::new_dm(user.id, target.id); 23 | 24 | channel.insert().await?; 25 | 26 | Payload::ChannelCreate(channel.clone()).to(user.id).await; 27 | 28 | if target.id != user.id { 29 | Payload::ChannelCreate(channel.clone()).to(target.id).await; 30 | } 31 | 32 | Ok(channel.into()) 33 | } 34 | -------------------------------------------------------------------------------- /src/routes/users/relationships/add.rs: -------------------------------------------------------------------------------- 1 | use crate::config::MAX_FRIEND_REQUESTS; 2 | use crate::extractors::*; 3 | use crate::gateway::*; 4 | use crate::structures::*; 5 | use crate::utils::*; 6 | 7 | pub async fn add(Extension(mut user): Extension, Path(id): Path) -> Result<()> { 8 | if *MAX_FRIEND_REQUESTS <= user.relations.len() as u64 { 9 | return Err(Error::MaximumFriendRequests); 10 | } 11 | 12 | if let Some(&status) = user.relations.0.get(&id) { 13 | match status { 14 | RelationshipStatus::Friend => return Err(Error::AlreadyFriends), 15 | RelationshipStatus::Blocked => return Err(Error::Blocked), 16 | RelationshipStatus::BlockedByOther => return Err(Error::BlockedByOther), 17 | RelationshipStatus::Outgoing => return Err(Error::AlreadySendRequest), 18 | _ => {} 19 | }; 20 | } 21 | 22 | let mut target = id.user().await?; 23 | 24 | // (user_status, target_status) 25 | let status = if Some(&RelationshipStatus::Outgoing) == target.relations.0.get(&user.id) { 26 | // Accept friend request 27 | (RelationshipStatus::Friend, RelationshipStatus::Friend) 28 | } else { 29 | // Send friend request 30 | (RelationshipStatus::Outgoing, RelationshipStatus::Incoming) 31 | }; 32 | 33 | user.relations.0.insert(target.id, status.0); 34 | target.relations.0.insert(user.id, status.1); 35 | 36 | let mut tx = pool().begin().await?; 37 | 38 | user.update_tx(&mut tx).await?; 39 | target.update_tx(&mut tx).await?; 40 | 41 | tx.commit().await?; 42 | 43 | user.relationship = status.1.into(); 44 | target.relationship = status.0.into(); 45 | 46 | Payload::UserUpdate(target.clone()).to(user.id).await; 47 | Payload::UserUpdate(user).to(target.id).await; 48 | 49 | Ok(()) 50 | } 51 | -------------------------------------------------------------------------------- /src/routes/users/relationships/block.rs: -------------------------------------------------------------------------------- 1 | use crate::config::MAX_BLOCKED; 2 | use crate::extractors::*; 3 | use crate::gateway::*; 4 | use crate::structures::*; 5 | use crate::utils::*; 6 | 7 | pub async fn block(Extension(mut user): Extension, Path(id): Path) -> Result<()> { 8 | if *MAX_BLOCKED <= user.relations.len() as u64 { 9 | return Err(Error::MaximumBlocked); 10 | } 11 | 12 | if Some(&RelationshipStatus::Blocked) == user.relations.0.get(&id) { 13 | return Ok(()); 14 | } 15 | 16 | let status = if Some(&RelationshipStatus::BlockedByOther) == user.relations.0.get(&id) { 17 | // The target blocked me, block him is well 18 | (RelationshipStatus::Blocked, RelationshipStatus::Blocked) 19 | } else { 20 | // Block the target 21 | ( 22 | RelationshipStatus::Blocked, 23 | RelationshipStatus::BlockedByOther, 24 | ) 25 | }; 26 | 27 | let mut target = id.user().await?; 28 | 29 | user.relations.0.insert(target.id, status.0); 30 | target.relations.0.insert(user.id, status.1); 31 | 32 | let mut tx = pool().begin().await?; 33 | 34 | user.update_tx(&mut tx).await?; 35 | target.update_tx(&mut tx).await?; 36 | 37 | tx.commit().await?; 38 | 39 | user.relationship = status.1.into(); 40 | target.relationship = status.0.into(); 41 | 42 | Payload::UserUpdate(target.clone()).to(user.id).await; 43 | Payload::UserUpdate(user).to(target.id).await; 44 | 45 | Ok(()) 46 | } 47 | -------------------------------------------------------------------------------- /src/routes/users/relationships/delete.rs: -------------------------------------------------------------------------------- 1 | use crate::extractors::*; 2 | use crate::gateway::*; 3 | use crate::structures::*; 4 | use crate::utils::*; 5 | 6 | pub async fn delete(Extension(mut user): Extension, Path(id): Path) -> Result<()> { 7 | let Some(status) = user.relations.0.get(&id) else { Err(Error::UnknownUser)? }; 8 | 9 | // He blocked you. you can't remove it by yourself 10 | if status != &RelationshipStatus::BlockedByOther { 11 | let mut target = id.user().await?; 12 | 13 | if target.relations.0.get(&user.id).unwrap() == &RelationshipStatus::Blocked { 14 | // If you trying to unblock him but he also blocked you thats will happen 15 | user.relations 16 | .0 17 | .insert(target.id, RelationshipStatus::BlockedByOther); 18 | } else { 19 | target.relations.0.remove(&user.id); 20 | user.relations.0.remove(&target.id); 21 | } 22 | 23 | let mut tx = pool().begin().await?; 24 | 25 | user.update_tx(&mut tx).await?; 26 | target.update_tx(&mut tx).await?; 27 | 28 | tx.commit().await?; 29 | 30 | user.relationship = target.relations.0.get(&user.id).copied(); 31 | target.relationship = user.relations.0.get(&target.id).copied(); 32 | 33 | Payload::UserUpdate(target.clone()).to(user.id).await; 34 | Payload::UserUpdate(user).to(target.id).await; 35 | } 36 | 37 | Ok(()) 38 | } 39 | -------------------------------------------------------------------------------- /src/routes/users/relationships/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod add; 2 | pub mod block; 3 | pub mod delete; 4 | 5 | pub fn routes() -> axum::Router { 6 | use axum::{routing::*, Router}; 7 | 8 | Router::new().route( 9 | "/:user_id", 10 | delete(delete::delete).post(add::add).put(block::block), 11 | ) 12 | } 13 | -------------------------------------------------------------------------------- /src/structures/attachment.rs: -------------------------------------------------------------------------------- 1 | use super::Base; 2 | use crate::utils::Snowflake; 3 | use serde::{Deserialize, Serialize}; 4 | use sqlx::{postgres::PgArguments, Arguments, FromRow}; 5 | 6 | #[serde_as] 7 | #[derive(FromRow, Serialize, Deserialize, Debug, OpgModel, Clone)] 8 | pub struct Attachment { 9 | pub id: Snowflake, 10 | pub filename: String, 11 | #[serde(skip_serializing_if = "Option::is_none", default)] 12 | pub width: Option, 13 | #[serde(skip_serializing_if = "Option::is_none", default)] 14 | pub height: Option, 15 | pub content_type: String, 16 | pub size: i32, 17 | #[serde(skip_serializing, default)] 18 | pub deleted: bool, 19 | } 20 | 21 | impl Base<'_, Snowflake> for Attachment { 22 | fn id(&self) -> Snowflake { 23 | self.id 24 | } 25 | 26 | fn table_name() -> &'static str { 27 | "attachments" 28 | } 29 | 30 | fn fields(&self) -> (Vec<&str>, PgArguments) { 31 | let mut values = PgArguments::default(); 32 | 33 | values.add(self.id); 34 | values.add(&self.filename); 35 | values.add(self.width); 36 | values.add(self.height); 37 | values.add(&self.content_type); 38 | values.add(self.size); 39 | values.add(self.deleted); 40 | 41 | ( 42 | vec![ 43 | "id", 44 | "filename", 45 | "width", 46 | "height", 47 | "content_type", 48 | "size", 49 | "deleted", 50 | ], 51 | values, 52 | ) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/structures/base.rs: -------------------------------------------------------------------------------- 1 | use crate::{database::pool, utils::Snowflake}; 2 | use sqlx::{ 3 | postgres::{PgArguments, PgRow}, 4 | Arguments, FromRow, Transaction, 5 | }; 6 | use sqlx::{Encode, Postgres, Type}; 7 | 8 | pub struct SqlQuery { 9 | args: PgArguments, 10 | query: String, 11 | } 12 | 13 | impl SqlQuery { 14 | pub fn new>(query: Q) -> Self { 15 | Self { 16 | args: PgArguments::default(), 17 | query: query.into(), 18 | } 19 | } 20 | 21 | pub fn push<'q, Q>(mut self, arg: Q) -> Self 22 | where 23 | Q: 'q + Encode<'q, Postgres> + Type + Send, 24 | { 25 | self.args.add(arg); 26 | self 27 | } 28 | 29 | pub async fn find<'a, T: Base<'a, Snowflake> + Send>(self) -> Result, sqlx::Error> { 30 | T::find_with_args(self.query, self.args).await 31 | } 32 | 33 | pub async fn find_one<'a, T: Base<'a, Snowflake> + Send>(self) -> Result { 34 | T::find_one_with_args(self.query, self.args).await 35 | } 36 | } 37 | 38 | #[async_trait] 39 | pub trait Base<'q, T: 'q + Encode<'q, Postgres> + Type + Send + ToString + 'q>: 40 | for<'a> FromRow<'a, PgRow> + Sized + Unpin 41 | { 42 | fn id(&self) -> T; 43 | 44 | fn table_name() -> &'static str; 45 | 46 | fn fields(&self) -> (Vec<&str>, PgArguments); 47 | 48 | fn primary_key() -> &'static str { 49 | "id" 50 | } 51 | 52 | async fn update(&self) -> Result<(), sqlx::Error> { 53 | let (columns, args) = self.fields(); 54 | let mut args_placeholders = vec![]; 55 | 56 | let mut i = 1; 57 | 58 | for col in columns { 59 | args_placeholders.push(format!("{col} = ${i}")); 60 | i += 1; 61 | } 62 | 63 | let query = format!( 64 | "UPDATE {} SET {} WHERE {} = ${i}", 65 | Self::table_name(), 66 | args_placeholders.join(","), 67 | Self::primary_key() 68 | ); 69 | 70 | log::debug!("{query}"); 71 | 72 | sqlx::query_with(&query, args).execute(pool()).await?; 73 | 74 | Ok(()) 75 | } 76 | 77 | async fn update_tx(&self, tx: &mut Transaction) -> Result<(), sqlx::Error> { 78 | let (columns, mut args) = self.fields(); 79 | let mut args_placeholders = vec![]; 80 | 81 | let mut i = 1; 82 | 83 | for col in columns { 84 | args_placeholders.push(format!("{col} = ${i}")); 85 | i += 1; 86 | } 87 | 88 | let query = format!( 89 | "UPDATE {} SET {} WHERE {} = ${i}", 90 | Self::table_name(), 91 | args_placeholders.join(","), 92 | Self::primary_key() 93 | ); 94 | 95 | args.add(self.id()); 96 | 97 | log::debug!("{query}"); 98 | 99 | sqlx::query_with(&query, args).execute(tx).await?; 100 | 101 | Ok(()) 102 | } 103 | 104 | async fn insert(&self) -> Result<(), sqlx::Error> { 105 | let (columns, args) = self.fields(); 106 | let mut args_placeholders = vec![]; 107 | 108 | let mut i = 1; 109 | 110 | for _ in 0..columns.len() { 111 | args_placeholders.push(format!("${i}")); 112 | i += 1; 113 | } 114 | 115 | let query = format!( 116 | "INSERT INTO {} ({}) VALUES ({})", 117 | Self::table_name(), 118 | columns.join(","), 119 | args_placeholders.join(",") 120 | ); 121 | 122 | log::debug!("{query}"); 123 | 124 | sqlx::query_with(&query, args).execute(pool()).await?; 125 | 126 | Ok(()) 127 | } 128 | 129 | async fn find + Send, Q>( 130 | filter: TT, 131 | args: Vec, 132 | ) -> Result, sqlx::Error> 133 | where 134 | Q: 'q + Encode<'q, Postgres> + Type + Send, 135 | { 136 | let mut arguments = PgArguments::default(); 137 | 138 | for arg in args { 139 | arguments.add(arg); 140 | } 141 | 142 | Self::find_with_args(filter, arguments).await 143 | } 144 | 145 | async fn find_with_args + Send>( 146 | filter: TT, 147 | arguments: PgArguments, 148 | ) -> Result, sqlx::Error> { 149 | sqlx::query_as_with::<_, Self, _>( 150 | &format!( 151 | "SELECT * FROM {} WHERE {}", 152 | Self::table_name(), 153 | filter.into() 154 | ), 155 | arguments, 156 | ) 157 | .fetch_all(pool()) 158 | .await 159 | } 160 | 161 | async fn find_and_limit + Send, Q>( 162 | filter: TT, 163 | args: Vec, 164 | limit: usize, 165 | ) -> Result, sqlx::Error> 166 | where 167 | Q: 'q + Encode<'q, Postgres> + Type + Send, 168 | { 169 | let mut arguments = PgArguments::default(); 170 | 171 | for arg in args { 172 | arguments.add(arg); 173 | } 174 | 175 | sqlx::query_as_with::<_, Self, _>( 176 | &format!( 177 | "SELECT * FROM {} WHERE {} LIMIT {}", 178 | Self::table_name(), 179 | filter.into(), 180 | limit 181 | ), 182 | arguments, 183 | ) 184 | .fetch_all(pool()) 185 | .await 186 | } 187 | 188 | async fn find_one + Send, Q>( 189 | filter: TT, 190 | args: Vec, 191 | ) -> Result 192 | where 193 | Q: 'q + Encode<'q, Postgres> + Type + Send, 194 | { 195 | let mut arguments = PgArguments::default(); 196 | 197 | for arg in args { 198 | arguments.add(arg); 199 | } 200 | 201 | Self::find_one_with_args(filter, arguments).await 202 | } 203 | 204 | async fn find_one_with_args + Send>( 205 | filter: TT, 206 | arguments: PgArguments, 207 | ) -> Result { 208 | sqlx::query_as_with::<_, Self, _>( 209 | &format!( 210 | "SELECT * FROM {} WHERE {} LIMIT 1", 211 | Self::table_name(), 212 | filter.into() 213 | ), 214 | arguments, 215 | ) 216 | .fetch_one(pool()) 217 | .await 218 | } 219 | 220 | async fn find_by_id(id: Q) -> Result { 221 | sqlx::query_as::<_, Self>(&format!( 222 | "SELECT * FROM {} WHERE {} = {}", 223 | Self::table_name(), 224 | Self::primary_key(), 225 | id.to_string() 226 | )) 227 | .fetch_one(pool()) 228 | .await 229 | } 230 | 231 | async fn count + Send, Q>(filter: TT, args: Vec) -> Result 232 | where 233 | Q: 'q + Encode<'q, Postgres> + Type + Send, 234 | { 235 | let mut arguments = PgArguments::default(); 236 | 237 | for arg in args { 238 | arguments.add(arg); 239 | } 240 | 241 | Ok(sqlx::query_with( 242 | &format!( 243 | "SELECT COUNT(*) FROM {} WHERE {}", 244 | Self::table_name(), 245 | filter.into() 246 | ), 247 | arguments, 248 | ) 249 | .execute(pool()) 250 | .await? 251 | .rows_affected()) 252 | } 253 | 254 | async fn delete(self) -> Result<(), sqlx::Error> { 255 | sqlx::query(&format!( 256 | "DELETE FROM {} WHERE {} = {}", 257 | Self::table_name(), 258 | Self::primary_key(), 259 | self.id().to_string() 260 | )) 261 | .execute(pool()) 262 | .await 263 | .map(|_| ()) 264 | } 265 | 266 | async fn delete_tx(self, tx: &mut Transaction) -> Result<(), sqlx::Error> { 267 | sqlx::query(&format!( 268 | "DELETE FORM {} WHERE {} = {}", 269 | Self::table_name(), 270 | Self::primary_key(), 271 | self.id().to_string() 272 | )) 273 | .execute(tx) 274 | .await 275 | .map(|_| ()) 276 | } 277 | } 278 | -------------------------------------------------------------------------------- /src/structures/bot.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use crate::utils::Snowflake; 3 | use serde::{Deserialize, Serialize}; 4 | use sqlx::{postgres::PgArguments, Arguments, FromRow}; 5 | 6 | #[serde_as] 7 | #[derive(Debug, FromRow, Serialize, Deserialize, Clone, OpgModel)] 8 | pub struct Bot { 9 | pub id: Snowflake, 10 | pub username: String, 11 | pub owner_id: Snowflake, 12 | pub verified: bool, 13 | } 14 | 15 | impl Bot { 16 | pub fn new(username: String, owner_id: Snowflake) -> Self { 17 | Self { 18 | id: Snowflake::generate(), 19 | username, 20 | owner_id, 21 | verified: false, 22 | } 23 | } 24 | 25 | #[cfg(test)] 26 | pub async fn faker() -> Result { 27 | let owner = User::faker(); 28 | let bot = Self::new("Ghost Bot".to_string(), owner.id); 29 | 30 | owner.insert().await?; 31 | 32 | Ok(bot) 33 | } 34 | } 35 | 36 | impl Base<'_, Snowflake> for Bot { 37 | fn id(&self) -> Snowflake { 38 | self.id 39 | } 40 | 41 | fn table_name() -> &'static str { 42 | "bots" 43 | } 44 | 45 | fn fields(&self) -> (Vec<&str>, PgArguments) { 46 | let mut values = PgArguments::default(); 47 | 48 | values.add(self.id); 49 | values.add(&self.username); 50 | values.add(self.owner_id); 51 | values.add(self.verified); 52 | 53 | (vec!["id", "username", "owner_id", "verified"], values) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/structures/channel.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use crate::utils::{Permissions, Snowflake, DEFAULT_PERMISSION_DM}; 3 | use sqlx::{postgres::PgArguments, Arguments, FromRow}; 4 | 5 | use serde::{Deserialize, Serialize}; 6 | use serde_repr::{Deserialize_repr, Serialize_repr}; 7 | 8 | #[derive( 9 | Debug, Serialize_repr, Deserialize_repr, Clone, Copy, PartialEq, Eq, OpgModel, sqlx::Type, 10 | )] 11 | #[repr(i32)] 12 | pub enum ChannelTypes { 13 | Unknown = 0, 14 | Direct = 1, 15 | Group = 2, 16 | } 17 | 18 | impl Default for ChannelTypes { 19 | fn default() -> Self { 20 | Self::Unknown 21 | } 22 | } 23 | 24 | #[serde_as] 25 | #[skip_serializing_none] 26 | #[derive(Serialize, Deserialize, FromRow, Clone, OpgModel, Debug)] 27 | pub struct Channel { 28 | pub id: Snowflake, 29 | 30 | pub r#type: ChannelTypes, 31 | 32 | // Group 33 | pub name: Option, 34 | 35 | // DM/Group 36 | pub recipients: Option>, 37 | 38 | // Group 39 | #[serde(default)] 40 | pub owner_id: Option, 41 | 42 | // Group 43 | pub permissions: Option, 44 | } 45 | 46 | impl Default for Channel { 47 | fn default() -> Self { 48 | Self { 49 | id: Snowflake::generate(), 50 | r#type: ChannelTypes::Unknown, 51 | name: None, 52 | recipients: None, 53 | owner_id: None, 54 | permissions: None, 55 | } 56 | } 57 | } 58 | 59 | impl Channel { 60 | pub fn new_dm(user: Snowflake, target: Snowflake) -> Self { 61 | Self { 62 | r#type: ChannelTypes::Direct, 63 | recipients: Some(vec![user, target]), 64 | ..Default::default() 65 | } 66 | } 67 | 68 | pub fn new_group(user: Snowflake, name: String) -> Self { 69 | Self { 70 | name: name.into(), 71 | r#type: ChannelTypes::Group, 72 | recipients: Some(vec![user]), 73 | owner_id: user.into(), 74 | permissions: Some(*DEFAULT_PERMISSION_DM), 75 | ..Default::default() 76 | } 77 | } 78 | 79 | pub fn is_group(&self) -> bool { 80 | self.r#type == ChannelTypes::Group 81 | } 82 | 83 | pub fn is_dm(&self) -> bool { 84 | self.r#type == ChannelTypes::Direct 85 | } 86 | 87 | pub async fn fetch_messages(&self, limit: usize) -> Result, sqlx::Error> { 88 | Message::find_and_limit("channel_id = $1", vec![self.id], limit).await 89 | } 90 | } 91 | 92 | impl Base<'_, Snowflake> for Channel { 93 | fn id(&self) -> Snowflake { 94 | self.id 95 | } 96 | 97 | fn table_name() -> &'static str { 98 | "channels" 99 | } 100 | 101 | fn fields(&self) -> (Vec<&str>, PgArguments) { 102 | let mut values = PgArguments::default(); 103 | 104 | values.add(self.id); 105 | values.add(self.r#type); 106 | values.add(&self.name); 107 | values.add(&self.recipients); 108 | values.add(self.owner_id); 109 | values.add(self.permissions); 110 | 111 | ( 112 | vec![ 113 | "id", 114 | "type", 115 | "name", 116 | "recipients", 117 | "owner_id", 118 | "permissions", 119 | ], 120 | values, 121 | ) 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/structures/message.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use crate::utils::Snowflake; 3 | use chrono::NaiveDateTime; 4 | use serde::{Deserialize, Serialize}; 5 | use sqlx::types::Json; 6 | use sqlx::{postgres::PgArguments, Arguments, FromRow}; 7 | 8 | #[serde_as] 9 | #[derive(Debug, Serialize, Deserialize, FromRow, Clone, OpgModel)] 10 | pub struct Message { 11 | pub id: Snowflake, 12 | pub content: Option, 13 | pub attachments: Json>, 14 | pub channel_id: Snowflake, 15 | pub author_id: Snowflake, 16 | pub edited_at: Option, 17 | } 18 | 19 | impl Message { 20 | pub fn new(channel_id: Snowflake, author_id: Snowflake) -> Self { 21 | Self { 22 | id: Snowflake::generate(), 23 | content: None, 24 | channel_id, 25 | author_id, 26 | attachments: Json(vec![]), 27 | edited_at: None, 28 | } 29 | } 30 | 31 | pub fn is_empty(&self) -> bool { 32 | self.content.is_none() && self.attachments.0.is_empty() 33 | } 34 | } 35 | 36 | impl Base<'_, Snowflake> for Message { 37 | fn id(&self) -> Snowflake { 38 | self.id 39 | } 40 | 41 | fn table_name() -> &'static str { 42 | "messages" 43 | } 44 | 45 | fn fields(&self) -> (Vec<&str>, sqlx::postgres::PgArguments) { 46 | let mut values = PgArguments::default(); 47 | 48 | values.add(self.id); 49 | values.add(&self.content); 50 | values.add(&self.attachments); 51 | values.add(self.channel_id); 52 | values.add(self.author_id); 53 | values.add(self.edited_at); 54 | 55 | ( 56 | vec![ 57 | "id", 58 | "content", 59 | "attachments", 60 | "channel_id", 61 | "author_id", 62 | "edited_at", 63 | ], 64 | values, 65 | ) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/structures/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod attachment; 2 | pub mod base; 3 | pub mod bot; 4 | pub mod channel; 5 | pub mod message; 6 | pub mod session; 7 | pub mod user; 8 | 9 | pub use crate::database::pool; 10 | pub use crate::utils::Error; 11 | pub use attachment::*; 12 | pub use base::*; 13 | pub use bot::*; 14 | pub use channel::*; 15 | pub use message::*; 16 | pub use session::*; 17 | pub use user::*; 18 | -------------------------------------------------------------------------------- /src/structures/session.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use crate::utils::Snowflake; 3 | use nanoid::nanoid; 4 | use serde::{Deserialize, Serialize}; 5 | use sqlx::{postgres::PgArguments, Arguments, FromRow}; 6 | 7 | #[serde_as] 8 | #[derive(Debug, Serialize, Deserialize, FromRow, Clone, OpgModel)] 9 | pub struct Session { 10 | pub id: Snowflake, 11 | #[serde(skip)] 12 | pub token: String, 13 | #[serde(skip)] 14 | pub user_id: Option, 15 | } 16 | 17 | impl Session { 18 | pub fn new(user_id: Snowflake) -> Self { 19 | Self { 20 | id: Snowflake::generate(), 21 | token: nanoid!(64), 22 | user_id: Some(user_id), 23 | } 24 | } 25 | 26 | #[cfg(test)] 27 | pub async fn faker() -> Result { 28 | let user = User::faker(); 29 | let session = Self::new(user.id); 30 | 31 | user.insert().await?; 32 | 33 | Ok(session) 34 | } 35 | } 36 | 37 | impl Base<'_, Snowflake> for Session { 38 | fn id(&self) -> Snowflake { 39 | self.id 40 | } 41 | 42 | fn table_name() -> &'static str { 43 | "sessions" 44 | } 45 | 46 | fn fields(&self) -> (Vec<&str>, PgArguments) { 47 | let mut values = PgArguments::default(); 48 | 49 | values.add(self.id); 50 | values.add(&self.token); 51 | values.add(self.user_id); 52 | 53 | (vec!["id", "token", "user_id"], values) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/structures/user.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use crate::utils::{Badges, Private, Snowflake}; 3 | use serde::{Deserialize, Serialize}; 4 | use serde_repr::{Deserialize_repr, Serialize_repr}; 5 | use sqlx::types::Json; 6 | use sqlx::{postgres::PgArguments, Arguments, FromRow}; 7 | use std::collections::HashMap; 8 | 9 | #[derive( 10 | Debug, Serialize_repr, Deserialize_repr, Clone, Copy, PartialEq, Eq, OpgModel, sqlx::Type, 11 | )] 12 | #[repr(i32)] 13 | pub enum RelationshipStatus { 14 | Friend = 0, 15 | Incoming = 1, 16 | Outgoing = 2, 17 | Blocked = 3, 18 | BlockedByOther = 4, 19 | } 20 | 21 | #[derive(Debug, Serialize_repr, Deserialize_repr, OpgModel, Clone, PartialEq, Eq)] 22 | #[repr(u8)] 23 | pub enum PresenceStatus { 24 | Offline = 0, 25 | Online = 1, 26 | Idle = 2, 27 | Dnd = 3, 28 | // BirthDay = 4 (coming feature) 29 | } 30 | 31 | #[derive(Serialize, Deserialize, OpgModel, Debug, Clone)] 32 | pub struct Presence { 33 | pub status: PresenceStatus, 34 | pub text: Option, 35 | } 36 | 37 | impl Default for Presence { 38 | fn default() -> Self { 39 | Self { 40 | status: PresenceStatus::Offline, 41 | text: None, 42 | } 43 | } 44 | } 45 | 46 | impl Presence { 47 | pub fn is_online(&self) -> bool { 48 | self.status != PresenceStatus::Offline 49 | } 50 | } 51 | 52 | #[serde_as] 53 | #[derive(Debug, Serialize, Deserialize, FromRow, Clone, OpgModel)] 54 | pub struct User { 55 | pub id: Snowflake, 56 | pub username: String, 57 | pub avatar: Option, 58 | pub badges: Badges, 59 | pub presence: Json, 60 | #[sqlx(default)] 61 | pub relationship: Option, 62 | #[serde(skip_serializing_if = "Private::is_private")] 63 | pub relations: Private>>, 64 | #[serde(skip_serializing_if = "Private::is_private")] 65 | pub email: Private, 66 | #[serde(skip_serializing_if = "Private::is_private")] 67 | pub password: Private, 68 | #[serde(skip_serializing_if = "Private::is_private")] 69 | pub verified: Private, 70 | } 71 | 72 | impl User { 73 | pub fn new(username: String, email: String, password: String) -> Self { 74 | Self { 75 | id: Snowflake::generate(), 76 | username, 77 | email: email.into(), 78 | password: password.into(), 79 | avatar: None, 80 | relationship: None, 81 | verified: false.into(), 82 | presence: Json(Presence::default()), 83 | badges: Badges::default(), 84 | relations: Json(HashMap::new()).into(), 85 | } 86 | } 87 | 88 | pub fn with_hidden_fields(&self) -> Self { 89 | let mut u = self.clone(); 90 | u.verified.set_public(); 91 | u.password.set_public(); 92 | u.email.set_public(); 93 | u.relations.set_public(); 94 | u 95 | } 96 | 97 | pub async fn email_taken(email: &str) -> bool { 98 | User::find_one("email = $1", vec![email]).await.is_ok() 99 | } 100 | 101 | pub async fn fetch_sessions(&self) -> Result, sqlx::Error> { 102 | Session::find("user_id = $1", vec![self.id]).await 103 | } 104 | 105 | pub async fn fetch_bots(&self) -> Result, sqlx::Error> { 106 | Bot::find("owner_id = $1", vec![self.id]).await 107 | } 108 | 109 | pub async fn fetch_channels(&self) -> Result, sqlx::Error> { 110 | Channel::find("recipients @> ARRAY[$1]::BIGINT[]", vec![self.id]).await 111 | } 112 | 113 | pub async fn fetch_relations( 114 | &self, 115 | additional_ids: &mut Vec, 116 | ) -> Result, sqlx::Error> { 117 | let mut ids = self.relations.0.keys().copied().collect::>(); 118 | 119 | ids.append(additional_ids); 120 | 121 | if ids.is_empty() { 122 | return Ok(vec![]); 123 | } 124 | 125 | User::find("id = ANY($1)", vec![ids]).await 126 | } 127 | 128 | pub async fn fetch_by_token(token: &str) -> sqlx::Result { 129 | User::find_one( 130 | "verified = TRUE AND id = ( SELECT user_id FROM sessions WHERE token = $1 )", 131 | vec![token], 132 | ) 133 | .await 134 | } 135 | 136 | #[cfg(test)] 137 | pub fn faker() -> Self { 138 | use argon2::Config; 139 | 140 | let config = Config::default(); 141 | let salt = nanoid::nanoid!(24); 142 | let hashed_password = 143 | argon2::hash_encoded("passw0rd".as_bytes(), salt.as_bytes(), &config).unwrap(); 144 | 145 | let email = format!("ghost.{}@example.com", nanoid::nanoid!(6)); 146 | let mut user = Self::new("Ghost".to_string(), email, hashed_password); 147 | user.verified = true.into(); 148 | user 149 | } 150 | } 151 | 152 | impl Base<'_, Snowflake> for User { 153 | fn id(&self) -> Snowflake { 154 | self.id 155 | } 156 | 157 | fn table_name() -> &'static str { 158 | "users" 159 | } 160 | 161 | fn fields(&self) -> (Vec<&str>, PgArguments) { 162 | let mut values = PgArguments::default(); 163 | 164 | values.add(self.id); 165 | values.add(&self.username); 166 | values.add(&self.avatar); 167 | values.add(&self.badges); 168 | values.add(&self.presence); 169 | values.add(&self.relations); 170 | values.add(&self.email); 171 | values.add(&self.password); 172 | values.add(&self.verified); 173 | 174 | ( 175 | vec![ 176 | "id", 177 | "username", 178 | "avatar", 179 | "badges", 180 | "presence", 181 | "relations", 182 | "email", 183 | "password", 184 | "verified", 185 | ], 186 | values, 187 | ) 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /src/utils/badges.rs: -------------------------------------------------------------------------------- 1 | use bitflags::bitflags; 2 | use serde::{ 3 | de::{Error, Visitor}, 4 | Deserialize, Deserializer, Serialize, Serializer, 5 | }; 6 | use sqlx::{ 7 | encode::IsNull, 8 | error::BoxDynError, 9 | postgres::{PgArgumentBuffer, PgTypeInfo, PgValueRef}, 10 | Decode, Encode, Postgres, Type, 11 | }; 12 | use std::fmt; 13 | 14 | bitflags! { 15 | #[derive(Default)] 16 | pub struct Badges: i64 { 17 | const STAFF = 1 << 1; 18 | const DEVELOPER = 1 << 2; 19 | const SUPPORTER = 1 << 3; 20 | const TRANSLATOR = 1 << 4; 21 | } 22 | } 23 | 24 | impl Type for Badges { 25 | fn type_info() -> PgTypeInfo { 26 | i64::type_info() 27 | } 28 | } 29 | 30 | impl Encode<'_, Postgres> for Badges { 31 | fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull { 32 | Encode::::encode(self.bits(), buf) 33 | } 34 | } 35 | 36 | impl<'r> Decode<'r, Postgres> for Badges { 37 | fn decode(value: PgValueRef<'r>) -> Result { 38 | Ok(Badges::from_bits(Decode::::decode(value)?).unwrap()) 39 | } 40 | } 41 | 42 | impl Serialize for Badges { 43 | fn serialize(&self, serializer: S) -> Result 44 | where 45 | S: Serializer, 46 | { 47 | serializer.collect_str(&self.bits()) 48 | } 49 | } 50 | 51 | struct BadgesVisitor; 52 | 53 | impl<'de> Visitor<'de> for BadgesVisitor { 54 | type Value = Badges; 55 | 56 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 57 | formatter.write_str("a valid badges") 58 | } 59 | 60 | fn visit_string(self, v: String) -> Result 61 | where 62 | E: Error, 63 | { 64 | self.visit_i64(v.parse().map_err(E::custom)?) 65 | } 66 | 67 | fn visit_str(self, v: &str) -> Result 68 | where 69 | E: Error, 70 | { 71 | self.visit_i64(v.parse().map_err(E::custom)?) 72 | } 73 | 74 | fn visit_u64(self, v: u64) -> Result 75 | where 76 | E: Error, 77 | { 78 | self.visit_i64(v as i64) 79 | } 80 | 81 | fn visit_i64(self, v: i64) -> Result 82 | where 83 | E: Error, 84 | { 85 | Badges::from_bits(v).ok_or_else(|| E::custom("Invalid bits")) 86 | } 87 | } 88 | 89 | impl<'de> Deserialize<'de> for Badges { 90 | fn deserialize(deserializer: D) -> Result 91 | where 92 | D: Deserializer<'de>, 93 | { 94 | deserializer.deserialize_i64(BadgesVisitor) 95 | } 96 | } 97 | 98 | use opg::{Components, Model, ModelData, ModelString, ModelType, ModelTypeDescription, OpgModel}; 99 | 100 | impl OpgModel for Badges { 101 | fn get_schema(_cx: &mut Components) -> Model { 102 | Model { 103 | description: "Badges bits".to_string().into(), 104 | data: ModelData::Single(ModelType { 105 | nullable: false, 106 | type_description: ModelTypeDescription::String(ModelString::default()), 107 | }), 108 | } 109 | } 110 | 111 | fn type_name() -> Option> { 112 | None 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/utils/email.rs: -------------------------------------------------------------------------------- 1 | use crate::config::*; 2 | use crate::database::redis::*; 3 | use crate::structures::{Base, User}; 4 | use crate::utils::Snowflake; 5 | use lazy_regex::regex; 6 | 7 | use serde_json::json; 8 | use sqlx::types::Uuid; 9 | use sqlx::{postgres::PgArguments, Arguments, FromRow}; 10 | 11 | const THREE_HOURS_IN_SECONDS: i64 = 10800; 12 | 13 | #[derive(FromRow)] 14 | pub struct AccountInvite { 15 | pub code: Uuid, 16 | pub used: bool, 17 | pub taken_by: Option, 18 | } 19 | 20 | impl Base<'_, Uuid> for AccountInvite { 21 | fn id(&self) -> Uuid { 22 | self.code 23 | } 24 | 25 | fn primary_key() -> &'static str { 26 | "code" 27 | } 28 | 29 | fn fields(&self) -> (Vec<&str>, PgArguments) { 30 | let mut values = PgArguments::default(); 31 | 32 | values.add(self.code); 33 | values.add(self.used); 34 | values.add(self.taken_by); 35 | 36 | (vec!["code", "used", "taken_by"], values) 37 | } 38 | 39 | fn table_name() -> &'static str { 40 | "account_invites" 41 | } 42 | } 43 | 44 | pub fn normalize(email: String) -> Option { 45 | let split = regex!("([^@]+)(@.+)").captures(&email)?; 46 | let mut clean = regex!("\\+.+|\\.") 47 | .replace_all(split.get(1)?.as_str(), "") 48 | .to_string(); 49 | clean.push_str(split.get(2)?.as_str()); 50 | 51 | Some(clean.to_lowercase()) 52 | } 53 | 54 | pub async fn send(user: &User) -> bool { 55 | let mut content = include_str!("../../assets/templates/verify.html").to_string(); 56 | let code = Uuid::new_v4(); 57 | 58 | content = content 59 | .replace("%%EMAIL%%", &user.email) 60 | .replace("%%CODE%%", &code.to_string()) 61 | .replace("%%USER_ID%%", &user.id.to_string()); 62 | 63 | let body = json!({ 64 | "subject": "Verify your ItChat account", 65 | "sender": { "email": "noreply@itchat.world" }, 66 | "to": [{ "email": user.email }], 67 | "type": "classic", 68 | "htmlContent": content, 69 | }); 70 | 71 | let res = reqwest::Client::new() 72 | .post("https://api.sendinblue.com/v3/smtp/email") 73 | .header("api-key", (*SENDINBLUE_API_KEY).clone()) 74 | .header("Content-Type", "application/json") 75 | .header("Accept", "application/json") 76 | .body(body.to_string()) 77 | .send() 78 | .await; 79 | 80 | if res.map(|r| r.status().is_success()).unwrap_or(false) { 81 | REDIS 82 | .set::<(), _, _>( 83 | *user.id, 84 | code.to_string(), 85 | Expiration::EX(THREE_HOURS_IN_SECONDS).into(), 86 | None, 87 | false, 88 | ) 89 | .await 90 | .is_ok() 91 | } else { 92 | false 93 | } 94 | } 95 | 96 | pub async fn verify(user_id: Snowflake, code: Uuid) -> bool { 97 | match REDIS.get::(user_id.to_string()).await { 98 | Ok(token) if code.to_string() == token => { 99 | REDIS.del::(user_id.to_string()).await.ok(); 100 | true 101 | } 102 | _ => false, 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/utils/error.rs: -------------------------------------------------------------------------------- 1 | use super::Permissions; 2 | use crate::middlewares::ratelimit::RateLimitInfo; 3 | use axum::{ 4 | extract::rejection::JsonRejection, 5 | http::{HeaderMap, StatusCode}, 6 | response::{IntoResponse, Json, Response}, 7 | }; 8 | use quick_error::quick_error; 9 | use serde::Serialize; 10 | use std::fmt::Debug; 11 | 12 | quick_error! { 13 | #[derive(Debug, Serialize, OpgModel)] 14 | #[serde(tag = "type", rename_all = "snake_case")] 15 | pub enum Error { 16 | RateLimited(info: RateLimitInfo) { 17 | from(RateLimitInfo) 18 | display("Executed the rate limit. Please retry after {}s", info.retry_after) 19 | } 20 | InvalidBody { display("You have provided a bad json schema") } 21 | InternalError { display("Internal server error") } 22 | MissingHeader { display("Missing header") } 23 | AccountVerificationRequired { display("You need to verify your account in order to perform this action") } 24 | InvalidToken { display("Unauthorized. Provide a valid token and try again") } 25 | EmailAlreadyInUse { display("This email already in use") } 26 | 27 | MissingPermissions(missing: Permissions) { 28 | display("You lack permissions to perform that action, missing: {}", missing.bits()) 29 | } 30 | 31 | EmptyMessage { display("Cannot send an empty message") } 32 | RequireInviteCode { display("You must have an invite code to perform this action") } 33 | InviteAlreadyTaken { display("This invite already used") } 34 | FailedCaptcha { display("Respect the captcha, Respect you") } 35 | MissingAccess { display("You missing access to perform this action ") } 36 | DatabaseError { display("Database cannot process this operation") } 37 | 38 | 39 | Blocked 40 | BlockedByOther 41 | AlreadyFriends 42 | AlreadySendRequest 43 | 44 | UnknownAccount 45 | UnknownBot 46 | UnknownChannel 47 | UnknownInvite 48 | UnknownUser 49 | UnknownMessage 50 | UnknownSession 51 | UnknownMember 52 | Unknown { display("Unknown error has occurred") } 53 | 54 | MaximumFriends { display("Maximum number of friends reached") } 55 | MaximumGroups { display("Maximum number of groups reached") } 56 | MaximumRoles { display("Maximum number of server roles reached") } 57 | MaximumChannels { display("Maximum number of channels reached") } 58 | MaximumGroupMembers { display("Maximum number of group members reached") } 59 | MaximumBots { display("Maximum number of bots reached") } 60 | MaximumFriendRequests { display("Maximum number of friend requests reached") } 61 | MaximumBlocked { display("Maximum number of blocked user reached") } 62 | } 63 | } 64 | 65 | pub type Result = std::result::Result; 66 | 67 | impl From for Error { 68 | fn from(err: sqlx::Error) -> Self { 69 | log::error!("Database Error: {}", err); 70 | Self::DatabaseError 71 | } 72 | } 73 | 74 | impl From for Error { 75 | fn from(err: axum::Error) -> Self { 76 | log::error!("{err}"); 77 | Self::InternalError 78 | } 79 | } 80 | 81 | impl From for Error { 82 | fn from(_: JsonRejection) -> Self { 83 | Self::InvalidBody 84 | } 85 | } 86 | 87 | impl From for Error { 88 | fn from(_: rmp_serde::encode::Error) -> Self { 89 | Self::Unknown 90 | } 91 | } 92 | 93 | impl IntoResponse for Error { 94 | fn into_response(self) -> Response { 95 | let status = match self { 96 | Error::RateLimited { .. } => StatusCode::TOO_MANY_REQUESTS, 97 | Error::InvalidToken => StatusCode::UNAUTHORIZED, 98 | Error::InvalidBody => StatusCode::UNPROCESSABLE_ENTITY, 99 | _ => StatusCode::BAD_REQUEST, 100 | }; 101 | 102 | let mut headers = HeaderMap::new(); 103 | let mut body = serde_json::json!(self); 104 | let msg = self.to_string(); 105 | 106 | if msg.contains(' ') { 107 | body["message"] = msg.into(); 108 | } 109 | 110 | if let Error::RateLimited(info) = self { 111 | headers.insert("X-RateLimit-Remaining", info.remaining.into()); 112 | headers.insert("X-RateLimit-Limit", info.limit.into()); 113 | headers.insert("Retry-After", info.retry_after.into()); 114 | } 115 | 116 | (status, headers, Json(body)).into_response() 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/utils/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod badges; 2 | pub mod email; 3 | pub mod error; 4 | pub mod permissions; 5 | pub mod r#ref; 6 | pub mod snowflake; 7 | pub mod types; 8 | 9 | pub use self::snowflake::Snowflake; 10 | pub use ::snowflake::*; 11 | pub use badges::*; 12 | pub use error::*; 13 | pub use permissions::*; 14 | pub use r#ref::*; 15 | pub use types::*; 16 | -------------------------------------------------------------------------------- /src/utils/permissions.rs: -------------------------------------------------------------------------------- 1 | use crate::structures::*; 2 | use crate::utils::{Error, Ref, Result, Snowflake}; 3 | use bitflags::bitflags; 4 | use serde::{ 5 | de::{Error as SerdeError, Visitor}, 6 | Deserialize, Deserializer, Serialize, Serializer, 7 | }; 8 | use sqlx::{ 9 | encode::IsNull, 10 | error::BoxDynError, 11 | postgres::{PgArgumentBuffer, PgTypeInfo, PgValueRef}, 12 | Decode, Encode, Postgres, Type, 13 | }; 14 | use std::fmt; 15 | 16 | bitflags! { 17 | #[derive(Default)] 18 | pub struct Permissions: i64 { 19 | const VIEW_CHANNEL = 1 << 0; 20 | const SEND_MESSAGES = 1 << 1; 21 | const READ_MESSAGE_HISTORY = 1 << 2; 22 | const EMBED_LINKS = 1 << 3; 23 | const UPLOAD_FILES = 1 << 4; 24 | const MANAGE_SERVER = 1 << 5; 25 | const MANAGE_CHANNELS = 1 << 6; 26 | const MANAGE_MESSAGES = 1 << 7; 27 | const MANAGE_ROLES = 1 << 8; 28 | const MANAGE_INVITES = 1 << 9; 29 | const MANAGE_NICKNAMES = 1 << 10; 30 | const BAN_MEMBERS = 1 << 11; 31 | const KICK_MEMBERS = 1 << 12; 32 | const CHANGE_NICKNAME = 1 << 13; 33 | const INVITE_OTHERS = 1 << 14; 34 | } 35 | } 36 | 37 | macro_rules! bits { 38 | (ALL) => {{ Permissions::all() }}; 39 | ($flag:ident) => {{ Permissions::$flag }}; 40 | ($($flag:ident),*) => {{ 41 | #[allow(unused_mut)] 42 | let mut bits = Permissions::default(); 43 | $( bits.insert(Permissions::$flag); )* 44 | bits 45 | }}; 46 | } 47 | 48 | pub(crate) use bits; 49 | 50 | lazy_static! { 51 | pub static ref DEFAULT_PERMISSION_DM: Permissions = bits![ 52 | VIEW_CHANNEL, 53 | SEND_MESSAGES, 54 | EMBED_LINKS, 55 | UPLOAD_FILES, 56 | READ_MESSAGE_HISTORY 57 | ]; 58 | pub static ref DEFAULT_PERMISSION_EVERYONE: Permissions = bits![ 59 | VIEW_CHANNEL, 60 | SEND_MESSAGES, 61 | EMBED_LINKS, 62 | UPLOAD_FILES, 63 | READ_MESSAGE_HISTORY 64 | ]; 65 | } 66 | 67 | impl Permissions { 68 | pub async fn fetch_cached(user: &User, channel: Option<&Channel>) -> Result { 69 | let mut p = bits![]; 70 | 71 | if let Some(channel) = channel { 72 | if p.is_all() { 73 | return Ok(p); 74 | } 75 | 76 | if channel.is_dm() { 77 | p.insert(*DEFAULT_PERMISSION_DM); 78 | 79 | let recipients = channel.recipients.as_ref().unwrap(); 80 | let is_notes = recipients[0] == recipients[1]; 81 | 82 | if !is_notes 83 | && user 84 | .relations 85 | .0 86 | .get(&recipients[1]) 87 | .map(|s| s != &RelationshipStatus::Friend) 88 | .unwrap_or(false) 89 | { 90 | p.remove(bits![SEND_MESSAGES]); 91 | } 92 | } 93 | 94 | if channel.is_group() { 95 | // for group owners 96 | if channel.owner_id == Some(user.id) { 97 | p = bits![ALL]; 98 | return Ok(p); 99 | } 100 | 101 | p.insert(channel.permissions.unwrap()); 102 | } 103 | } 104 | 105 | Ok(p) 106 | } 107 | 108 | pub async fn fetch(user: &User, channel_id: Option) -> Result { 109 | let channel = if let Some(channel_id) = channel_id { 110 | Some(channel_id.channel(None).await?) 111 | } else { 112 | None 113 | }; 114 | 115 | Permissions::fetch_cached(user, channel.as_ref()).await 116 | } 117 | 118 | pub fn has(self, bits: Permissions) -> Result<()> { 119 | if self.is_all() { 120 | return Ok(()); 121 | } 122 | 123 | if !self.contains(bits) { 124 | return Err(Error::MissingPermissions(self.difference(bits))); 125 | } 126 | 127 | Ok(()) 128 | } 129 | } 130 | 131 | impl Type for Permissions { 132 | fn type_info() -> PgTypeInfo { 133 | i64::type_info() 134 | } 135 | } 136 | 137 | impl Encode<'_, Postgres> for Permissions { 138 | fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull { 139 | i64::encode(self.bits(), buf) 140 | } 141 | } 142 | 143 | impl<'r> Decode<'r, Postgres> for Permissions { 144 | fn decode(value: PgValueRef<'r>) -> Result { 145 | Ok(Permissions::from_bits(i64::decode(value)?).unwrap()) 146 | } 147 | } 148 | 149 | impl Serialize for Permissions { 150 | fn serialize(&self, serializer: S) -> Result { 151 | serializer.collect_str(&self.bits()) 152 | } 153 | } 154 | 155 | struct PermissionsVisitor; 156 | 157 | impl<'de> Visitor<'de> for PermissionsVisitor { 158 | type Value = Permissions; 159 | 160 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 161 | formatter.write_str("a valid permissions") 162 | } 163 | 164 | fn visit_string(self, v: String) -> Result 165 | where 166 | E: SerdeError, 167 | { 168 | self.visit_str(&v) 169 | } 170 | 171 | fn visit_str(self, v: &str) -> Result 172 | where 173 | E: SerdeError, 174 | { 175 | self.visit_i64(v.parse().map_err(E::custom)?) 176 | } 177 | 178 | fn visit_u64(self, v: u64) -> Result 179 | where 180 | E: SerdeError, 181 | { 182 | self.visit_i64(v as i64) 183 | } 184 | 185 | fn visit_i64(self, v: i64) -> Result 186 | where 187 | E: SerdeError, 188 | { 189 | Permissions::from_bits(v).ok_or_else(|| E::custom("Invalid bits")) 190 | } 191 | } 192 | 193 | impl<'de> Deserialize<'de> for Permissions { 194 | fn deserialize(deserializer: D) -> Result 195 | where 196 | D: Deserializer<'de>, 197 | { 198 | deserializer.deserialize_any(PermissionsVisitor) 199 | } 200 | } 201 | 202 | use opg::{Components, Model, ModelData, ModelString, ModelType, ModelTypeDescription, OpgModel}; 203 | 204 | impl OpgModel for Permissions { 205 | fn get_schema(_cx: &mut Components) -> Model { 206 | Model { 207 | description: "Permissions bits".to_string().into(), 208 | data: ModelData::Single(ModelType { 209 | nullable: false, 210 | type_description: ModelTypeDescription::String(ModelString::default()), 211 | }), 212 | } 213 | } 214 | 215 | fn type_name() -> Option> { 216 | None 217 | } 218 | } 219 | 220 | #[cfg(test)] 221 | mod tests { 222 | use super::*; 223 | 224 | #[test] 225 | fn all() { 226 | assert!(bits![ALL].is_all()); 227 | } 228 | 229 | #[test] 230 | fn default() { 231 | assert_eq!(bits![], Permissions::default()); 232 | } 233 | 234 | #[test] 235 | fn one_parameter() { 236 | assert!(Permissions::VIEW_CHANNEL.contains(bits![VIEW_CHANNEL])); 237 | } 238 | 239 | #[test] 240 | fn multiple_parameters() { 241 | let p = Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES; 242 | assert!(p.contains(bits![VIEW_CHANNEL, SEND_MESSAGES])); 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /src/utils/ref.rs: -------------------------------------------------------------------------------- 1 | use crate::structures::*; 2 | use crate::utils::error::*; 3 | use crate::utils::Snowflake; 4 | 5 | #[async_trait] 6 | pub trait Ref { 7 | fn id(&self) -> Snowflake; 8 | 9 | async fn user(&self) -> Result { 10 | User::find_by_id(self.id()) 11 | .await 12 | .map_err(|_| Error::UnknownUser) 13 | } 14 | 15 | async fn channel(&self, recipient: Option) -> Result { 16 | let channel = if let Some(recipient) = recipient { 17 | Channel::find_one( 18 | "id = $1 AND recipients @> ARRAY[$2]::BIGINT[]", 19 | vec![self.id(), recipient], 20 | ) 21 | .await 22 | } else { 23 | Channel::find_by_id(self.id()).await 24 | }; 25 | 26 | channel.map_err(|_| Error::UnknownChannel) 27 | } 28 | 29 | async fn message(&self) -> Result { 30 | Message::find_by_id(self.id()) 31 | .await 32 | .map_err(|_| Error::UnknownMessage) 33 | } 34 | 35 | async fn session(&self, user_id: Snowflake) -> Result { 36 | Session::find_one("id = $1 AND user_id = $2", vec![self.id(), user_id]) 37 | .await 38 | .map_err(|_| Error::UnknownSession) 39 | } 40 | 41 | async fn bot(&self) -> Result { 42 | Bot::find_by_id(self.id()) 43 | .await 44 | .map_err(|_| Error::UnknownBot) 45 | } 46 | } 47 | 48 | impl Ref for Snowflake { 49 | fn id(&self) -> Snowflake { 50 | *self 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/utils/snowflake.rs: -------------------------------------------------------------------------------- 1 | use chrono::{DateTime, TimeZone, Utc}; 2 | use serde::{Deserialize, Serialize}; 3 | use snowflake::SnowflakeIdGenerator; 4 | use sqlx::postgres::{PgHasArrayType, PgTypeInfo}; 5 | use sqlx::Type; 6 | use std::sync::Mutex; 7 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; 8 | 9 | lazy_static! { 10 | // Fri, 01 Jan 2021 00:00:00 GMT 11 | static ref EPOCH: SystemTime = UNIX_EPOCH + Duration::from_millis(1609459200000); 12 | 13 | static ref GENERATOR: Mutex = Mutex::new(SnowflakeIdGenerator::with_epoch(0, 0, *EPOCH)); 14 | } 15 | 16 | #[serde_as] 17 | #[derive(Type, Serialize, Deserialize, opg::OpgModel, Clone, Copy, PartialEq, Eq, Debug, Hash)] 18 | #[sqlx(transparent)] 19 | #[opg(string)] 20 | pub struct Snowflake(#[serde_as(as = "serde_with::DisplayFromStr")] pub i64); 21 | 22 | impl Snowflake { 23 | pub fn generate() -> Self { 24 | Self(GENERATOR.lock().unwrap().generate()) 25 | } 26 | 27 | pub fn created_at_timestamp(&self) -> Duration { 28 | Duration::from_millis((**self >> 22) as u64) + EPOCH.duration_since(UNIX_EPOCH).unwrap() 29 | } 30 | 31 | pub fn created_at(&self) -> DateTime { 32 | Utc.timestamp_opt(self.created_at_timestamp().as_secs() as i64, 0) 33 | .unwrap() 34 | } 35 | } 36 | 37 | impl ToString for Snowflake { 38 | fn to_string(&self) -> String { 39 | self.0.to_string() 40 | } 41 | } 42 | 43 | impl std::ops::Deref for Snowflake { 44 | type Target = i64; 45 | 46 | fn deref(&self) -> &Self::Target { 47 | &self.0 48 | } 49 | } 50 | 51 | impl PgHasArrayType for Snowflake { 52 | fn array_type_info() -> PgTypeInfo { 53 | i64::array_type_info() 54 | } 55 | 56 | fn array_compatible(_: &PgTypeInfo) -> bool { 57 | true 58 | } 59 | } 60 | 61 | impl TryFrom for Snowflake { 62 | type Error = std::num::ParseIntError; 63 | 64 | fn try_from(value: String) -> Result { 65 | Ok(Snowflake(value.parse()?)) 66 | } 67 | } 68 | 69 | #[cfg(test)] 70 | mod tests { 71 | use super::*; 72 | use std::thread::sleep; 73 | 74 | #[test] 75 | fn test_snowflake_generate() { 76 | let id = Snowflake::generate(); 77 | assert!(id.is_positive()); 78 | } 79 | 80 | #[test] 81 | fn test_snowflake_created_at() { 82 | let id = Snowflake::generate(); 83 | 84 | sleep(Duration::from_millis(100)); 85 | 86 | let now = Utc::now(); 87 | 88 | assert!(id.created_at() < now); 89 | assert!((id.created_at_timestamp().as_millis() as i64) < now.timestamp_millis()); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/utils/types.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use sqlx::{encode::IsNull, error::BoxDynError, postgres::*, Decode, Encode, Postgres, Type}; 3 | 4 | #[derive(Clone, Debug, Serialize, Deserialize)] 5 | #[serde(untagged)] 6 | pub enum Private { 7 | Hidden(T), 8 | Shown(T), 9 | } 10 | 11 | impl> Type for Private { 12 | fn type_info() -> PgTypeInfo { 13 | T::type_info() 14 | } 15 | 16 | fn compatible(ty: &PgTypeInfo) -> bool { 17 | T::compatible(ty) 18 | } 19 | } 20 | 21 | impl<'a, T: Encode<'a, Postgres>> Encode<'_, Postgres> for Private { 22 | fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull { 23 | T::encode_by_ref(self, buf) 24 | } 25 | } 26 | 27 | impl<'r, T: Decode<'r, Postgres>> Decode<'r, Postgres> for Private { 28 | fn decode(value: PgValueRef<'r>) -> Result { 29 | // By default the value is hidden 30 | T::decode(value).map(|v| Self::Hidden(v)) 31 | } 32 | } 33 | 34 | impl From for Private { 35 | fn from(d: T) -> Self { 36 | Self::Hidden(d) 37 | } 38 | } 39 | 40 | impl Default for Private { 41 | fn default() -> Self { 42 | Self::Hidden(T::default()) 43 | } 44 | } 45 | 46 | impl Private { 47 | pub fn is_private(&self) -> bool { 48 | matches!(self, Private::Hidden(_)) 49 | } 50 | 51 | pub fn set_public(&mut self) { 52 | *self = Self::Shown((**self).clone()); 53 | } 54 | 55 | pub fn set_private(&mut self) { 56 | *self = Self::Hidden((**self).clone()); 57 | } 58 | } 59 | 60 | impl std::ops::Deref for Private { 61 | type Target = T; 62 | 63 | fn deref(&self) -> &Self::Target { 64 | match self { 65 | Self::Hidden(x) | Self::Shown(x) => x, 66 | } 67 | } 68 | } 69 | 70 | impl std::ops::DerefMut for Private { 71 | fn deref_mut(&mut self) -> &mut Self::Target { 72 | match self { 73 | Self::Hidden(x) | Self::Shown(x) => x, 74 | } 75 | } 76 | } 77 | 78 | impl_opg_model!(generic_simple: Private); 79 | --------------------------------------------------------------------------------