├── .github ├── dependabot.yml └── workflows │ ├── release-by-label-linux.yml │ ├── release-by-label.yml │ ├── release-manual.yml │ ├── rust-by-gh.yml │ └── test.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── VERSION ├── help.help.txt ├── help.manual.txt ├── help.usage.txt ├── logos └── matrix-commander-rs.svg ├── rustfmt.toml ├── screenshots ├── matrix-commander-rs-screenshot.png └── screenshot.png ├── scripts ├── clean-local.sh ├── create-help-help.sh ├── create-help-manual.sh ├── create-help-usage.sh ├── matrix-commander-rs-tui ├── path-adjust.sh ├── update-1-version.sh ├── update-2-help-manual.py ├── update-5-tag.sh ├── workflow-outline.txt └── workflow.sh ├── src ├── emoji_verify.rs ├── listen.rs ├── main.rs └── mclient.rs └── tests ├── test-devices.sh ├── test-get-display-name.sh ├── test-get-profile.sh ├── test-rooms.sh ├── test-send.sh ├── test-version.sh ├── test.l.jpg ├── test.s.jpg ├── test.s.png └── test.s.svg /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Set update schedule for each package manager 2 | 3 | version: 2 4 | updates: 5 | 6 | - package-ecosystem: "github-actions" 7 | directory: "/" 8 | schedule: 9 | # Check for updates to GitHub Actions every weekday 10 | interval: "daily" 11 | 12 | - package-ecosystem: "cargo" 13 | directory: "/" 14 | schedule: 15 | # Check for updates managed by Composer once a week 16 | interval: "weekly" 17 | -------------------------------------------------------------------------------- /.github/workflows/release-by-label-linux.yml: -------------------------------------------------------------------------------- 1 | # .github/workflow/release-by-label.yml 2 | 3 | # automatically perform release when a version tag is pushed via git 4 | 5 | name: "tagged-release-linux-only" 6 | 7 | on: 8 | # For the time being, disable "push tag" so that only 1 action fires 9 | # We don't want both actions to fire, the other action now covers std. Linux as well. 10 | # push: 11 | # tags: 12 | # - "v*" 13 | workflow_dispatch: 14 | inputs: 15 | tag_name: 16 | description: 'Tag name for release' 17 | required: false 18 | default: nightly 19 | # push: 20 | # branches: [ "main" ] 21 | # pull_request: 22 | # branches: [ "main" ] 23 | 24 | 25 | env: 26 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 27 | CARGO_TERM_COLOR: always 28 | 29 | jobs: 30 | tagname: 31 | runs-on: ubuntu-latest 32 | outputs: 33 | tag_name: ${{ steps.tag.outputs.tag }} 34 | steps: 35 | - if: github.event_name == 'workflow_dispatch' 36 | run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV 37 | 38 | - if: github.event_name == 'push' 39 | run: | 40 | TAG_NAME=${{ github.ref }} 41 | echo "TAG_NAME=${TAG_NAME#refs/tags/}" >> $GITHUB_ENV 42 | - id: vars 43 | shell: bash 44 | run: echo "sha_short=${GITHUB_SHA::7}" >> $GITHUB_OUTPUT 45 | 46 | - if: env.TAG_NAME == 'nightly' 47 | run: echo 'TAG_NAME=nightly-${{ steps.vars.outputs.sha_short }}' >> $GITHUB_ENV 48 | 49 | - id: tag 50 | run: echo "tag=$TAG_NAME" >> $GITHUB_OUTPUT 51 | 52 | linux: 53 | runs-on: ubuntu-latest 54 | container: ubuntu:24.04 55 | needs: tagname 56 | env: 57 | RELEASE_TAG_NAME: ${{ needs.tagname.outputs.tag_name }} 58 | DEBIAN_FRONTEND: noninteractive 59 | 60 | steps: 61 | - uses: actions/checkout@v4 62 | 63 | - if: github.event_name == 'workflow_dispatch' 64 | run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV 65 | 66 | - if: github.event_name == 'schedule' 67 | run: echo 'TAG_NAME=nightly' >> $GITHUB_ENV 68 | 69 | - if: github.event_name == 'push' 70 | run: | 71 | TAG_NAME=${{ github.ref }} 72 | echo "TAG_NAME=${TAG_NAME#refs/tags/}" >> $GITHUB_ENV 73 | 74 | - name: Install dependencies 75 | run: | 76 | apt-get -y update 77 | apt-get -y install cmake pkg-config libfontconfig-dev libgtk-3-dev libssl-dev libolm-dev libc6 curl wget 78 | 79 | - name: Install Rust toolchain 80 | uses: actions-rs/toolchain@v1 81 | with: 82 | toolchain: stable 83 | target: x86_64-unknown-linux-gnu 84 | profile: minimal 85 | 86 | - name: Build 87 | run: cargo build --profile release --bin matrix-commander-rs 88 | 89 | - name: Gzip 90 | run: | 91 | mkdir matrix-commander-rs 92 | cp ./target/release/matrix-commander-rs matrix-commander-rs/ 93 | cp README.md matrix-commander-rs/ 94 | cp LICENSE matrix-commander-rs/ 95 | cp help.help.txt help.manual.txt help.usage.txt matrix-commander-rs/ 96 | tar -zcvf ./matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_linux.tar.gz matrix-commander-rs 97 | # tar -zcvf ./matrix-commander-rs_linux.tar.gz matrix-commander-rs 98 | sha256sum ./matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_linux.tar.gz > ./matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_linux.tar.gz.sha256sum 99 | echo "sha256 checksum: " 100 | # cat ./matrix-commander-rs_${TAG_NAME}_linux.tar.gz.sha256sum 101 | cat ./matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_linux.tar.gz.sha256sum 102 | ls 103 | ls -l 104 | echo ${TAG_NAME} > tag.txt 105 | cat tag.txt 106 | - uses: actions/upload-artifact@v4 107 | with: 108 | name: plain-linux 109 | path: | 110 | ./matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_linux.tar.gz 111 | ./matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_linux.tar.gz.sha256sum 112 | retention-days: 1 113 | 114 | # https://github.com/softprops/action-gh-release 115 | - name: Release 116 | # run: | 117 | # ls 118 | # TAG_NAME=$(cat tag.txt) 119 | # cat tag.txt 120 | # echo $TAG_NAME 121 | uses: "softprops/action-gh-release@v2" 122 | if: startsWith(github.ref, 'refs/tags/') 123 | with: 124 | token: "${{ secrets.GITHUB_TOKEN }}" 125 | prerelease: false 126 | generate_release_notes: true 127 | files: | 128 | ./matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_linux.tar.gz 129 | ./matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_linux.tar.gz.sha256sum 130 | README.md 131 | LICENSE 132 | help.help.txt help.manual.txt help.usage.txt 133 | -------------------------------------------------------------------------------- /.github/workflows/release-by-label.yml: -------------------------------------------------------------------------------- 1 | # .github/workflow/release-by-label.yml 2 | 3 | # automatically perform release when a version tag is pushed via git 4 | 5 | name: "tagged-release" 6 | 7 | on: 8 | # TURNED IT OFF IN SEPT 2024 9 | # fires when there is a git push with version tag 10 | # push: 11 | # tags: 12 | # - "v*" 13 | workflow_dispatch: 14 | inputs: 15 | tag_name: 16 | description: 'Tag name for release' 17 | required: false 18 | default: nightly 19 | # push: 20 | # branches: [ "main" ] 21 | # pull_request: 22 | # branches: [ "main" ] 23 | 24 | 25 | env: 26 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 27 | CARGO_TERM_COLOR: always 28 | 29 | jobs: 30 | tagname: 31 | runs-on: ubuntu-latest 32 | outputs: 33 | tag_name: ${{ steps.tag.outputs.tag }} 34 | steps: 35 | - if: github.event_name == 'workflow_dispatch' 36 | run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV 37 | 38 | - if: github.event_name == 'push' 39 | run: | 40 | TAG_NAME=${{ github.ref }} 41 | echo "TAG_NAME=${TAG_NAME#refs/tags/}" >> $GITHUB_ENV 42 | - id: vars 43 | shell: bash 44 | run: echo "sha_short=${GITHUB_SHA::7}" >> $GITHUB_OUTPUT 45 | 46 | - if: env.TAG_NAME == 'nightly' 47 | run: echo 'TAG_NAME=nightly-${{ steps.vars.outputs.sha_short }}' >> $GITHUB_ENV 48 | 49 | - id: tag 50 | run: echo "tag=$TAG_NAME" >> $GITHUB_OUTPUT 51 | 52 | tagged-release: 53 | name: "Tagged Release" 54 | runs-on: "ubuntu-latest" 55 | needs: tagname 56 | container: ubuntu:24.04 57 | env: 58 | RELEASE_TAG_NAME: ${{ needs.tagname.outputs.tag_name }} 59 | DEBIAN_FRONTEND: noninteractive 60 | 61 | steps: 62 | - uses: actions/checkout@v4 63 | 64 | - if: github.event_name == 'workflow_dispatch' 65 | run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV 66 | 67 | - if: github.event_name == 'schedule' 68 | run: echo 'TAG_NAME=nightly' >> $GITHUB_ENV 69 | 70 | - if: github.event_name == 'push' 71 | run: | 72 | TAG_NAME=${{ github.ref }} 73 | echo "TAG_NAME=${TAG_NAME#refs/tags/}" >> $GITHUB_ENV 74 | 75 | - name: Install dependencies 76 | run: | 77 | apt-get -y update 78 | apt-get -y install cmake pkg-config libfontconfig-dev libgtk-3-dev libssl-dev libolm-dev rename libc6 79 | 80 | - name: Install Rust toolchain 81 | uses: actions-rs/toolchain@v1 82 | with: 83 | toolchain: stable 84 | target: x86_64-unknown-linux-gnu 85 | profile: minimal 86 | 87 | - name: Build 88 | run: cargo build --profile release --bin matrix-commander-rs 89 | 90 | - name: Gzip 91 | run: | 92 | mkdir matrix-commander-rs 93 | cp ./target/release/matrix-commander-rs matrix-commander-rs/ 94 | cp README.md matrix-commander-rs/ 95 | cp LICENSE matrix-commander-rs/ 96 | cp help.help.txt matrix-commander-rs/ 97 | cp help.manual.txt matrix-commander-rs/ 98 | cp help.usage.txt matrix-commander-rs/ 99 | tar -zcvf ./matrix-commander-rs_${TAG_NAME}_linux.tar.gz matrix-commander-rs 100 | # tar -zcvf ./matrix-commander-rs_linux.tar.gz matrix-commander-rs 101 | sha256sum ./matrix-commander-rs_${TAG_NAME}_linux.tar.gz > ./matrix-commander-rs_${TAG_NAME}_linux.tar.gz.sha256sum 102 | echo "SHA256 checksum is: " 103 | cat ./matrix-commander-rs_${TAG_NAME}_linux.tar.gz.sha256sum 104 | ls 105 | ls -l 106 | echo ${TAG_NAME} > tag.txt 107 | cat tag.txt 108 | 109 | - name: Upload artifact Linux 110 | uses: actions/upload-artifact@v4 111 | with: 112 | name: Binary 113 | path: | 114 | ./matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_linux.tar.gz 115 | ./matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_linux.tar.gz.sha256sum 116 | retention-days: 1 117 | 118 | # this overwrites all files in the workspace, so files from before will be lost. 119 | # - uses: actions/checkout@master 120 | # 121 | # This would compile and run test cases, but we have a separate Github action for that 122 | # - name: Build 123 | # run: cargo build --verbose 124 | # - name: Run tests 125 | # run: cargo test --verbose 126 | 127 | - name: Compile 128 | id: compile 129 | uses: rust-build/rust-build.action@master 130 | with: 131 | RUSTTARGET: x86_64-pc-windows-gnu 132 | UPLOAD_MODE: none 133 | - name: Upload artifact 134 | uses: actions/upload-artifact@v4 135 | with: 136 | name: Binary 137 | path: | 138 | ${{ steps.compile.outputs.BUILT_ARCHIVE }} 139 | ${{ steps.compile.outputs.BUILT_CHECKSUM }} 140 | 141 | - name: Compile 142 | id: compile2 143 | uses: rust-build/rust-build.action@master 144 | with: 145 | RUSTTARGET: x86_64-unknown-linux-musl 146 | # ARCHIVE_TYPES: tar.gz 147 | UPLOAD_MODE: none 148 | MINIFY: true 149 | EXTRA_FILES: "README.md LICENSE help.help.txt help.manual.txt help.usage.txt" 150 | - name: Upload artifact 151 | uses: actions/upload-artifact@v4 152 | with: 153 | name: Binary 154 | path: | 155 | ${{ steps.compile2.outputs.BUILT_ARCHIVE }} 156 | ${{ steps.compile2.outputs.BUILT_CHECKSUM }} 157 | 158 | - name: Compile 159 | id: compile3 160 | uses: rust-build/rust-build.action@master 161 | with: 162 | RUSTTARGET: x86_64-apple-darwin 163 | # ARCHIVE_TYPES: tar.gz 164 | UPLOAD_MODE: none 165 | MINIFY: true 166 | EXTRA_FILES: "README.md LICENSE help.help.txt help.manual.txt help.usage.txt" 167 | - name: Upload artifact 168 | uses: actions/upload-artifact@v4 169 | with: 170 | name: Binary 171 | path: | 172 | ${{ steps.compile3.outputs.BUILT_ARCHIVE }} 173 | ${{ steps.compile3.outputs.BUILT_CHECKSUM }} 174 | 175 | - name: Final-check 176 | run: | 177 | ls -l 178 | echo "content of output directory" 179 | ls -l output 180 | TAG_NAME=$(cat tag.txt) 181 | cat tag.txt 182 | echo "tag name: $TAG_NAME" 183 | echo "release tag: $RELEASE_TAG_NAME" 184 | echo "env release tag: " ${{ env.RELEASE_TAG_NAME }} 185 | echo "if rename not installed, will stop action if using rename" 186 | echo $(which rename) 187 | echo $(rename -h) 188 | echo $(rename -v) 189 | echo $(rename -V) 190 | rename 's/_null_/_${{ env.RELEASE_TAG_NAME }}_/' output/* 191 | #cd output 192 | #ls 193 | #mv matrix-commander-rs_null_x86_64-pc-windows-gnu.zip matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_x86_64-pc-windows-gnu.zip 194 | #mv matrix-commander-rs_null_x86_64-pc-windows-gnu.zip.sha256sum matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_x86_64-pc-windows-gnu.zip.sha256sum 195 | #mv matrix-commander-rs_null_x86_64-unknown-linux-musl.zip matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_x86_64-unknown-linux-musl.zip 196 | #mv matrix-commander-rs_null_x86_64-unknown-linux-musl.zip.sha256sum matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_x86_64-unknown-linux-musl.zip.sha256sum 197 | #mv matrix-commander-rs_null_x86_64-apple-darwin.zip matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_x86_64-apple-darwin.zip 198 | #mv matrix-commander-rs_null_x86_64-apple-darwin.zip.sha256sum matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_x86_64-apple-darwin.zip.sha256sum 199 | #cd .. 200 | ls * output/* 201 | 202 | # https://github.com/softprops/action-gh-release 203 | # do wildcards like * work in files? 204 | - name: Release 205 | uses: "softprops/action-gh-release@v2" 206 | with: 207 | token: "${{ secrets.GITHUB_TOKEN }}" 208 | prerelease: false 209 | generate_release_notes: true 210 | files: | 211 | README.md 212 | LICENSE 213 | matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_linux.tar.gz.sha256sum 214 | matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_linux.tar.gz 215 | output/matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_x86_64-pc-windows-gnu.zip 216 | output/matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_x86_64-pc-windows-gnu.zip.sha256sum 217 | output/matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_x86_64-unknown-linux-musl.zip 218 | output/matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_x86_64-unknown-linux-musl.zip.sha256sum 219 | output/matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_x86_64-apple-darwin.zip 220 | output/matrix-commander-rs_${{ env.RELEASE_TAG_NAME }}_x86_64-apple-darwin.zip.sha256sum 221 | hel*.txt 222 | 223 | # ${{ steps.compile.outputs.BUILT_ARCHIVE }} 224 | # ${{ steps.compile.outputs.BUILT_CHECKSUM }} 225 | # ${{ steps.compile2.outputs.BUILT_ARCHIVE }} 226 | # ${{ steps.compile2.outputs.BUILT_CHECKSUM }} 227 | # ${{ steps.compile3.outputs.BUILT_ARCHIVE }} 228 | # ${{ steps.compile3.outputs.BUILT_CHECKSUM }} 229 | -------------------------------------------------------------------------------- /.github/workflows/release-manual.yml: -------------------------------------------------------------------------------- 1 | # .github/workflows/release.yml 2 | 3 | # do a manual release on the Github website and it will trigger a release event 4 | # and any release event will trigger this action 5 | 6 | name: ManualRelease 7 | 8 | on: 9 | release: 10 | types: [created] 11 | 12 | env: 13 | CARGO_TERM_COLOR: always 14 | 15 | jobs: 16 | release: 17 | name: release ${{ matrix.target }} 18 | runs-on: ubuntu-latest 19 | strategy: 20 | fail-fast: false 21 | matrix: 22 | include: 23 | - target: x86_64-pc-windows-gnu 24 | archive: zip 25 | - target: x86_64-unknown-linux-musl 26 | archive: tar.gz tar.xz tar.zst 27 | - target: x86_64-apple-darwin 28 | archive: zip 29 | steps: 30 | - uses: actions/checkout@master 31 | - name: Compile and release 32 | uses: rust-build/rust-build.action@v1.4.5 33 | env: 34 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 35 | with: 36 | RUSTTARGET: ${{ matrix.target }} 37 | ARCHIVE_TYPES: ${{ matrix.archive }} 38 | EXTRA_FILES: "README.md LICENSE help.txt" 39 | -------------------------------------------------------------------------------- /.github/workflows/rust-by-gh.yml: -------------------------------------------------------------------------------- 1 | name: Rust-by-gh 2 | 3 | # only works on tags, if there is no tag it will not work 4 | # cannot start it manually 5 | 6 | on: 7 | # fires when there is a git push with version tag 8 | push: 9 | # this would trigger twice, once for tag v, once for branch main 10 | # branches: [ "main" ] 11 | tags: 12 | - "v*" 13 | # pull_request: 14 | # branches: [ "main" ] 15 | # tags: 16 | # - "v*" 17 | # workflow_dispatch: just for local testing of the Rust comiles, but it will never create a Github release 18 | workflow_dispatch: 19 | inputs: 20 | tag_name: 21 | description: 'Tag name for release' 22 | required: false 23 | default: nightly 24 | 25 | env: 26 | CARGO_TERM_COLOR: always 27 | 28 | jobs: 29 | build: 30 | 31 | runs-on: ubuntu-latest 32 | 33 | steps: 34 | - uses: actions/checkout@v4 35 | # Don't build if we dont have a version tag tag, cannot create release without a version tag anyways 36 | # if: startsWith(github.ref, 'refs/tags/') 37 | 38 | - name: Build 39 | run: | 40 | echo "Rust says: " 41 | rustc -vV 42 | echo "uname says: $(uname -m)" 43 | CCARCH=x86_64-unknown-linux-gnu 44 | cargo build --release 45 | ls -l target target/* 46 | find . -name "matrix*commander*" 47 | mv ./target/*/matrix-commander-rs matrix-commander-rs.$CCARCH 48 | ls -l ./matrix-commander-rs* 49 | cargo clean 50 | # now cross compile 51 | sudo apt-get install podman 52 | cargo install cross 53 | CCARCH=aarch64-unknown-linux-gnu 54 | cross build --target $CCARCH --release 55 | ls -l target target/* 56 | find . -name "matrix*commander*" 57 | mv ./target/$CCARCH/*/matrix-commander-rs matrix-commander-rs.$CCARCH 58 | ls -l ./matrix-commander-rs* 59 | cargo clean 60 | # now cross compile 61 | CCARCH=armv7-linux-androideabi 62 | cross build --target $CCARCH --release 63 | ls -l target target/* 64 | find . -name "matrix*commander*" 65 | mv ./target/$CCARCH/*/matrix-commander-rs matrix-commander-rs.$CCARCH 66 | ls -l ./matrix-commander-rs* 67 | cargo clean 68 | # cannot build for aarch64-apple-darwin 69 | # [cross] warning: `cross` does not provide a Docker image for target aarch64-apple-darwin, specify a custom image in `Cross.toml`. 70 | # cannot build for x86_64-apple-darwin 71 | # [cross] warning: `cross` does not provide a Docker image for target x86_64-apple-darwin, specify a custom image in `Cross.toml`. 72 | # cannot build for Windows 73 | # [cross] warning: `cross` does not provide a Docker image for target x86_64-pc-windows-msvc, specify a custom image in `Cross.toml`. 74 | 75 | 76 | # - uses: actions/upload-artifact@v4 77 | # with: 78 | # name: plain-linux 79 | # path: | 80 | # ./matrix-commander-rs* 81 | # retention-days: 1 82 | 83 | # https://github.com/softprops/action-gh-release 84 | - name: Release 85 | uses: "softprops/action-gh-release@v2" 86 | if: startsWith(github.ref, 'refs/tags/') 87 | with: 88 | token: "${{ secrets.GITHUB_TOKEN }}" 89 | prerelease: false 90 | generate_release_notes: true 91 | files: | 92 | ./matrix-commander-rs* 93 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | # .github/workflow/test.yml 2 | 3 | # build the crate and run the test cases 4 | # like cargo build; cargo test 5 | 6 | name: Test 7 | 8 | on: 9 | # TURNED IT OFF IN SEPT 2024 10 | # push: 11 | # branches: [ "main" ] 12 | # pull_request: 13 | # branches: [ "main" ] 14 | workflow_dispatch: 15 | 16 | env: 17 | CARGO_TERM_COLOR: always 18 | 19 | jobs: 20 | build: 21 | 22 | runs-on: ubuntu-latest 23 | 24 | steps: 25 | - uses: actions/checkout@v4 26 | - name: Build 27 | run: cargo build --verbose 28 | - name: Run tests 29 | run: cargo test --verbose 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | # send it to Github so that other people can have transparency 8 | # Cargo.lock 9 | 10 | Cargo.toml.* 11 | 12 | # These are backup files generated by rustfmt 13 | **/*.rs.bk 14 | 15 | # To-do list 16 | todo.txt 17 | 18 | src.22*/* 19 | 20 | test.txt 21 | 22 | README.md.* 23 | 24 | # ignore a local copy of the compiled binary 25 | matrix-commander-rs* 26 | 27 | 28 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 2 | 3 | [package] 4 | name = "matrix-commander" 5 | version = "0.10.0" 6 | edition = "2021" 7 | description = "simple but convenient CLI-based Matrix client app for sending and receiving" 8 | documentation = "https://docs.rs/matrix-commander" 9 | readme = "README.md" 10 | homepage = "https://github.com/8go/matrix-commander-rs" 11 | repository = "https://github.com/8go/matrix-commander-rs/" 12 | license = "GPL-3.0-or-later" 13 | # crates.io only allows 5 keywords 14 | keywords = ["Matrix", "cli", "command-line-tool", "tool", "messaging"] 15 | categories = ["command-line-utilities", "network-programming"] 16 | exclude = ["todo.txt", ".*"] 17 | publish = true 18 | 19 | 20 | [dependencies] 21 | clap = { version = "4.5", features = [ 22 | "derive", 23 | "color", 24 | "wrap_help", 25 | "unicode", 26 | ] } 27 | colored = "2.1" 28 | directories = "5.0" 29 | futures-util = "0.3" 30 | json = "0.12" 31 | # matrix-sdk = { git = "https://github.com/matrix-org/matrix-rust-sdk , features = ["markdown", "anyhow"] } 32 | matrix-sdk = { version = "0.7", features = [ 33 | "markdown", 34 | "anyhow", 35 | "bundled-sqlite", 36 | ] } 37 | mime = "0.3" 38 | mime_guess = "2.0" 39 | # 40 | # create openssl dependency for cross compilation. 41 | # this removes dependencies on architecture specific openssl files. 42 | # see: https://stackoverflow.com/questions/54775076/how-to-cross-compile-a-rust-project-with-openssl 43 | # see: https://github.com/cross-rs/cross/issues/229 44 | # see: https://stackoverflow.com/questions/68871193/pkg-config-error-during-rust-cross-compilation 45 | openssl = { version = '0.10', features = ["vendored"] } 46 | regex = "1.11" 47 | reqwest = "0.12" 48 | rpassword = "7.3" 49 | serde_json = "1.0" 50 | serde = { version = "1.0", features = ["derive"] } 51 | thiserror = "1.0" 52 | tokio = { version = "1.41", default-features = false, features = [ 53 | "rt-multi-thread", 54 | "macros", 55 | ] } 56 | tracing = "0.1" 57 | tracing-subscriber = { version = "0.3", features = ["env-filter"] } 58 | update-informer = "1.1" 59 | url = { version = "2.5", features = ["serde"] } 60 | 61 | 62 | [dev-dependencies] 63 | # "matrix-commander-rs" will be the Rust program 64 | # to perform tests on async functions 65 | tokio-test = "0.4" 66 | 67 | # this is to distinguish it from "matrix-commander" which is the Python program 68 | # For people that have both Python and Rust installed: 69 | # "matrix-commander" will remain the Python program 70 | [[bin]] 71 | name = "matrix-commander-rs" 72 | path = "src/main.rs" 73 | 74 | # https://doc.rust-lang.org/cargo/reference/manifest.html#the-badges-section 75 | [badges] 76 | # The author wants to share it with the community but is not intending to meet anyone's particular use case. 77 | maintenance = { status = "experimental" } 78 | 79 | 80 | [profile.release] 81 | strip = "symbols" 82 | lto = true 83 | 84 | [profile.release-tiny] 85 | inherits = "release" 86 | opt-level = "s" 87 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 0.10.0 2 | -------------------------------------------------------------------------------- /help.help.txt: -------------------------------------------------------------------------------- 1 | Welcome to "matrix-commander-rs", a Matrix CLI client. ─── On the first run use 2 | --login to log in, to authenticate. On the second run we suggest to use 3 | --verify to get verified. Manual verification is built-in and can be used to 4 | verify devices and users. Or combine both --login and --verify in the first 5 | run. On further runs "matrix-commander-rs" implements a simple Matrix CLI 6 | client that can send messages or files, listen to messages, operate on rooms, 7 | etc. ─── ─── This project is currently only a vision. The Python package 8 | "matrix-commander" exists. The vision is to have a compatible program in Rust. 9 | I cannot do it myself, but I can coordinate and merge your pull requests. Have 10 | a look at the repo "https://github.com/8go/matrix-commander-rs/". Please help! 11 | Please contribute code to make this vision a reality, and to one day have a 12 | feature-rich "matrix-commander-rs" crate. Safe! 13 | Usage: matrix-commander-rs [OPTIONS] 14 | Options: 15 | --contribute 16 | Please contribute 17 | -v, --version [] 18 | Print version number or check if a newer version exists on crates.io. 19 | --usage 20 | Prints a very short help summary. 21 | -h, --help 22 | Prints short help displaying about one line per argument. 23 | --manual 24 | Prints long help. 25 | --readme 26 | Prints README.md file, the documenation in Markdown. 27 | -d, --debug... 28 | Overwrite the default log level. 29 | --log-level ... 30 | Set the log level by overwriting the default log level. 31 | --verbose... 32 | Set the verbosity level. 33 | --plain 34 | Disable encryption for a specific action. 35 | -c, --credentials 36 | Specify path to a file containing credentials. 37 | -s, --store 38 | Specify a path to a directory to be used as "store" for encrypted 39 | messaging. 40 | --login 41 | Login to and authenticate with the Matrix homeserver. 42 | --verify 43 | Perform account verification. 44 | --bootstrap 45 | --logout 46 | Logout this or all devices from the Matrix homeserver. 47 | --homeserver 48 | Specify a homeserver for use by certain actions. 49 | --user-login 50 | Optional argument to specify the user for --login. 51 | --password 52 | Specify a password for use by certain actions. 53 | --device 54 | Specify a device name, for use by certain actions. 55 | --room-default 56 | Optionally specify a room as the default room for future actions. 57 | --devices 58 | Print the list of devices. 59 | --timeout 60 | Set the timeout of the calls to the Matrix server. 61 | -m, --message [...] 62 | Send one or more messages. 63 | --markdown 64 | Specify the message format as MarkDown. 65 | --code 66 | SPecify the message format as Code. 67 | -r, --room [...] 68 | Optionally specify one or multiple rooms. 69 | -f, --file [...] 70 | Send one or multiple files (e.g. PDF, DOC, MP4). 71 | --notice 72 | Specify the message type as Notice. 73 | --emote 74 | Specify the message type as Emote. 75 | --sync 76 | Select synchronization choice. 77 | -l, --listen 78 | Listen to messages. 79 | --tail 80 | Get the last messages. 81 | -y, --listen-self 82 | Get your own messages. 83 | --whoami 84 | Print your user name. 85 | -o, --output 86 | Specify the output format. 87 | --file-name [...] 88 | Specify one or multiple file names for some actions. 89 | --get-room-info [...] 90 | Get room information. 91 | --room-create [...] 92 | Create one or multiple rooms. 93 | --room-dm-create [...] 94 | Create one or multiple direct messaging (DM) rooms for given users. 95 | --room-leave [...] 96 | Leave this room or these rooms. 97 | --room-forget [...] 98 | Forget one or multiple rooms. 99 | --room-invite [...] 100 | Invite one ore more users to join one or more rooms. 101 | --room-join [...] 102 | Join one or multiple rooms. 103 | --room-ban [...] 104 | Ban one ore more users from one or more rooms. 105 | --room-unban [...] 106 | Unban one ore more users from one or more rooms. 107 | --room-kick [...] 108 | Kick one ore more users from one or more rooms. 109 | --room-resolve-alias [...] 110 | Resolves room aliases to room ids. 111 | --room-enable-encryption [...] 112 | Enable encryption for one or multiple rooms. 113 | --alias [...] 114 | Provide one or more aliases. 115 | --name [...] 116 | Specify one or multiple names. 117 | --topic [...] 118 | Specify one or multiple topics. 119 | --rooms 120 | Print the list of past and current rooms. 121 | --invited-rooms 122 | Print the list of invited rooms. 123 | --joined-rooms 124 | Print the list of joined rooms. 125 | --left-rooms 126 | Print the list of left rooms. 127 | --room-get-visibility [...] 128 | Get the visibility of one or more rooms. 129 | --room-get-state [...] 130 | Get the state of one or more rooms. 131 | --joined-members [...] 132 | Print the list of joined members for one or multiple rooms. 133 | --delete-device [...] 134 | Delete one or multiple devices. 135 | -u, --user [...] 136 | Specify one or multiple users. 137 | --get-avatar 138 | Get your own avatar. 139 | --set-avatar 140 | Set your own avatar. 141 | --get-avatar-url 142 | Get your own avatar URL. 143 | --set-avatar-url 144 | Set your own avatar URL. 145 | --unset-avatar-url 146 | Remove your own avatar URL. 147 | --get-display-name 148 | Get your own display name. 149 | --set-display-name 150 | Set your own display name. 151 | --get-profile 152 | Get your own profile. 153 | --media-upload [...] 154 | Upload one or multiple files (e.g. PDF, DOC, MP4) to the homeserver 155 | content repository. 156 | --media-download [...] 157 | Download one or multiple files from the homeserver content 158 | repository. 159 | --mime [...] 160 | Specify the Mime type of certain input files. 161 | --media-delete [...] 162 | Delete one or multiple objects (e.g. files) from the content 163 | repository. 164 | --media-mxc-to-http [...] 165 | Convert URIs to HTTP URLs. 166 | --get-masterkey 167 | Get your own master key. 168 | PS: Also have a look at scripts/matrix-commander-rs-tui. 169 | Use --manual to get more detailed help information. 170 | -------------------------------------------------------------------------------- /help.usage.txt: -------------------------------------------------------------------------------- 1 | Usage: matrix-commander-rs [OPTIONS] 2 | Options: 3 | --contribute 4 | -v, --version [] 5 | --usage 6 | -h, --help 7 | --manual 8 | --readme 9 | -d, --debug... 10 | --log-level ... 11 | --verbose... 12 | --plain 13 | -c, --credentials 14 | -s, --store 15 | --login 16 | --verify 17 | --bootstrap 18 | --logout 19 | --homeserver 20 | --user-login 21 | --password 22 | --device 23 | --room-default 24 | --devices 25 | --timeout 26 | -m, --message [...] 27 | --markdown 28 | --code 29 | -r, --room [...] 30 | -f, --file [...] 31 | --notice 32 | --emote 33 | --sync 34 | -l, --listen 35 | --tail 36 | -y, --listen-self 37 | --whoami 38 | -o, --output 39 | --file-name [...] 40 | --get-room-info [...] 41 | --room-create [...] 42 | --room-dm-create [...] 43 | --room-leave [...] 44 | --room-forget [...] 45 | --room-invite [...] 46 | --room-join [...] 47 | --room-ban [...] 48 | --room-unban [...] 49 | --room-kick [...] 50 | --room-resolve-alias [...] 51 | --room-enable-encryption [...] 52 | --alias [...] 53 | --name [...] 54 | --topic [...] 55 | --rooms 56 | --invited-rooms 57 | --joined-rooms 58 | --left-rooms 59 | --room-get-visibility [...] 60 | --room-get-state [...] 61 | --joined-members [...] 62 | --delete-device [...] 63 | -u, --user [...] 64 | --get-avatar 65 | --set-avatar 66 | --get-avatar-url 67 | --set-avatar-url 68 | --unset-avatar-url 69 | --get-display-name 70 | --set-display-name 71 | --get-profile 72 | --media-upload [...] 73 | --media-download [...] 74 | --mime [...] 75 | --media-delete [...] 76 | --media-mxc-to-http [...] 77 | --get-masterkey 78 | -------------------------------------------------------------------------------- /logos/matrix-commander-rs.svg: -------------------------------------------------------------------------------- 1 | 2 | 14 | 16 | 35 | 237 | 241 | 245 | 246 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | edition = "2021" 2 | -------------------------------------------------------------------------------- /screenshots/matrix-commander-rs-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/8go/matrix-commander-rs/a4acbf7f1abcaf86a0341e98b555c38163a1b830/screenshots/matrix-commander-rs-screenshot.png -------------------------------------------------------------------------------- /screenshots/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/8go/matrix-commander-rs/a4acbf7f1abcaf86a0341e98b555c38163a1b830/screenshots/screenshot.png -------------------------------------------------------------------------------- /scripts/clean-local.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # echo "doing small cleanup of debug build" 3 | ls -lh target/debug/incremental/matrix_commander_rs-* target/debug/matrix-commander-rs* 2> /dev/null 4 | rm -r -f target/debug/incremental/matrix_commander_rs-* target/debug/matrix-commander-rs* 5 | -------------------------------------------------------------------------------- /scripts/create-help-help.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | PATH=".:./target/release/:./target/debug/:$PATH" && 3 | matrix-commander-rs --help >help.help.txt 4 | echo "help.help.txt is $(wc -l help.help.txt | cut -d ' ' -f1) lines long" 5 | 6 | # ALTERNATIVE: 7 | # #!/usr/bin/env bash 8 | # old_width=$(stty size | cut -d' ' -f2-) && stty cols 69 && cargo run -- --help >help.help.txt && 9 | # stty cols $old_width && stty size && echo -n "Max width: " && wc -L help.help.txt 10 | # sed -i "s|target/debug/matrix-commander-rs|matrix-commander-rs|g" help.help.txt 11 | # # remove color codes, bold and underline char sequences 12 | # sed -i "s,\x1B\[[0-9;]*[a-zA-Z],,g" help.help.txt 13 | -------------------------------------------------------------------------------- /scripts/create-help-manual.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | PATH=".:./target/release/:./target/debug/:$PATH" && 3 | matrix-commander-rs --manual >help.manual.txt 4 | echo "help.manual.txt is $(wc -l help.manual.txt | cut -d ' ' -f1) lines long" 5 | -------------------------------------------------------------------------------- /scripts/create-help-usage.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | PATH=".:./target/release/:./target/debug/:$PATH" && 3 | matrix-commander-rs --usage >help.usage.txt 4 | echo "help.usage.txt is $(wc -l help.usage.txt | cut -d ' ' -f1) lines long" 5 | -------------------------------------------------------------------------------- /scripts/matrix-commander-rs-tui: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # vipe (from moreutils) must be installed 4 | type vipe >/dev/null 2>&1 || { 5 | echo "This script requires that you install \"vipe\" from the packge \"moreutils\"." 6 | echo "Read https://www.putorius.net/moreutils.html for installation instructions." 7 | echo "As an alternative you could also install \"vipe.sh\" from https://github.com/0mp/vipe.sh/blob/master/vipe.sh." 8 | exit 0 9 | } 10 | 11 | # fzf must be installed 12 | type fzf >/dev/null 2>&1 || { 13 | echo "This script requires that you install \"fzf\"." 14 | echo "Read https://github.com/junegunn/fzf#installation for installation instructions." 15 | exit 0 16 | } 17 | 18 | EXE=matrix-commander-rs 19 | 20 | # Instruction on how to use fzf 21 | echo "Set env variables EDITOR and VISUAL to change the editor being used." 22 | echo "Use tab to select the correct arguments in the correct order." 23 | sleep 1 24 | # generate the short command options list 25 | # run it throu fzf, run it through editor, execute it 26 | # shellcheck disable=SC2046 # quoting will 27 | PATH=".:./target/release/:./target/debug/:$PATH" $EXE --usage | 28 | sed '1,/^Options:/d' | 29 | sed "s/^ -., / /g" | 30 | sed "s/^ //g" | 31 | sed "s/^$//g" | sort | 32 | echo -n "$EXE $(fzf -m)" | xargs | vipe | /bin/bash 33 | 34 | # to force a specific editor do this: e.g. forcing to use "nano" 35 | # PATH=".:./target/release/:./target/debug/:$PATH" $EXE --usage | 36 | # sed '1,/^Options:/d' | sed "s/^ -., / /g" | sed "s/^ //g" | sed "s/^$//g" | sort | 37 | # echo -n "$EXE $(fzf -m)" | EDITOR=nano VISUAL=nano vipe | /bin/bash 38 | -------------------------------------------------------------------------------- /scripts/path-adjust.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # source this script, don't execute it 3 | # source scripts/path-adjust.sh 4 | export PATH="$PATH:./scripts" 5 | -------------------------------------------------------------------------------- /scripts/update-1-version.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # A version number is defined by: MAJOR.MINOR.PATCH 4 | # where 5 | # MAJOR version when you make incompatible API changes 6 | # MINOR version when you add functionality in a backwards-compatible manner, and 7 | # PATCH version when you make backwards-compatible bug fixes. 8 | # See also Issue #109 9 | # 10 | # bumps version number of project 11 | # change 1 line (VERSION) in "Cargo.toml" 12 | # creates 1-line `VERSION` file 13 | # 14 | # the script must take 1 argument: either `--mayor`, `--minor` or `--patch` 15 | # NO default is set on purpose. 16 | 17 | FN="Cargo.toml" 18 | VERSION_FILE="VERSION" 19 | UPDATE="invalid" 20 | 21 | if ! [ -f "$FN" ]; then 22 | FN="../$FN" 23 | if ! [ -f "$FN" ]; then 24 | echo -n "ERROR: $(basename -- "$FN") not found. " 25 | echo "Neither in local nor in parent directory." 26 | exit 1 27 | fi 28 | fi 29 | 30 | if ! [ -f "$FN" ]; then 31 | echo "ERROR: File \"$FN\" not found." 32 | exit 1 33 | fi 34 | 35 | if [ "${1,,}" == "-ma" ] || [ "${1,,}" == "--mayor" ]; then 36 | UPDATE="MAYOR" 37 | fi 38 | 39 | if [ "${1,,}" == "-mi" ] || [ "${1,,}" == "--minor" ]; then 40 | UPDATE="MINOR" 41 | fi 42 | 43 | if [ "${1,,}" == "-p" ] || [ "${1,,}" == "--patch" ]; then 44 | UPDATE="PATCH" 45 | fi 46 | 47 | 48 | if [ "${UPDATE,,}" == "invalid" ]; then 49 | echo "Error: No version type specified: specify either '--mayor', '--minor' or '--patch'." 50 | exit 2 51 | fi 52 | 53 | echo "Doing a ${UPDATE} version increment." 54 | 55 | 56 | PREFIX="version = " 57 | REGEX="^${PREFIX}\"[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\"" 58 | COUNT=$(grep --count -e "$REGEX" $FN) 59 | if [ "$COUNT" == "1" ]; then 60 | NR=$(grep -e "$REGEX" $FN | cut -d'"' -f2) 61 | A=$(echo $NR | cut -d'.' -f1) 62 | M=$(echo $NR | cut -d'.' -f2) 63 | Z=$(echo $NR | cut -d'.' -f3) 64 | if [ "$UPDATE" == "MAYOR" ]; then 65 | A=$((A + 1)) 66 | M="0" 67 | Z="0" 68 | elif [ "$UPDATE" == "MINOR" ]; then 69 | M=$((M + 1)) 70 | Z="0" 71 | else 72 | Z=$((Z + 1)) 73 | fi 74 | NEWVERSIONNR="${A}.${M}.${Z}" 75 | echo $NEWVERSIONNR >"$VERSION_FILE" 76 | NEWVERSION="$PREFIX\"${A}.${M}.${Z}\"" 77 | sed -i "s/$REGEX/$NEWVERSION/" $FN 78 | RETURN=$? 79 | if [ "$RETURN" == "0" ]; then 80 | echo "SUCCESS: Modified file $FN by setting version to $NEWVERSION." 81 | else 82 | echo "ERROR: could not change version to $NEWVERSION in $FN." 83 | exit 1 84 | fi 85 | else 86 | echo "Error while searching for $REGEX" 87 | grep -e "$PREFIX" $FN 88 | if [ "$COUNT" == "1" ]; then 89 | echo "ERROR: Version not found in $FN, expected 1 occurance." 90 | else 91 | echo "ERROR: Version found $COUNT times in $FN, expected 1 occurance." 92 | fi 93 | exit 1 94 | fi 95 | 96 | exit 0 97 | -------------------------------------------------------------------------------- /scripts/update-2-help-manual.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import re 3 | import shutil 4 | import subprocess 5 | import sys 6 | from datetime import datetime 7 | from os import R_OK, access 8 | from os.path import isfile 9 | 10 | # runs program (cargo run) to create the help.manual.txt file 11 | # 12 | # replace this pattern: 13 | # ``` 14 | # Usage: ... 15 | # ``` 16 | # in the README.md file with the help.manual.txt file 17 | 18 | # datetime object containing current date and time 19 | now = datetime.now() 20 | date_string = now.strftime("%Y%m%d-%H%M%S") 21 | 22 | helpfile = "help.manual.txt" 23 | filename = "README.md" 24 | # create_help_script = "scripts/create-help-manual.sh" 25 | 26 | if isfile(filename) and access(filename, R_OK): 27 | # so that subprocess can execute it without PATH 28 | filename = "./" + filename 29 | helpfile = "./" + helpfile 30 | else: 31 | filename = "../" + filename 32 | helpfile = "../" + helpfile 33 | if not (isfile(filename) and access(filename, R_OK)): 34 | print( 35 | f"Error: file {filename[3:]} not found, neither in " 36 | "local nor in parent directory." 37 | ) 38 | sys.exit(1) 39 | 40 | backupfile = filename + "." + date_string 41 | shutil.copy2(filename, backupfile) 42 | 43 | with open(helpfile, "w") as f: 44 | # tty size defaults to 80 columns 45 | bashCmd = ["cargo", "run", "--", "--manual"] 46 | process = subprocess.Popen(bashCmd, stdout=f) 47 | _, error = process.communicate() 48 | if error: 49 | print("Error: Running cargo failed. Not enough disk space?") 50 | print(error) 51 | sys.exit(1) 52 | 53 | with open(helpfile, "r+") as f: 54 | helptext = f.read() 55 | if len(helptext) < 100: 56 | print(f"Error: file {helpfile} has length {len(helptext)}. Something is wrong. Aborting.") 57 | sys.exit(1) 58 | 59 | 60 | bashCmd = ["sed", "-i" , "s,"+"\x1B"+"\[[0-9;]*[a-zA-Z],,g" , helpfile] 61 | process = subprocess.Popen(bashCmd,) 62 | _, error = process.communicate() 63 | if error: 64 | print(error) 65 | 66 | bashCmd = ["wc", "-L", helpfile] # max line length 67 | process = subprocess.Popen(bashCmd, stdout=subprocess.PIPE) 68 | output, error = process.communicate() 69 | if error: 70 | print(error) 71 | else: 72 | output = output.decode("utf-8").strip("\n") 73 | print(f"Maximum line length is {output}") 74 | 75 | with open(helpfile, "r+") as f: 76 | helptext = f.read() 77 | print(f"Length of new {helpfile} file is: {len(helptext)}") 78 | 79 | with open(filename, "r+") as f: 80 | text = f.read() 81 | print(f"Length of {filename} before: {len(text)}") 82 | text = re.sub( 83 | r"```\nWelcome to[\s\S]*?```", 84 | "```\n" 85 | + helptext.translate( 86 | str.maketrans( 87 | { 88 | "\\": r"\\", 89 | } 90 | ) 91 | ) 92 | + "```", 93 | text, 94 | ) 95 | 96 | text = re.sub( 97 | r"target/debug/matrix-commander-rs", 98 | "matrix-commander-rs", 99 | text, 100 | ) 101 | 102 | print(f"Length of {filename} after: {len(text)}") 103 | f.seek(0) 104 | f.write(text) 105 | f.truncate() 106 | 107 | bashCmd = ["diff", filename, backupfile] 108 | process = subprocess.Popen(bashCmd, stdout=subprocess.PIPE) 109 | output, error = process.communicate() 110 | if error: 111 | print(error) 112 | else: 113 | output = output.decode("utf-8").strip("\n") 114 | print(f"Diff is:\n{output}") 115 | -------------------------------------------------------------------------------- /scripts/update-5-tag.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # commit first 4 | echo "it is assumed that a git commit has just been committed" 5 | 6 | # then tag 7 | # # lightweight tag (will not be automatically pushed with --follow-tags) 8 | # git tag v"$(cat VERSION)" # lightweight tag (will not be automatically pushed) 9 | # annotated tag (will be automatically pushed with --follow-tags) 10 | git tag -a -m "release: v$(cat VERSION)" -m "" -m "$(git log -1 --pretty=%B)" v"$(cat VERSION)" # annotated tag 11 | 12 | git tag --list -n | tail -n 7 # list tags 13 | git log --pretty=oneline -n 7 # now it shows tag in commit hash 14 | 15 | git tag --list -n10 | tail -n 10 # show the commit comments in last tag 16 | # git tag --list -n20 $(git describe) # show last tag details 17 | 18 | # then push 19 | echo "new tag was created, now ready for a git push" 20 | -------------------------------------------------------------------------------- /scripts/workflow-outline.txt: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | echo "Welcome!" 4 | echo "The script outlines the rough workflow" 5 | echo "" 6 | echo "You have written some code? Let's publish it." 7 | 8 | git pull 9 | 10 | echo "Update version number in Cargo.toml." 11 | scripts/update-1-version.sh 12 | 13 | scripts/update-2-help.py # create helpfile and update README.md accordingly 14 | 15 | cargo clippy --color always 2>&1 | less -r # if output is very long 16 | cargo fmt 17 | 18 | # show files containing changes that were not yet committed into git 19 | cargo package --list # a bit like `git status` 20 | 21 | cargo build 22 | cargo build --color always 2>&1 | less -r # if output is very long 23 | # cargo build --examples 24 | cargo test 25 | cargo test --color always 2>&1 | less -r # if output is very long 26 | cargo run 27 | # cargo run --example example 28 | # cargo run -- --version # pass some argument 29 | cargo build --release 30 | cargo run --release 31 | 32 | # generate documentation 33 | cargo doc 34 | firefox target/doc/matrix_commander/index.html 35 | 36 | git status 37 | git commit -a 38 | git push 39 | git log -1 --pretty=%B # details of last commit 40 | git status 41 | 42 | cargo login # provide token 43 | cargo publish --dry-run 44 | cargo package --list # show files containing changes 45 | cargo publish # push to crates.io and doc.rs 46 | 47 | cargo clean # rm ./target directory 48 | -------------------------------------------------------------------------------- /scripts/workflow.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | echo "Welcome!" 4 | echo "The script outlines the rough workflow" 5 | echo 6 | echo "You have written some code? Let's publish it." 7 | 8 | # https://askubuntu.com/questions/1705/how-can-i-create-a-select-menu-in-a-shell-script 9 | PS3="Please enter your choice: " 10 | OPT1="rustup self update # update rustup" 11 | OPT2="rustup update stable # update rust" 12 | OPT3="cargo upgrade # update dependency versions in Cargo.toml" 13 | OPT4="cargo update # update dependencies" 14 | OPTC="Continue" 15 | OPTQ="Quit" 16 | options=("$OPT1" "$OPT2" "$OPT3" "$OPT4" "$OPTC" "$OPTQ") 17 | select opt in "${options[@]}"; do 18 | if [ "${REPLY,,}" == "c" ]; then opt="$OPTC"; fi 19 | if [ "${REPLY,,}" == "q" ]; then opt="$OPTQ"; fi 20 | case ${opt} in 21 | "$OPT1" | "$OPT2" | "$OPT3" | "$OPT4") 22 | OPTE=${opt%%#*} # remove everything after first # 23 | echo "Performing: $OPTE" 24 | $OPTE 25 | continue 26 | ;; 27 | "$OPTC") 28 | echo "On to next step." 29 | break 30 | ;; 31 | "$OPTQ" | "quit") 32 | echo "Quitting program." 33 | exit 0 34 | ;; 35 | *) echo "invalid option $REPLY" ;; 36 | esac 37 | done 38 | 39 | PS3="Please enter your choice: " 40 | OPT1="git pull # get the latest from Github" 41 | OPTC="Continue" 42 | OPTQ="Quit" 43 | options=("$OPT1" "$OPTC" "$OPTQ") 44 | select opt in "${options[@]}"; do 45 | if [ "${REPLY,,}" == "c" ]; then opt="$OPTC"; fi 46 | if [ "${REPLY,,}" == "q" ]; then opt="$OPTQ"; fi 47 | case ${opt} in 48 | "$OPT1") 49 | OPTE=${opt%%#*} # remove everything after first # 50 | echo "Performing: $OPTE" 51 | $OPTE 52 | break 53 | ;; 54 | "$OPTC") 55 | echo "On to next step." 56 | break 57 | ;; 58 | "$OPTQ" | "quit") 59 | echo "Quitting program." 60 | exit 0 61 | ;; 62 | *) echo "invalid option $REPLY" ;; 63 | esac 64 | done 65 | 66 | PS3="Please enter your choice: " 67 | OPT1="cargo test # run this testcase" 68 | OPT2="tests/test-version.sh # run this testcase" 69 | OPT3="tests/test-send.sh # run this testcase" 70 | OPT4="tests/test-devices.sh # run this testcase" 71 | OPT5="tests/test-rooms.sh # run this testcase" 72 | OPT6="tests/test-get-profile.sh # run this testcase" 73 | OPT7="tests/test-get-display-name.sh # run this testcase" 74 | OPTC="Continue" 75 | OPTQ="Quit" 76 | options=("$OPT1" "$OPT2" "$OPT3" "$OPT4" "$OPT5" "$OPT6" "$OPT7" "$OPTC" "$OPTQ") 77 | select opt in "${options[@]}"; do 78 | if [ "${REPLY,,}" == "c" ]; then opt="$OPTC"; fi 79 | if [ "${REPLY,,}" == "q" ]; then opt="$OPTQ"; fi 80 | case ${opt} in 81 | "$OPT1" | "$OPT2" | "$OPT3" | "$OPT4" | "$OPT5" | "$OPT6" | "$OPT7") 82 | OPTE=${opt%%#*} # remove everything after first # 83 | echo "Performing: $OPTE" 84 | $OPTE 85 | continue 86 | ;; 87 | "$OPTC") 88 | echo "On to next step." 89 | break 90 | ;; 91 | "$OPTQ") 92 | echo "Quitting program." 93 | exit 0 94 | ;; 95 | *) echo "invalid option $REPLY" ;; 96 | esac 97 | done 98 | 99 | PS3="Please enter your choice: " 100 | OPT1="scripts/update-1-version.sh --mayor # increment MAJOR version number, incompatible" 101 | OPT2="scripts/update-1-version.sh --minor # increment MINOR version number, new feature" 102 | OPT3="scripts/update-1-version.sh --patch # increment PATCH version number, bug fix" 103 | OPT4="cargo clean" 104 | OPT5="cargo build" 105 | OPT6="scripts/create-help-usage.sh # create help usage file" 106 | OPT7="scripts/create-help-help.sh # create help help file" 107 | OPT8="scripts/update-2-help-manual.py # update help manual file, puts it also into README.md" 108 | OPT9="cargo clippy # linting" 109 | OPT10="cargo fmt # beautifying" 110 | OPTC="Continue" 111 | OPTQ="Quit" 112 | options=("$OPT1" "$OPT2" "$OPT3" "$OPT4" "$OPT5" "$OPT6" "$OPT7" "$OPT8" "$OPT9" "$OPT10" "$OPTC" "$OPTQ") 113 | select opt in "${options[@]}"; do 114 | if [ "${REPLY,,}" == "c" ]; then opt="$OPTC"; fi 115 | if [ "${REPLY,,}" == "q" ]; then opt="$OPTQ"; fi 116 | case ${opt} in 117 | "$OPT1" | "$OPT2" | "$OPT3" | "$OPT4" | "$OPT5" | "$OPT6" | "$OPT7" | "$OPT8" | "$OPT9" | "$OPT10") 118 | OPTE=${opt%%#*} # remove everything after first # 119 | echo "Performing: $OPTE" 120 | $OPTE 121 | continue 122 | ;; 123 | "$OPTC") 124 | echo "On to next step." 125 | break 126 | ;; 127 | "$OPTQ") 128 | echo "Quitting program." 129 | exit 0 130 | ;; 131 | *) echo "invalid option $REPLY" ;; 132 | esac 133 | done 134 | 135 | PS3="Please enter your choice: " 136 | OPT1="git status # what is the current status" 137 | OPT2="git add Cargo.lock Cargo.toml README.md VERSION help.manual.txt help.help.txt help.usage.txt src/emoji_verify.rs src/main.rs src/mclient.rs" 138 | OPT3="cargo package --list # show files containing changes" 139 | OPTC="Continue" 140 | OPTQ="Quit" 141 | options=("$OPT1" "$OPT2" "$OPT3" "$OPTC" "$OPTQ") 142 | select opt in "${options[@]}"; do 143 | if [ "${REPLY,,}" == "c" ]; then opt="$OPTC"; fi 144 | if [ "${REPLY,,}" == "q" ]; then opt="$OPTQ"; fi 145 | case ${opt} in 146 | "$OPT1" | "$OPT2" | "$OPT3") 147 | OPTE=${opt%%#*} # remove everything after first # 148 | echo "Performing: $OPTE" 149 | $OPTE 150 | continue 151 | ;; 152 | "$OPTC") 153 | echo "On to next step." 154 | break 155 | ;; 156 | "$OPTQ") 157 | echo "Quitting program." 158 | exit 0 159 | ;; 160 | *) echo "invalid option $REPLY" ;; 161 | esac 162 | done 163 | 164 | PS3="Please enter your choice: " 165 | OPT1="git commit -a # alternative 1 for commit" 166 | OPT2="git commit # alternative 2 for commit" 167 | OPT3="git commit -a -m 'release: v$(cat VERSION)' # alternative 3 for commit; being lazy" 168 | OPTC="Continue" 169 | OPTQ="Quit" 170 | options=("$OPT1" "$OPT2" "$OPT3" "$OPTC" "$OPTQ") 171 | select opt in "${options[@]}"; do 172 | if [ "${REPLY,,}" == "c" ]; then opt="$OPTC"; fi 173 | if [ "${REPLY,,}" == "q" ]; then opt="$OPTQ"; fi 174 | case ${opt} in 175 | "$OPT1" | "$OPT2" | "$OPT3") 176 | OPTE=${opt%%#*} # remove everything after first # 177 | echo "Performing: $OPTE" 178 | $OPTE 179 | break 180 | ;; 181 | "$OPTC") 182 | echo "On to next step." 183 | break 184 | ;; 185 | "$OPTQ") 186 | echo "Quitting program." 187 | exit 0 188 | ;; 189 | *) echo "invalid option $REPLY" ;; 190 | esac 191 | done 192 | 193 | PS3="Please enter your choice: " 194 | OPT1="scripts/update-5-tag.sh # create new annotated tag" 195 | OPTC="Continue" 196 | OPTQ="Quit" 197 | options=("$OPT1" "$OPTC" "$OPTQ") 198 | select opt in "${options[@]}"; do 199 | if [ "${REPLY,,}" == "c" ]; then opt="$OPTC"; fi 200 | if [ "${REPLY,,}" == "q" ]; then opt="$OPTQ"; fi 201 | case ${opt} in 202 | "$OPT1") 203 | OPTE=${opt%%#*} # remove everything after first # 204 | echo "Performing: $OPTE" 205 | $OPTE 206 | break 207 | ;; 208 | "$OPTC") 209 | echo "On to next step." 210 | break 211 | ;; 212 | "$OPTQ") 213 | echo "Quitting program." 214 | exit 0 215 | ;; 216 | *) echo "invalid option $REPLY" ;; 217 | esac 218 | done 219 | 220 | PS3="Please enter your choice: " 221 | echo "A tag push of major version kicks off the Docker actions workflow on Github." 222 | echo "A tag push of major version kicks off the PiPy actions workflow on Github." 223 | echo "Note: a PR does not trigger Github Actions workflows." 224 | echo "Only pushing a tag kicks off the workflow and only if not a minor version." 225 | echo "Instead of 2 separate pushes, one can use *annotated* tags and ----follow-tags." 226 | OPT1="git push --follow-tags # alternative 1; does both push of changes and push of tag" 227 | OPT2="git push # alternative 2a; 1st push, since there is no tag, no trigger on workflows" 228 | OPT3="git push origin v'$(cat VERSION)' # alternative 2b; 2nd push, pushing tag" 229 | OPT4="git push && git push origin v'$(cat VERSION)' # alternative 3; both pushes" 230 | OPTC="Continue" 231 | OPTQ="Quit" 232 | options=("$OPT1" "$OPT2" "$OPT3" "$OPT4" "$OPTC" "$OPTQ") 233 | select opt in "${options[@]}"; do 234 | if [ "${REPLY,,}" == "c" ]; then opt="$OPTC"; fi 235 | if [ "${REPLY,,}" == "q" ]; then opt="$OPTQ"; fi 236 | case ${opt} in 237 | "$OPT1" | "$OPT2" | "$OPT3" | "$OPT4") 238 | OPTE=${opt%%#*} # remove everything after first # 239 | echo "Performing: $OPTE" 240 | $OPTE 241 | break 242 | ;; 243 | "$OPTC") 244 | echo "On to next step." 245 | break 246 | ;; 247 | "$OPTQ") 248 | echo "Quitting program." 249 | exit 0 250 | ;; 251 | *) echo "invalid option $REPLY" ;; 252 | esac 253 | done 254 | 255 | PS3="Please enter your choice: " 256 | echo "Watch Actions workflows on Github, if any." 257 | echo "Now double-check if everything is in order." 258 | OPT1="git tag --list -n --sort=-refname # list tags" 259 | OPT2="git log --pretty=oneline -n 7 # now it shows tag in commit hash" 260 | OPT3="git log -1 --pretty=%B # details of last commit" 261 | OPT4="git tag --list -n20 $(git describe) # details of last tag" 262 | OPT5="git status # list status" 263 | OPTC="Continue" 264 | OPTQ="Quit" 265 | options=("$OPT1" "$OPT2" "$OPT3" "$OPT4" "$OPT5" "$OPTC" "$OPTQ") 266 | select opt in "${options[@]}"; do 267 | if [ "${REPLY,,}" == "c" ]; then opt="$OPTC"; fi 268 | if [ "${REPLY,,}" == "q" ]; then opt="$OPTQ"; fi 269 | case ${opt} in 270 | "$OPT1" | "$OPT2" | "$OPT3" | "$OPT4" | "$OPT5") 271 | OPTE=${opt%%#*} # remove everything after first # 272 | echo "Performing: $OPTE" 273 | $OPTE 274 | continue 275 | ;; 276 | "$OPTC") 277 | echo "On to next step." 278 | break 279 | ;; 280 | "$OPTQ") 281 | echo "Quitting program." 282 | exit 0 283 | ;; 284 | *) echo "invalid option $REPLY" ;; 285 | esac 286 | done 287 | 288 | PS3="Please enter your choice: " 289 | OPT1="cargo login # log into crates.io" 290 | OPT2="cargo clean" 291 | OPT3="cargo publish" 292 | OPTC="Continue" 293 | OPTQ="Quit" 294 | options=("$OPT1" "$OPT2" "$OPT3" "$OPTC" "$OPTQ") 295 | select opt in "${options[@]}"; do 296 | if [ "${REPLY,,}" == "c" ]; then opt="$OPTC"; fi 297 | if [ "${REPLY,,}" == "q" ]; then opt="$OPTQ"; fi 298 | case ${opt} in 299 | "$OPT1" | "$OPT2" | "$OPT3") 300 | OPTE=${opt%%#*} # remove everything after first # 301 | echo "Performing: $OPTE" 302 | $OPTE 303 | continue 304 | ;; 305 | "$OPTC") 306 | echo "On to next step." 307 | break 308 | ;; 309 | "$OPTQ" | "quit") 310 | echo "Quitting program." 311 | exit 0 312 | ;; 313 | *) echo "invalid option $REPLY" ;; 314 | esac 315 | done 316 | 317 | echo "Bye" 318 | 319 | exit 0 320 | -------------------------------------------------------------------------------- /src/emoji_verify.rs: -------------------------------------------------------------------------------- 1 | // 2 | // https://www.github.com/8go/matrix-commander-rs 3 | // emoji_verify.rs 4 | // 5 | 6 | //! Module that bundles everything together do to emoji verification for Matrix. 7 | //! It implements the emoji-verification protocol. 8 | 9 | use std::io::{self, Write}; 10 | use tracing::{debug, error, info, warn}; 11 | 12 | use futures_util::StreamExt; 13 | 14 | // Code for emoji verify 15 | use matrix_sdk::{ 16 | self, 17 | config::SyncSettings, 18 | encryption::verification::{ 19 | format_emojis, Emoji, SasState, SasVerification, Verification, VerificationRequest, 20 | VerificationRequestState, 21 | }, 22 | ruma::{ 23 | events::{ 24 | key::verification::{ 25 | accept::ToDeviceKeyVerificationAcceptEvent, 26 | cancel::ToDeviceKeyVerificationCancelEvent, 27 | done::{OriginalSyncKeyVerificationDoneEvent, ToDeviceKeyVerificationDoneEvent}, 28 | key::{OriginalSyncKeyVerificationKeyEvent, ToDeviceKeyVerificationKeyEvent}, 29 | // mac::{ToDeviceKeyVerificationMacEvent}, 30 | ready::ToDeviceKeyVerificationReadyEvent, 31 | request::ToDeviceKeyVerificationRequestEvent, 32 | start::OriginalSyncKeyVerificationStartEvent, 33 | start::ToDeviceKeyVerificationStartEvent, 34 | VerificationMethod, 35 | }, 36 | room::message::{MessageType, OriginalSyncRoomMessageEvent, SyncRoomMessageEvent}, 37 | }, 38 | OwnedDeviceId, OwnedUserId, UserId, 39 | }, 40 | Client, 41 | }; 42 | // local 43 | use crate::get_prog_without_ext; 44 | 45 | async fn wait_for_confirmation(sas: SasVerification, emoji: [Emoji; 7]) { 46 | println!("\nDo the emojis match: \n{}", format_emojis(emoji)); 47 | print!("Confirm with `yes` or cancel with `no`: "); 48 | if let Err(e) = io::stdout().flush() { 49 | warn!("Warning: Failed to flush stdout: {e}"); 50 | } 51 | let mut input = String::new(); 52 | if io::stdin().read_line(&mut input).is_err() { 53 | error!("Error: Unable to read user input. Cancelling."); 54 | input = "no".to_string(); // cancel 55 | } 56 | match input.trim().to_lowercase().as_ref() { 57 | "yes" | "true" | "ok" => sas.confirm().await.unwrap(), 58 | _ => sas.cancel().await.unwrap(), 59 | } 60 | } 61 | 62 | /// Utility function to print confirmed verification results 63 | fn print_success(sas: &SasVerification) { 64 | let device = sas.other_device(); 65 | 66 | println!( 67 | "Successfully verified device {} {}, local trust state: {:?}", 68 | device.user_id(), 69 | device.device_id(), 70 | device.local_trust_state() 71 | ); 72 | 73 | println!("\nDo more Emoji verifications or hit Control-C to terminate program.\n"); 74 | } 75 | 76 | /// Utility functions to show all devices of the user and their verification state. 77 | async fn print_devices(user_id: &UserId, client: &Client) { 78 | info!("Devices of user {}", user_id); 79 | 80 | for device in client 81 | .encryption() 82 | .get_user_devices(user_id) 83 | .await 84 | .unwrap() 85 | .devices() 86 | { 87 | info!( 88 | " {:<10} {:<30} is_verified={:<}", 89 | device.device_id(), 90 | device.display_name().unwrap_or("-"), 91 | device.is_verified() 92 | ); 93 | } 94 | } 95 | 96 | async fn sas_verification_handler(client: Client, sas: SasVerification) { 97 | println!( 98 | "Starting verification with {} {}", 99 | &sas.other_device().user_id(), 100 | &sas.other_device().device_id() 101 | ); 102 | print_devices(sas.other_device().user_id(), &client).await; 103 | sas.accept().await.unwrap(); 104 | 105 | let mut stream = sas.changes(); 106 | 107 | while let Some(state) = stream.next().await { 108 | match state.clone() { 109 | SasState::KeysExchanged { 110 | emojis, 111 | decimals: _, 112 | } => { 113 | debug!( 114 | "sas_verification_handler: state {:?} (SasState::KeysExchanged)", 115 | state 116 | ); 117 | tokio::spawn(wait_for_confirmation( 118 | sas.clone(), 119 | emojis 120 | .expect("Error: We only support verifications using emojis") 121 | .emojis, 122 | )); 123 | } 124 | SasState::Done { .. } => { 125 | debug!( 126 | "sas_verification_handler: state {:?} (SasState::Done)", 127 | state 128 | ); 129 | print_success(&sas); 130 | print_devices(sas.other_device().user_id(), &client).await; 131 | break; 132 | } 133 | SasState::Cancelled(cancel_info) => { 134 | println!( 135 | "The verification has been cancelled, reason: {}", 136 | cancel_info.reason() 137 | ); 138 | 139 | break; 140 | } 141 | SasState::Started { .. } | SasState::Accepted { .. } | SasState::Confirmed => { 142 | debug!("sas_verification_handler: state {:?} ignored", state); 143 | } 144 | } 145 | } 146 | } 147 | 148 | async fn request_verification_handler(client: Client, request: VerificationRequest) { 149 | println!( 150 | "Accepting verification request from {}", 151 | request.other_user_id(), 152 | ); 153 | request 154 | .accept() 155 | .await 156 | .expect("Error: Can't accept verification request"); 157 | 158 | let mut stream = request.changes(); 159 | 160 | while let Some(state) = stream.next().await { 161 | match state.clone() { 162 | VerificationRequestState::Created { .. } 163 | | VerificationRequestState::Requested { .. } 164 | | VerificationRequestState::Ready { .. } => { 165 | debug!("request_verification_handler: state {:?} ignored", state); 166 | } 167 | VerificationRequestState::Transitioned { verification } => { 168 | // We only support SAS verification. 169 | debug!( 170 | "request_verification_handler: state {:?}, Verification state transitioned.", 171 | state 172 | ); 173 | if let Verification::SasV1(s) = verification { 174 | debug!("request_verification_handler: Verification state transitioned to Emoji verification."); 175 | tokio::spawn(sas_verification_handler(client, s)); 176 | break; 177 | } 178 | } 179 | VerificationRequestState::Done | VerificationRequestState::Cancelled(_) => { 180 | debug!( 181 | "request_verification_handler: state {:?} forces us to stop", 182 | state 183 | ); 184 | break; 185 | } 186 | } 187 | } 188 | } 189 | 190 | /// Go into the event loop and implement the emoji verification protocol. 191 | /// We are waiting for someone else to request the verification. 192 | /// This is the main function, the access point, to emoji verification. 193 | /// Remember it is interactive and will remain in the event loop until user 194 | /// leaves with Control-C. 195 | pub async fn sync_wait_for_verification_request(client: &Client) -> matrix_sdk::Result<()> { 196 | client.add_event_handler( 197 | |ev: ToDeviceKeyVerificationRequestEvent, client: Client| async move { 198 | debug!("ToDeviceKeyVerificationRequestEvent: entering"); 199 | let request = client 200 | .encryption() 201 | .get_verification_request(&ev.sender, &ev.content.transaction_id) 202 | .await 203 | .expect("Error: Request object wasn't created"); 204 | 205 | tokio::spawn(request_verification_handler(client, request)); 206 | 207 | debug!("ToDeviceKeyVerificationRequestEvent: leaving"); 208 | }, 209 | ); 210 | 211 | client.add_event_handler( 212 | |ev: OriginalSyncRoomMessageEvent, client: Client| async move { 213 | debug!("OriginalSyncRoomMessageEvent: entering"); 214 | if let MessageType::VerificationRequest(_) = &ev.content.msgtype { 215 | let request = client 216 | .encryption() 217 | .get_verification_request(&ev.sender, &ev.event_id) 218 | .await 219 | .expect("Error: Request object wasn't created"); 220 | 221 | tokio::spawn(request_verification_handler(client, request)); 222 | 223 | debug!("OriginalSyncRoomMessageEvent: leaving"); 224 | } 225 | }, 226 | ); 227 | 228 | // // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 229 | // client.add_event_handler( 230 | // |ev: ToDeviceKeyVerificationStartEvent, client: Client| async move { 231 | // debug!("ToDeviceKeyVerificationStartEvent"); 232 | // if let Some(Verification::SasV1(sas)) = client 233 | // .encryption() 234 | // .get_verification(&ev.sender, ev.content.transaction_id.as_str()) 235 | // .await 236 | // { 237 | // info!( 238 | // "Starting verification with {} {}", 239 | // &sas.other_device().user_id(), 240 | // &sas.other_device().device_id() 241 | // ); 242 | // print_devices(&ev.sender, &client).await; 243 | // sas.accept().await.unwrap(); 244 | // } 245 | // }, 246 | // ); 247 | 248 | // // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 249 | // client.add_event_handler( 250 | // |ev: ToDeviceKeyVerificationKeyEvent, client: Client| async move { 251 | // debug!("ToDeviceKeyVerificationKeyEvent"); 252 | // if let Some(Verification::SasV1(sas)) = client 253 | // .encryption() 254 | // .get_verification(&ev.sender, ev.content.transaction_id.as_str()) 255 | // .await 256 | // { 257 | // tokio::spawn(sas_verification_handler(client, sas)); 258 | // } 259 | // }, 260 | // ); 261 | 262 | // // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 263 | // client.add_event_handler( 264 | // |ev: ToDeviceKeyVerificationDoneEvent, client: Client| async move { 265 | // debug!("ToDeviceKeyVerificationDoneEvent"); 266 | // if let Some(Verification::SasV1(sas)) = client 267 | // .encryption() 268 | // .get_verification(&ev.sender, ev.content.transaction_id.as_str()) 269 | // .await 270 | // { 271 | // if sas.is_done() { 272 | // print_success(&sas); 273 | // print_devices(&ev.sender, &client).await; 274 | // } 275 | // } 276 | // }, 277 | // ); 278 | 279 | // // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 280 | // client.add_event_handler( 281 | // |ev: OriginalSyncKeyVerificationStartEvent, client: Client| async move { 282 | // debug!("OriginalSyncKeyVerificationStartEvent"); 283 | // if let Some(Verification::SasV1(sas)) = client 284 | // .encryption() 285 | // .get_verification(&ev.sender, ev.content.relates_to.event_id.as_str()) 286 | // .await 287 | // { 288 | // println!( 289 | // "Starting verification with {} {}", 290 | // &sas.other_device().user_id(), 291 | // &sas.other_device().device_id() 292 | // ); 293 | // print_devices(&ev.sender, &client).await; 294 | // sas.accept().await.unwrap(); 295 | // } 296 | // }, 297 | // ); 298 | 299 | // // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 300 | // client.add_event_handler( 301 | // |ev: OriginalSyncKeyVerificationKeyEvent, client: Client| async move { 302 | // debug!("OriginalSyncKeyVerificationKeyEvent"); 303 | // if let Some(Verification::SasV1(sas)) = client 304 | // .encryption() 305 | // .get_verification(&ev.sender, ev.content.relates_to.event_id.as_str()) 306 | // .await 307 | // { 308 | // tokio::spawn(sas_verification_handler(client, sas)); 309 | // } 310 | // }, 311 | // ); 312 | 313 | // // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 314 | // client.add_event_handler( 315 | // |ev: OriginalSyncKeyVerificationDoneEvent, client: Client| async move { 316 | // debug!("OriginalSyncKeyVerificationDoneEvent"); 317 | // if let Some(Verification::SasV1(sas)) = client 318 | // .encryption() 319 | // .get_verification(&ev.sender, ev.content.relates_to.event_id.as_str()) 320 | // .await 321 | // { 322 | // if sas.is_done() { 323 | // print_success(&sas); 324 | // print_devices(&ev.sender, &client).await; 325 | // } 326 | // } 327 | // }, 328 | // ); 329 | 330 | // go into event loop to sync and to execute verify protocol 331 | println!("Ready and waiting ..."); 332 | println!("Go to other Matrix client like Element and initiate Emoji verification there."); 333 | println!("Best to have the other Matrix client ready and waiting before you start"); 334 | println!("{}.", get_prog_without_ext()); 335 | client.sync(SyncSettings::new()).await?; 336 | 337 | Ok(()) 338 | } 339 | 340 | // ############################################################################################### 341 | 342 | /// Go into the event loop and implement the emoji verification protocol. 343 | /// We are initiating the verification witn device recipient_device. 344 | /// This is the main function, the access point, to emoji verification. 345 | /// Remember it is interactive and will remain in the event loop until user 346 | /// leaves with Control-C. 347 | pub async fn sync_request_verification( 348 | client: &Client, 349 | recipient_user: String, 350 | recipient_device: String, 351 | ) -> matrix_sdk::Result<()> { 352 | client.add_event_handler( 353 | |ev: ToDeviceKeyVerificationRequestEvent, client: Client| async move { 354 | debug!("ToDeviceKeyVerificationRequestEvent: entering"); 355 | let request = client 356 | .encryption() 357 | .get_verification_request(&ev.sender, &ev.content.transaction_id) 358 | .await 359 | .expect("Error: Request object wasn't created"); 360 | 361 | tokio::spawn(request_verification_handler(client, request)); 362 | debug!("ToDeviceKeyVerificationRequestEvent: leaving"); 363 | }, 364 | ); 365 | 366 | client.add_event_handler( 367 | |ev: OriginalSyncRoomMessageEvent, client: Client| async move { 368 | debug!("OriginalSyncRoomMessageEvent: entering"); 369 | if let MessageType::VerificationRequest(_) = &ev.content.msgtype { 370 | let request = client 371 | .encryption() 372 | .get_verification_request(&ev.sender, &ev.event_id) 373 | .await 374 | .expect("Error: Request object wasn't created"); 375 | 376 | tokio::spawn(request_verification_handler(client, request)); 377 | } 378 | debug!("OriginalSyncRoomMessageEvent: leaving"); 379 | }, 380 | ); 381 | 382 | client.add_event_handler(|_ev: SyncRoomMessageEvent, _client: Client| async move { 383 | debug!("SyncRoomMessageEvent"); 384 | }); 385 | 386 | // needed as of Sept 2024 387 | client.add_event_handler( 388 | |ev: ToDeviceKeyVerificationStartEvent, client: Client| async move { 389 | debug!("ToDeviceKeyVerificationStartEvent"); 390 | if let Some(Verification::SasV1(sas)) = client 391 | .encryption() 392 | .get_verification(&ev.sender, ev.content.transaction_id.as_str()) 393 | .await 394 | { 395 | debug!( 396 | "ToDeviceKeyVerificationStartEvent: Verification state has Emoji verification." 397 | ); 398 | tokio::spawn(sas_verification_handler(client, sas)); 399 | } 400 | }, 401 | ); 402 | 403 | // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 404 | client.add_event_handler( 405 | |_ev: ToDeviceKeyVerificationReadyEvent, _client: Client| async move { 406 | debug!("ToDeviceKeyVerificationReadyEvent"); 407 | }, 408 | ); 409 | 410 | // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 411 | client.add_event_handler( 412 | |_ev: ToDeviceKeyVerificationAcceptEvent, _client: Client| async move { 413 | debug!("ToDeviceKeyVerificationAcceptEvent"); 414 | }, 415 | ); 416 | 417 | // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 418 | client.add_event_handler( 419 | |_ev: ToDeviceKeyVerificationCancelEvent, _client: Client| async move { 420 | debug!("ToDeviceKeyVerificationCancelEvent"); 421 | }, 422 | ); 423 | 424 | // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 425 | client.add_event_handler( 426 | |_ev: ToDeviceKeyVerificationKeyEvent, _client: Client| async move { 427 | debug!("ToDeviceKeyVerificationKeyEvent"); 428 | // if let Some(Verification::SasV1(sas)) = client 429 | // .encryption() 430 | // .get_verification(&ev.sender, ev.content.transaction_id.as_str()) 431 | // .await 432 | // { 433 | // tokio::spawn(sas_verification_handler(client, sas)); 434 | // } 435 | }, 436 | ); 437 | 438 | // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 439 | client.add_event_handler( 440 | |_ev: ToDeviceKeyVerificationDoneEvent, _client: Client| async move { 441 | debug!("ToDeviceKeyVerificationDoneEvent"); 442 | // if let Some(Verification::SasV1(sas)) = client 443 | // .encryption() 444 | // .get_verification(&ev.sender, ev.content.transaction_id.as_str()) 445 | // .await 446 | // { 447 | // if sas.is_done() { 448 | // print_success(&sas); 449 | // print_devices(&ev.sender, &client).await; 450 | // } 451 | // } 452 | }, 453 | ); 454 | 455 | // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 456 | client.add_event_handler( 457 | |_ev: OriginalSyncKeyVerificationStartEvent, _client: Client| async move { 458 | debug!("OriginalSyncKeyVerificationStartEvent"); 459 | // if let Some(Verification::SasV1(sas)) = client 460 | // .encryption() 461 | // .get_verification(&ev.sender, ev.content.relates_to.event_id.as_str()) 462 | // .await 463 | // { 464 | // println!( 465 | // "Starting verification with {} {}", 466 | // &sas.other_device().user_id(), 467 | // &sas.other_device().device_id() 468 | // ); 469 | // print_devices(&ev.sender, &client).await; 470 | // sas.accept().await.unwrap(); 471 | // } 472 | }, 473 | ); 474 | 475 | // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 476 | client.add_event_handler( 477 | |_ev: OriginalSyncKeyVerificationKeyEvent, _client: Client| async move { 478 | debug!("OriginalSyncKeyVerificationKeyEvent"); 479 | // if let Some(Verification::SasV1(sas)) = client 480 | // .encryption() 481 | // .get_verification(&ev.sender, ev.content.relates_to.event_id.as_str()) 482 | // .await 483 | // { 484 | // tokio::spawn(sas_verification_handler(client, sas)); 485 | // } 486 | }, 487 | ); 488 | 489 | // removed Sept 2024, following matrix-rust-sdk/examples/emoji_verification 490 | client.add_event_handler( 491 | |_ev: OriginalSyncKeyVerificationDoneEvent, _client: Client| async move { 492 | debug!("OriginalSyncKeyVerificationDoneEvent"); 493 | // if let Some(Verification::SasV1(sas)) = client 494 | // .encryption() 495 | // .get_verification(&ev.sender, ev.content.relates_to.event_id.as_str()) 496 | // .await 497 | // { 498 | // if sas.is_done() { 499 | // print_success(&sas); 500 | // print_devices(&ev.sender, &client).await; 501 | // } 502 | // } 503 | }, 504 | ); 505 | 506 | // go into event loop to sync and to execute verify protocol 507 | println!("Ready and waiting ..."); 508 | println!("We send request to other Matrix client like Element and initiate Emoji "); 509 | println!("verification with them. Best to have the other Matrix client ready and "); 510 | println!("waiting before you start {}.", get_prog_without_ext()); 511 | println!( 512 | "\n ### THIS IS PARTIALLY BROKEN. DOES NOT SEEM TO WORK WITH ELEMENT ANDROID APP. ###\ 513 | \n ### BUT IT DOES WORK WITH ELEMENT WEB APP IN BROWSER. ###\n" 514 | ); 515 | println!( 516 | "Sending request to user's {:?} device {:?}.", 517 | recipient_user, recipient_device 518 | ); 519 | 520 | let encryption = client.encryption(); 521 | let userid: OwnedUserId = UserId::parse(recipient_user).unwrap(); 522 | let deviceid: OwnedDeviceId = OwnedDeviceId::from(recipient_device); 523 | match encryption.get_device(&userid, &deviceid).await { 524 | Ok(Some(device)) => { 525 | // -> Result, CryptoStoreError> 526 | debug!( 527 | "Is device {} already verified? {:?}", 528 | device.device_id(), 529 | device.is_verified() 530 | ); 531 | 532 | // if !device.is_verified() { 533 | // We don't want to support showing a QR code, we only support SAS 534 | // verification 535 | let methods = vec![VerificationMethod::SasV1]; 536 | let verification = device.request_verification_with_methods(methods).await?; 537 | // let verification = device.request_verification().await?; 538 | debug!( 539 | "verification: we_started is {:?}", 540 | verification.we_started() 541 | ); 542 | debug!( 543 | "verification with device {} was requested.", 544 | device.device_id() 545 | ); 546 | // } 547 | } 548 | Ok(None) => error!("Error: device not found: {:?}", deviceid), 549 | Err(e) => error!("Error: could not get device: {:?}", e), 550 | } 551 | client.sync(SyncSettings::new()).await?; 552 | 553 | Ok(()) 554 | } 555 | -------------------------------------------------------------------------------- /src/listen.rs: -------------------------------------------------------------------------------- 1 | // 2 | // https://www.github.com/8go/matrix-commander-rs 3 | // listen.rs 4 | // 5 | 6 | //! Module that bundles code together that uses the `matrix-sdk` API. 7 | //! Primarily the matrix_sdk::Client API 8 | //! (see ). 9 | //! This module implements the matrix-sdk-based portions of the primitives 10 | //! 'listen', i.e. receiving and listening. 11 | 12 | //use std::borrow::Cow; 13 | // use std::env; 14 | //use std::fs; 15 | // use std::fs::File; 16 | // use std::io::{self, Write}; 17 | // use std::ops::Deref; 18 | // use std::path::Path; 19 | //use serde::{Deserialize, Serialize}; 20 | //use serde_json::Result; 21 | // use std::path::PathBuf; 22 | use tracing::{debug, error, info, warn}; 23 | // use thiserror::Error; 24 | // use directories::ProjectDirs; 25 | // use serde::{Deserialize, Serialize}; 26 | 27 | use matrix_sdk::{ 28 | config::SyncSettings, 29 | event_handler::Ctx, 30 | // SessionMeta, 31 | room::MessagesOptions, 32 | // room, 33 | room::Room, 34 | // ruma:: 35 | ruma::{ 36 | api::client::{ 37 | filter::{FilterDefinition, /* LazyLoadOptions, */ RoomEventFilter, RoomFilter}, 38 | sync::sync_events::v3::Filter, 39 | // sync::sync_events, 40 | }, 41 | events::room::encrypted::{ 42 | OriginalSyncRoomEncryptedEvent, 43 | /* RoomEncryptedEventContent, */ SyncRoomEncryptedEvent, 44 | }, 45 | events::room::message::{ 46 | AudioMessageEventContent, 47 | // EmoteMessageEventContent, 48 | FileMessageEventContent, 49 | ImageMessageEventContent, 50 | MessageType, 51 | // NoticeMessageEventContent, 52 | // OriginalRoomMessageEvent, OriginalSyncRoomMessageEvent, 53 | // RedactedRoomMessageEventContent, RoomMessageEvent, 54 | // OriginalSyncRoomEncryptedEvent, 55 | RedactedSyncRoomMessageEvent, 56 | RoomMessageEventContent, 57 | SyncRoomMessageEvent, 58 | TextMessageEventContent, 59 | VideoMessageEventContent, 60 | }, 61 | events::room::redaction::{ 62 | OriginalSyncRoomRedactionEvent, RedactedSyncRoomRedactionEvent, SyncRoomRedactionEvent, 63 | }, 64 | events::{ 65 | AnyMessageLikeEvent, 66 | AnyTimelineEvent, 67 | MessageLikeEvent, 68 | OriginalSyncMessageLikeEvent, 69 | // OriginalMessageLikeEvent, // MessageLikeEventContent, 70 | SyncMessageLikeEvent, 71 | }, 72 | // OwnedRoomAliasId, 73 | OwnedRoomId, 74 | OwnedUserId, 75 | // serde::Raw, 76 | // events::OriginalMessageLikeEvent, 77 | RoomId, 78 | // UserId, 79 | // OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, 80 | // device_id, room_id, session_id, user_id, OwnedDeviceId, OwnedUserId, 81 | UInt, 82 | }, 83 | Client, 84 | }; 85 | 86 | /// Declare the items used from main.rs 87 | use crate::{Error, Output}; 88 | 89 | /// Lower-level utility function to handle originalsyncmessagelikeevent 90 | fn handle_originalsyncmessagelikeevent( 91 | ev: &OriginalSyncMessageLikeEvent, 92 | room_id: &OwnedRoomId, 93 | context: &Ctx, 94 | ) { 95 | // --output json is handled above this level, 96 | // if Json is output this event processing is never needed and never reached 97 | debug!( 98 | "New message: {:?} from sender {:?}, room {:?}, event_id {:?}", 99 | ev.content, 100 | ev.sender, 101 | room_id, // ev does not contain room! 102 | ev.event_id, 103 | ); 104 | if context.whoami != ev.sender || context.listen_self { 105 | // The compiler knows that it is RoomMessageEventContent, because it comes from room::messages() 106 | // print_type_of(&orginialmessagelikeevent.content); // ruma_common::events::room::message::RoomMessageEventContent 107 | match ev.content.msgtype.to_owned() { 108 | MessageType::Text(textmessageeventcontent) => { 109 | // debug!("Msg of type Text"); 110 | let TextMessageEventContent { 111 | body, 112 | formatted, 113 | // message, 114 | .. 115 | } = textmessageeventcontent; 116 | println!( 117 | "Message: type Text: body {:?}, room {:?}, sender {:?}, event id {:?}, formatted {:?}, ", 118 | body, room_id, ev.sender, ev.event_id, formatted, 119 | ); 120 | } 121 | MessageType::File(filemessageeventcontent) => { 122 | // debug!("Msg of type File"); 123 | let FileMessageEventContent { 124 | body, 125 | filename, 126 | source, 127 | info, 128 | // message, 129 | // file, 130 | .. 131 | } = filemessageeventcontent; 132 | println!( 133 | "Message: type File: body {:?}, room {:?}, sender {:?}, event id {:?}, filename {:?}, source {:?}, info {:?}", 134 | body, room_id, ev.sender, ev.event_id, filename, source, info, 135 | ); 136 | } 137 | MessageType::Image(imagemessageeventcontent) => { 138 | // debug!("Msg of type File"); 139 | let ImageMessageEventContent { 140 | body, source, info, .. 141 | } = imagemessageeventcontent; 142 | println!( 143 | "Message: type Image: body {:?}, room {:?}, sender {:?}, event id {:?}, source {:?}, info {:?}", 144 | body, room_id, ev.sender, ev.event_id, source, info, 145 | ); 146 | } 147 | MessageType::Audio(audiomessageeventcontent) => { 148 | // debug!("Msg of type File"); 149 | let AudioMessageEventContent { 150 | body, source, info, .. 151 | } = audiomessageeventcontent; 152 | println!( 153 | "Message: type Image: body {:?}, room {:?}, sender {:?}, event id {:?}, source {:?}, info {:?}", 154 | body, room_id, ev.sender, ev.event_id, source, info, 155 | ); 156 | } 157 | MessageType::Video(videomessageeventcontent) => { 158 | // debug!("Msg of type File"); 159 | let VideoMessageEventContent { 160 | body, source, info, .. 161 | } = videomessageeventcontent; 162 | println!( 163 | "Message: type Image: body {:?}, room {:?}, sender {:?}, event id {:?}, source {:?}, info {:?}", 164 | body, room_id, ev.sender, ev.event_id, source, info, 165 | ); 166 | } 167 | _ => { 168 | debug!("Not handling this event: {:?}", ev); 169 | warn!( 170 | "Not handling this message type. Not implemented yet. {:?}", 171 | ev 172 | ); 173 | } 174 | } 175 | } else { 176 | debug!("Skipping message from itself because --listen-self is not set."); 177 | } 178 | } 179 | 180 | /// Utility function to handle RedactedSyncRoomMessageEvent events. 181 | // None of the args can be borrowed because this function is passed into a spawned process. 182 | async fn handle_redactedsyncroommessageevent( 183 | ev: RedactedSyncRoomMessageEvent, 184 | room: Room, 185 | _client: Client, 186 | context: Ctx, 187 | ) { 188 | debug!( 189 | "Received a message for RedactedSyncRoomMessageEvent. {:?}", 190 | ev 191 | ); 192 | if context.whoami == ev.sender && !context.listen_self { 193 | debug!("Skipping message from itself because --listen-self is not set."); 194 | return; 195 | } 196 | if !context.output.is_text() { 197 | // Serialize it to a JSON string. 198 | let j = match serde_json::to_string(&ev.content) { 199 | Ok(jsonstr) => { 200 | // this event does not contain the room_id, other events do. 201 | // People are missing the room_id in output. 202 | // Nasty hack: inserting the room_id into the JSON string. 203 | let mut s = jsonstr; 204 | s.insert_str(s.len() - 1, ",\"event_id\":\"\""); 205 | s.insert_str(s.len() - 2, ev.event_id.as_str()); 206 | s.insert_str(s.len() - 1, ",\"sender\":\"\""); 207 | s.insert_str(s.len() - 2, ev.sender.as_str()); 208 | s.insert_str(s.len() - 1, ",\"origin_server_ts\":\"\""); 209 | s.insert_str(s.len() - 2, &ev.origin_server_ts.0.to_string()); 210 | s.insert_str(s.len() - 1, ",\"room_id\":\"\""); 211 | s.insert_str(s.len() - 2, room.room_id().as_str()); 212 | s 213 | } 214 | Err(e) => e.to_string(), 215 | }; 216 | println!("{}", j); 217 | return; 218 | } 219 | debug!( 220 | "Received a message for RedactedSyncRoomMessageEvent. Not implemented yet for text format, try --output json. {:?}", 221 | ev 222 | ); 223 | } 224 | 225 | fn handle_originalsyncroomredactionevent(ev: OriginalSyncRoomRedactionEvent, room: Room) { 226 | debug!( 227 | "Received a message for OriginalSyncRoomRedactionEvent. {:?}", 228 | ev 229 | ); 230 | // Serialize it to a JSON string. 231 | let j = match serde_json::to_string(&ev.content) { 232 | Ok(jsonstr) => { 233 | // this event does not contain the room_id, other events do. 234 | // People are missing the room_id in output. 235 | // Nasty hack: inserting the room_id into the JSON string. 236 | let mut s = jsonstr; 237 | s.insert_str(s.len() - 1, ",\"event_id\":\"\""); 238 | s.insert_str(s.len() - 2, ev.event_id.as_str()); 239 | s.insert_str(s.len() - 1, ",\"sender\":\"\""); 240 | s.insert_str(s.len() - 2, ev.sender.as_str()); 241 | s.insert_str(s.len() - 1, ",\"origin_server_ts\":\"\""); 242 | s.insert_str(s.len() - 2, &ev.origin_server_ts.0.to_string()); 243 | s.insert_str(s.len() - 1, ",\"room_id\":\"\""); 244 | s.insert_str(s.len() - 2, room.room_id().as_str()); 245 | s 246 | } 247 | Err(e) => e.to_string(), 248 | }; 249 | println!("{}", j); 250 | } 251 | 252 | fn handle_redactedsyncroomredactionevent(ev: RedactedSyncRoomRedactionEvent, room: Room) { 253 | debug!( 254 | "Received a message for RedactedSyncRoomRedactionEvent. {:?}", 255 | ev 256 | ); 257 | // Serialize it to a JSON string. 258 | let j = match serde_json::to_string(&ev.content) { 259 | Ok(jsonstr) => { 260 | // this event does not contain the room_id, other events do. 261 | // People are missing the room_id in output. 262 | // Nasty hack: inserting the room_id into the JSON string. 263 | let mut s = jsonstr; 264 | s.insert_str(s.len() - 1, ",\"event_id\":\"\""); 265 | s.insert_str(s.len() - 2, ev.event_id.as_str()); 266 | s.insert_str(s.len() - 1, ",\"sender\":\"\""); 267 | s.insert_str(s.len() - 2, ev.sender.as_str()); 268 | s.insert_str(s.len() - 1, ",\"origin_server_ts\":\"\""); 269 | s.insert_str(s.len() - 2, &ev.origin_server_ts.0.to_string()); 270 | s.insert_str(s.len() - 1, ",\"room_id\":\"\""); 271 | s.insert_str(s.len() - 2, room.room_id().as_str()); 272 | s 273 | } 274 | Err(e) => e.to_string(), 275 | }; 276 | println!("{}", j); 277 | } 278 | 279 | /// Utility function to handle SyncRoomRedactionEvent events. 280 | // None of the args can be borrowed because this function is passed into a spawned process. 281 | async fn handle_syncroomredactedevent( 282 | ev: SyncRoomRedactionEvent, 283 | room: Room, 284 | _client: Client, 285 | context: Ctx, 286 | ) { 287 | debug!("Received a message for SyncRoomRedactionEvent. {:?}", ev); 288 | if context.whoami == ev.sender() && !context.listen_self { 289 | debug!("Skipping message from itself because --listen-self is not set."); 290 | return; 291 | } 292 | if !context.output.is_text() { 293 | // Serialize it to a JSON string. 294 | match ev { 295 | SyncRoomRedactionEvent::Original(evi) => { 296 | handle_originalsyncroomredactionevent(evi, room) 297 | } 298 | SyncRoomRedactionEvent::Redacted(evi) => { 299 | handle_redactedsyncroomredactionevent(evi, room) 300 | } 301 | } 302 | return; 303 | } 304 | debug!( 305 | "Received a message for SyncRoomRedactionEvent. Not implemented yet for text format, try --output json. {:?}", 306 | ev 307 | ); 308 | } 309 | 310 | /// Utility function to handle SyncRoomEncryptedEvent events. 311 | // None of the args can be borrowed because this function is passed into a spawned process. 312 | async fn handle_syncroomencryptedevent( 313 | ev: SyncRoomEncryptedEvent, 314 | room: Room, 315 | _client: Client, 316 | context: Ctx, 317 | ) { 318 | debug!("Received a SyncRoomEncryptedEvent message {:?}", ev); 319 | if context.whoami == ev.sender() && !context.listen_self { 320 | debug!("Skipping message from itself because --listen-self is not set."); 321 | return; 322 | } 323 | match ev { 324 | SyncMessageLikeEvent::Original(orginialmessagelikeevent) => { 325 | debug!( 326 | "New message: {:?} from sender {:?}, room {:?}, event_id {:?}", 327 | orginialmessagelikeevent.content, 328 | orginialmessagelikeevent.sender, 329 | room.room_id(), // "", // ev does not contain room! 330 | orginialmessagelikeevent.event_id, 331 | ); 332 | // let jroom = join_room(); 333 | // let _res = jroom.decrypt_event(&ev).await?; 334 | // Todo: attempt to decrypt msg 335 | } 336 | _ => { 337 | debug!( 338 | "Received a message for RedactedSyncMessageLikeEvent. Not implemented yet. {:?}", 339 | ev 340 | ); 341 | } 342 | } 343 | warn!("Decryption attempt not implemented yet."); 344 | } 345 | 346 | /// Utility function to handle OriginalSyncRoomEncryptedEvent events. 347 | // None of the args can be borrowed because this function is passed into a spawned process. 348 | async fn handle_originalsyncroomencryptedevent( 349 | ev: OriginalSyncRoomEncryptedEvent, 350 | room: Room, 351 | _client: Client, 352 | context: Ctx, 353 | ) { 354 | debug!("Received a OriginalSyncRoomEncryptedEvent message {:?}", ev); 355 | if context.whoami == ev.sender && !context.listen_self { 356 | debug!("Skipping message from itself because --listen-self is not set."); 357 | return; 358 | } 359 | debug!( 360 | "New message: {:?} from sender {:?}, room {:?}, event_id {:?}", 361 | ev.content, 362 | ev.sender, 363 | room.room_id(), // "", // ev does not contain room! 364 | ev.event_id, 365 | ); 366 | // let jroom = join_room(); 367 | // let _res = jroom.decrypt_event(&ev).await?; 368 | // Todo: attempt to decrypt msg 369 | warn!("Decryption attempt not implemented yet."); 370 | } 371 | 372 | /// Utility function to handle SyncRoomMessageEvent events. 373 | // None of the args can be borrowed because this function is passed into a spawned process. 374 | async fn handle_syncroommessageevent( 375 | ev: SyncRoomMessageEvent, 376 | room: Room, 377 | _client: Client, 378 | context: Ctx, 379 | ) { 380 | debug!("Received a message for event SyncRoomMessageEvent {:?}", ev); 381 | if context.whoami == ev.sender() && !context.listen_self { 382 | debug!("Skipping message from itself because --listen-self is not set."); 383 | return; 384 | } 385 | match ev { 386 | SyncMessageLikeEvent::Original(orginialmessagelikeevent) => { 387 | if !context.output.is_text() { 388 | // Serialize it to a JSON string. 389 | let j = match serde_json::to_string(&orginialmessagelikeevent.content) { 390 | Ok(jsonstr) => { 391 | // this event does not contain the room_id, other events do. 392 | // People are missing the room_id in output. 393 | // Nasty hack: inserting the room_id into the JSON string. 394 | let mut s = jsonstr; 395 | s.insert_str(s.len() - 1, ",\"event_id\":\"\""); 396 | s.insert_str(s.len() - 2, orginialmessagelikeevent.event_id.as_str()); 397 | s.insert_str(s.len() - 1, ",\"sender\":\"\""); 398 | s.insert_str(s.len() - 2, orginialmessagelikeevent.sender.as_str()); 399 | s.insert_str(s.len() - 1, ",\"origin_server_ts\":\"\""); 400 | s.insert_str(s.len() - 2, &orginialmessagelikeevent.origin_server_ts.0.to_string()); 401 | s.insert_str(s.len() - 1, ",\"room_id\":\"\""); 402 | s.insert_str(s.len() - 2, room.room_id().as_str()); 403 | s 404 | } 405 | Err(e) => e.to_string(), 406 | }; 407 | println!("{}", j); 408 | return; 409 | } 410 | handle_originalsyncmessagelikeevent( 411 | &orginialmessagelikeevent, 412 | &RoomId::parse(room.room_id()).unwrap(), 413 | &context, 414 | ); 415 | } 416 | _ => { 417 | debug!( 418 | "Received a message for RedactedSyncMessageLikeEvent. Not implemented yet. {:?}", 419 | ev 420 | ); 421 | } 422 | }; 423 | } 424 | 425 | /// Data structure needed to pass additional arguments into the event handler 426 | #[derive(Clone, Debug)] 427 | struct EvHandlerContext { 428 | whoami: OwnedUserId, 429 | listen_self: bool, 430 | output: Output, 431 | } 432 | 433 | /// Listen to all rooms once. Then continue. 434 | pub(crate) async fn listen_once( 435 | client: &Client, 436 | listen_self: bool, // listen to my own messages? 437 | whoami: OwnedUserId, 438 | output: Output, 439 | ) -> Result<(), Error> { 440 | info!( 441 | "mclient::listen_once(): listen_self {}, room {}", 442 | listen_self, "all" 443 | ); 444 | 445 | let context = EvHandlerContext { 446 | whoami, 447 | listen_self, 448 | output, 449 | }; 450 | 451 | client.add_event_handler_context(context.clone()); 452 | 453 | // Todo: print events nicely and filter by --listen-self 454 | client.add_event_handler(|ev: SyncRoomMessageEvent, room: Room, 455 | client: Client, context: Ctx| async move { 456 | tokio::spawn(handle_syncroommessageevent(ev, room, client, context)); 457 | }); 458 | 459 | client.add_event_handler( 460 | |ev: RedactedSyncRoomMessageEvent, 461 | room: Room, 462 | client: Client, 463 | context: Ctx| async move { 464 | tokio::spawn(handle_redactedsyncroommessageevent( 465 | ev, room, client, context, 466 | )); 467 | }, 468 | ); 469 | 470 | client.add_event_handler( 471 | |ev: SyncRoomRedactionEvent, 472 | room: Room, 473 | client: Client, 474 | context: Ctx| async move { 475 | tokio::spawn(handle_syncroomredactedevent(ev, room, client, context)); 476 | }, 477 | ); 478 | 479 | client.add_event_handler( 480 | |ev: OriginalSyncRoomEncryptedEvent, 481 | room: Room, 482 | client: Client, 483 | context: Ctx| async move { 484 | tokio::spawn(handle_originalsyncroomencryptedevent( 485 | ev, room, client, context, 486 | )); 487 | }, 488 | ); 489 | 490 | client.add_event_handler( 491 | |ev: SyncRoomEncryptedEvent, 492 | room: Room, 493 | client: Client, 494 | context: Ctx| async move { 495 | tokio::spawn(handle_syncroomencryptedevent(ev, room, client, context)); 496 | }, 497 | ); 498 | 499 | // go into event loop to sync and to execute verify protocol 500 | info!("Ready and getting messages from server..."); 501 | 502 | // get the current sync state from server before syncing 503 | // This gets all rooms but ignores msgs from itself. 504 | let settings = SyncSettings::default(); 505 | 506 | client.sync_once(settings).await?; 507 | Ok(()) 508 | } 509 | 510 | /// Listen to all rooms forever. Stay in the event loop. 511 | pub(crate) async fn listen_forever( 512 | client: &Client, 513 | listen_self: bool, // listen to my own messages? 514 | whoami: OwnedUserId, 515 | output: Output, 516 | ) -> Result<(), Error> { 517 | info!( 518 | "mclient::listen_forever(): listen_self {}, room {}", 519 | listen_self, "all" 520 | ); 521 | 522 | let context = EvHandlerContext { 523 | whoami, 524 | listen_self, 525 | output, 526 | }; 527 | 528 | client.add_event_handler_context(context.clone()); 529 | 530 | // Todo: print events nicely and filter by --listen-self 531 | client.add_event_handler( 532 | |ev: SyncRoomMessageEvent, room: Room, client: Client, context: Ctx| async move { 533 | tokio::spawn(handle_syncroommessageevent(ev, room, client, context)); 534 | }); 535 | 536 | client.add_event_handler( 537 | |ev: SyncRoomEncryptedEvent, room: Room, client: Client, context: Ctx| async move { 538 | tokio::spawn(handle_syncroomencryptedevent(ev, room, client, context)); 539 | }); 540 | 541 | client.add_event_handler( 542 | |ev: OriginalSyncRoomEncryptedEvent, 543 | room: Room, 544 | client: Client, 545 | context: Ctx| async move { 546 | tokio::spawn(handle_originalsyncroomencryptedevent( 547 | ev, room, client, context, 548 | )); 549 | }, 550 | ); 551 | 552 | client.add_event_handler( 553 | |ev: RedactedSyncRoomMessageEvent, 554 | room: Room, 555 | client: Client, 556 | context: Ctx| async move { 557 | tokio::spawn(handle_redactedsyncroommessageevent( 558 | ev, room, client, context, 559 | )); 560 | }, 561 | ); 562 | 563 | client.add_event_handler(|ev: SyncRoomRedactionEvent, 564 | room: Room, client: Client, context: Ctx| async move { 565 | tokio::spawn(handle_syncroomredactedevent(ev, room, client, context)); 566 | }); 567 | 568 | // go into event loop to sync and to execute verify protocol 569 | info!("Ready and waiting for messages ..."); 570 | info!("Once done listening, kill the process manually with Control-C."); 571 | 572 | // get the current sync state from server before syncing 573 | let settings = SyncSettings::default(); 574 | 575 | match client.sync(settings).await { 576 | Ok(()) => Ok(()), 577 | Err(e) => { 578 | // this does not catch Control-C 579 | error!("Event loop reported: {:?}", e); 580 | Ok(()) 581 | } 582 | } 583 | } 584 | 585 | #[allow(dead_code)] 586 | fn print_type_of(_: &T) { 587 | println!("{}", std::any::type_name::()) 588 | } 589 | 590 | /// Get last N messages from some specified rooms once, then go on. 591 | /// Listens to the room(s) specified in the argument, prints the last N messasges. 592 | /// The read messages can be already read ones or new unread ones. 593 | /// Then it returns. Less than N messages might be printed if the messages do not exist. 594 | /// Running it twice in a row (while no new messages were sent) should deliver the same output, response. 595 | pub(crate) async fn listen_tail( 596 | client: &Client, 597 | roomnames: &Vec, // roomId 598 | number: u64, // number of messages to print, N 599 | listen_self: bool, // listen to my own messages? 600 | whoami: OwnedUserId, 601 | output: Output, 602 | ) -> Result<(), Error> { 603 | info!( 604 | "mclient::listen_tail(): listen_self {}, roomnames {:?}", 605 | listen_self, roomnames 606 | ); 607 | if roomnames.is_empty() { 608 | return Err(Error::MissingRoom); 609 | } 610 | 611 | // We are *not* using the event manager, no sync()! 612 | 613 | info!("Ready and getting messages from server ..."); 614 | 615 | // convert Vec of strings into a slice of array of OwnedRoomIds 616 | let mut roomids: Vec = Vec::new(); 617 | for roomname in roomnames { 618 | roomids.push(match RoomId::parse(roomname.clone()) { 619 | Ok(id) => id, 620 | Err(ref e) => { 621 | error!( 622 | "Error: invalid room id {:?}. Error reported is {:?}.", 623 | roomname, e 624 | ); 625 | continue; 626 | } 627 | }); 628 | } 629 | let ownedroomidvecoption: Option> = Some(roomids.clone()); 630 | // // old code, when there was only 1 roomname 631 | // let roomclone = roomnames[0].clone(); 632 | // let ownedroomid: OwnedRoomId = RoomId::parse(&roomclone).unwrap(); 633 | // let ownedroomidvec = ownedroomid 634 | // let ownedroomidvecoption: Option> = Some(ownedroomid); 635 | let mut filter = FilterDefinition::default(); 636 | let mut roomfilter = RoomFilter::empty(); 637 | roomfilter.rooms = ownedroomidvecoption; 638 | filter.room = roomfilter; 639 | 640 | // Filter by limit. This works. 641 | // This gets the last N not yet read messages. If all messages had been read, it gets 0 messages. 642 | let mut roomtimeline = RoomEventFilter::empty(); 643 | roomtimeline.limit = UInt::new(number); 644 | filter.room.timeline = roomtimeline; 645 | 646 | // see: https://docs.rs/matrix-sdk/0.6.2/src/matrix_sdk/room/common.rs.html#167-200 647 | // there is also something like next_batch, a value indicating a point in the event timeline 648 | // prev_batch: https://docs.rs/matrix-sdk/0.6.2/src/matrix_sdk/room/common.rs.html#1142-1180 649 | // https://docs.rs/matrix-sdk/0.6.2/matrix_sdk/struct.BaseRoom.html#method.last_prev_batch 650 | // https://docs.rs/matrix-sdk/0.6.2/matrix_sdk/room/struct.Common.html#method.messages 651 | // https://docs.rs/matrix-sdk/0.6.2/matrix_sdk/room/struct.MessagesOptions.html 652 | 653 | let context = EvHandlerContext { 654 | whoami: whoami.clone(), 655 | listen_self, 656 | output, 657 | }; 658 | let ctx = Ctx(context); 659 | 660 | let mut err_count = 0u32; 661 | for roomid in roomids.iter() { 662 | let mut options = MessagesOptions::backward(); // .from("t47429-4392820_219380_26003_2265"); 663 | options.limit = UInt::new(number).unwrap(); 664 | let jroom = client.get_room(roomid.clone().as_ref()).unwrap(); 665 | let msgs = jroom.messages(options).await; 666 | // debug!("\n\nmsgs = {:?} \n\n", msgs); 667 | let chunk = msgs.unwrap().chunk; 668 | for index in 0..chunk.len() { 669 | debug!( 670 | "processing message {:?} out of {:?}", 671 | index + 1, 672 | chunk.len() 673 | ); 674 | let anytimelineevent = &chunk[chunk.len() - 1 - index]; // reverse ordering, getting older msg first 675 | // Todo : dump the JSON serialized string via Json API 676 | 677 | let rawevent: AnyTimelineEvent = anytimelineevent.event.deserialize().unwrap(); 678 | // print_type_of(&rawevent); // ruma_common::events::enums::AnyTimelineEvent 679 | debug!("rawevent = value is {:?}\n", rawevent); 680 | // rawevent = Ok(MessageLike(RoomMessage(Original(OriginalMessageLikeEvent { content: RoomMessageEventContent { 681 | // msgtype: Text(TextMessageEventContent { body: "54", formatted: None }), relates_to: Some(_Custom) }, event_id: "$xxx", sender: "@u:some.homeserver.org", origin_server_ts: MilliSecondsSinceUnixEpoch(123), room_id: "!rrr:some.homeserver.org", unsigned: MessageLikeUnsigned { age: Some(123), transaction_id: None, relations: None } })))) 682 | if !output.is_text() { 683 | println!("{}", anytimelineevent.event.json()); 684 | continue; 685 | } 686 | 687 | match rawevent { 688 | AnyTimelineEvent::MessageLike(anymessagelikeevent) => { 689 | debug!("value: {:?}", anymessagelikeevent); 690 | match anymessagelikeevent { 691 | AnyMessageLikeEvent::RoomMessage(messagelikeevent) => { 692 | debug!("value: {:?}", messagelikeevent); 693 | match messagelikeevent { 694 | MessageLikeEvent::Original(orginialmessagelikeevent) => { 695 | let room_id = orginialmessagelikeevent.room_id.clone(); 696 | let orginialsyncmessagelikeevent = 697 | OriginalSyncMessageLikeEvent::from( 698 | orginialmessagelikeevent, 699 | ); 700 | handle_originalsyncmessagelikeevent( 701 | &orginialsyncmessagelikeevent, 702 | &room_id, 703 | &ctx, 704 | ); 705 | } 706 | _ => { 707 | warn!("RoomMessage type is not handled. Not implemented yet."); 708 | err_count += 1; 709 | } 710 | } 711 | } 712 | AnyMessageLikeEvent::RoomEncrypted(messagelikeevent) => { 713 | warn!( 714 | "Event of type RoomEncrypted received: {:?}", 715 | messagelikeevent 716 | ); 717 | // messagelikeevent is something like 718 | // RoomEncrypted: Original(OriginalMessageLikeEvent { content: RoomEncryptedEventContent { scheme: MegolmV1AesSha2(MegolmV1AesSha2Content { ciphertext: "xxx", sender_key: "yyy", device_id: "DDD", session_id: "sss" }), relates_to: Some(_Custom) }, event_id: "$eee", sender: "@sss:some.homeserver.org", origin_server_ts: MilliSecondsSinceUnixEpoch(123), room_id: "!roomid:some.homeserver.org", 719 | // unsigned: MessageLikeUnsigned { age: Some(123), transaction_id: None, relations: None } }) 720 | // Cannot be decryoted with jroom.decrypt_event(&anytimelineevent.event).await?; 721 | // because decrypt_event() only decrypts events from sync() and not from messages() 722 | 723 | match messagelikeevent { 724 | MessageLikeEvent::Original(orginialmessagelikeevent) => { 725 | debug!( 726 | "New message: {:?} from sender {:?}, room {:?}, event_id {:?}", 727 | orginialmessagelikeevent.content, 728 | orginialmessagelikeevent.sender, 729 | orginialmessagelikeevent.room_id, 730 | orginialmessagelikeevent.event_id, 731 | ); 732 | if whoami != orginialmessagelikeevent.sender || listen_self { 733 | // The compiler knows that it is RoomMessageEventContent, because it comes from room::messages() 734 | // print_type_of(&orginialmessagelikeevent.content); // ruma_common::events::room::message::RoomEncryptedEventContent 735 | println!( 736 | "Message: type Encrypted: body {:?}, room {:?}, sender {:?}, event_id {:?}, message could not be decrypted", 737 | orginialmessagelikeevent.content, orginialmessagelikeevent.room_id, orginialmessagelikeevent.sender, orginialmessagelikeevent.event_id, 738 | ); 739 | // has orginialmessagelikeevent.content.relates_to.unwrap() 740 | } else { 741 | debug!("Skipping message from itself because --listen-self is not set."); 742 | } 743 | } 744 | _ => { 745 | warn!("RoomMessage type is not handled. Not implemented yet."); 746 | err_count += 1; 747 | } 748 | } 749 | } 750 | AnyMessageLikeEvent::RoomRedaction(messagelikeevent) => { 751 | warn!("Event of type RoomRedaction received. Not implemented yet. value: {:?}", messagelikeevent); 752 | err_count += 1; 753 | } 754 | // and many more 755 | _ => { 756 | warn!("MessageLike type is not handle. Not implemented yet."); 757 | err_count += 1; 758 | } 759 | } 760 | } 761 | _ => debug!("State event, not interested in that."), 762 | } 763 | } 764 | } 765 | if err_count != 0 { 766 | Err(Error::NotImplementedYet) 767 | } else { 768 | Ok(()) 769 | } 770 | } 771 | 772 | /// Listen to some specified rooms once, then go on. 773 | /// Listens to the room(s) provided as argument, prints any pending relevant messages, 774 | /// and then continues by returning. 775 | pub(crate) async fn listen_all( 776 | client: &Client, 777 | roomnames: &Vec, // roomId 778 | listen_self: bool, // listen to my own messages? 779 | whoami: OwnedUserId, 780 | output: Output, 781 | ) -> Result<(), Error> { 782 | if roomnames.is_empty() { 783 | return Err(Error::MissingRoom); 784 | } 785 | info!( 786 | "mclient::listen_all(): listen_self {}, roomnames {:?}", 787 | listen_self, roomnames 788 | ); 789 | 790 | let context = EvHandlerContext { 791 | whoami, 792 | listen_self, 793 | output, 794 | }; 795 | 796 | client.add_event_handler_context(context.clone()); 797 | 798 | // Todo: print events nicely and filter by --listen-self 799 | client.add_event_handler(|ev: SyncRoomMessageEvent, room: Room, client: Client, context: Ctx| async move { 800 | tokio::spawn(handle_syncroommessageevent(ev, room, client, context)); 801 | }); 802 | 803 | // this seems idential to SyncRoomMessageEvent and hence a duplicate 804 | // client.add_event_handler( 805 | // |ev: OriginalSyncRoomMessageEvent, _client: Client| async move { 806 | // println!( 807 | // "Received a message for OriginalSyncRoomMessageEvent {:?}", 808 | // ev 809 | // ); 810 | // }, 811 | // ); 812 | 813 | client.add_event_handler( 814 | |ev: RedactedSyncRoomMessageEvent, 815 | room: Room, 816 | client: Client, 817 | context: Ctx| async move { 818 | tokio::spawn(handle_redactedsyncroommessageevent( 819 | ev, room, client, context, 820 | )); 821 | }, 822 | ); 823 | 824 | client.add_event_handler(|ev: SyncRoomRedactionEvent, 825 | room: Room, client: Client, context: Ctx| async move { 826 | tokio::spawn(handle_syncroomredactedevent(ev, room, client, context)); 827 | }); 828 | 829 | // go into event loop to sync and to execute verify protocol 830 | info!("Ready and waiting for messages ..."); 831 | 832 | // search for filter: https://docs.rs/matrix-sdk/0.6.2/matrix_sdk/struct.Client.html#method.builder 833 | // https://docs.rs/ruma/latest/ruma/api/client/filter/struct.FilterDefinition.html 834 | // https://docs.rs/ruma/latest/ruma/api/client/filter/struct.RoomFilter.html ==> timeline, rooms 835 | // https://docs.rs/ruma/latest/ruma/api/client/filter/struct.RoomEventFilter.html ==> limit : max number of events to return, types :: event types to include; rooms: rooms to include 836 | 837 | let mut roomids: Vec = Vec::new(); 838 | for roomname in roomnames { 839 | roomids.push(RoomId::parse(roomname.clone()).unwrap()); 840 | } 841 | let ownedroomidvecoption: Option> = Some(roomids); 842 | // Filter by rooms. This works. 843 | let mut filter = FilterDefinition::default(); 844 | let mut roomfilter = RoomFilter::empty(); 845 | roomfilter.rooms = ownedroomidvecoption; 846 | filter.room = roomfilter; 847 | 848 | // // Let's enable member lazy loading. This filter is enabled by default. 849 | // filter.room.state.lazy_load_options = LazyLoadOptions::Enabled { 850 | // include_redundant_members: false, 851 | // }; 852 | 853 | // // Todo: add future option like --user to filter messages by user id 854 | // // Filter by user; this works but NOT for itself. 855 | // // It does not listen to its own messages, additing itself as sender does not help. 856 | // // The msgs sent by itself are not in this event stream and hence cannot be filtered. 857 | // let mut roomstate = RoomEventFilter::empty(); 858 | // let userid1: OwnedUserId = UserId::parse("@john:some.homeserver.org").unwrap(); 859 | // let userid2: OwnedUserId = UserId::parse("@jane:some.homeserver.org").unwrap(); 860 | // let useridslice = &[userid1, userid2][0..2]; 861 | // roomstate.senders = Some(useridslice); 862 | // filter.room.timeline = roomstate; 863 | 864 | // // Filter by limit. This works. 865 | // // This gets the last N not yet read messages. If all messages had been read, it gets 0 messages. 866 | // let mut roomtimeline = RoomEventFilter::empty(); 867 | // roomtimeline.limit = UInt::new(number); 868 | // filter.room.timeline = roomtimeline; 869 | 870 | // To be more efficient, more performant, usually one stores the filter on the 871 | // server under a given name. This way only the name but not the filter needs to 872 | // be transferred. But we would have an unlimited amount of filters. How to name them 873 | // uniquely? To avoid the naming problem, we do not create names but send the filter 874 | // itself. 875 | // The filter would be created like so: 876 | // // some unique naming scheme, dumb example prepending the room id with "room-", 877 | // // some sort of hash would be better. 878 | // let filter_name = format!("room-{}", room); 879 | // let filter_id = client 880 | // .get_or_upload_filter(&filter_name, filter) 881 | // .await 882 | // .unwrap(); 883 | // // now we can use the filter_name in the sync() call 884 | // let sync_settings = SyncSettings::new().filter(Filter::FilterId(&filter_id)); 885 | 886 | // let sync_settings = SyncSettings::default() 887 | // .token(client.sync_token().await.unwrap()) 888 | // .filter(Filter::FilterId(&filter_id)); 889 | 890 | let mut err_count = 0u32; 891 | let filterclone = filter.clone(); 892 | let sync_settings = SyncSettings::default().filter(Filter::FilterDefinition(filterclone)); 893 | 894 | match client.sync_once(sync_settings).await { 895 | Ok(response) => debug!("listen_all successful {:?}", response), 896 | Err(ref e) => { 897 | err_count += 1; 898 | error!("listen_all returned error {:?}", e); 899 | } 900 | } 901 | if err_count != 0 { 902 | Err(Error::ListenFailed) 903 | } else { 904 | Ok(()) 905 | } 906 | } 907 | -------------------------------------------------------------------------------- /tests/test-devices.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -t 1 ]; then 4 | # echo terminal 5 | green="\e[1;37;1;42m" 6 | off="\e[0m" 7 | red="\e[1;37;1;41m" 8 | else 9 | # echo "not a terminal", e.g. being piped out 10 | green="" 11 | off="" 12 | red="" 13 | fi 14 | 15 | # just in case PATH is not set correctly 16 | PATH="./target/debug/:./target/release/:../target/debug/:../target/release/:.:./matrix_commander-rs:../matrix_commander-rs:$PATH" 17 | 18 | # One may set similar values in the terminal before calling the script. 19 | # export MCRS_OPTIONS="-d --room \!...some.room.id:matrix.example.org " 20 | 21 | # getting some optional arguments 22 | if [ "$MCRS_OPTIONS" != "" ]; then 23 | echo "Exellent. Variable MCRS_OPTIONS already set. " \ 24 | "Using \"$MCRS_OPTIONS\" as additional options for testing." 25 | else 26 | echo "Optionally, set variable \"MCRS_OPTIONS\" for further options." 27 | fi 28 | 29 | echo "rustc version is: $(rustc -vV | xargs)" 30 | echo "rustup version is: $(rustup --version)" 31 | echo "cargo version is: $(cargo --version)" 32 | echo "GITHUB_WORKFLOW = $GITHUB_WORKFLOW" 33 | echo "GITHUB_REPOSITORY = $GITHUB_REPOSITORY" 34 | echo "MCRS_OPTIONS = $MCRS_OPTIONS" 35 | 36 | if [[ "$GITHUB_WORKFLOW" != "" ]]; then # if in Github Action Workflow 37 | echo "I am in Github Action Workflow $GITHUB_WORKFLOW." 38 | fi 39 | 40 | failures=0 41 | 42 | function test1() { 43 | echo "=== Test 1: get devices in text format ===" 44 | matrix-commander-rs --devices $MCRS_OPTIONS 45 | res=$? 46 | if [ "$res" == "0" ]; then 47 | echo "SUCCESS" 48 | else 49 | echo >&2 "FAILURE" 50 | let failures++ 51 | fi 52 | } 53 | 54 | function test2() { 55 | echo "=== Test 2: get devices in JSON format ===" 56 | fofile="/tmp/matrix-comander-rs-test-devices.json" 57 | matrix-commander-rs --devices --output json $MCRS_OPTIONS >$fofile 58 | res=$? 59 | if [ "$res" == "0" ]; then 60 | if cat $fofile | jq -e . >/dev/null 2>&1; then 61 | echo "Parsed JSON successfully and got something other than false/null" 62 | echo "SUCCESS" 63 | else 64 | echo "Failed to parse JSON, or got false/null" 65 | echo >&2 "FAILURE" 66 | let failures++ 67 | fi 68 | else 69 | echo >&2 "FAILURE" 70 | let failures++ 71 | fi 72 | rm $fofile 73 | } 74 | 75 | test1 76 | test2 77 | 78 | failtext="failure" 79 | if [ "$failures" != "1" ]; then 80 | failtext+="s" ## append an "s" to the end 81 | fi 82 | if [ "$failures" == "0" ]; then 83 | echo -e "${green}OK: Finished test series with $failures failures.${off}" 84 | else 85 | echo -e "${red}ERROR: Finished test series with $failures $failtext.${off}" 86 | fi 87 | 88 | exit $failures 89 | -------------------------------------------------------------------------------- /tests/test-get-display-name.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -t 1 ]; then 4 | # echo terminal 5 | green="\e[1;37;1;42m" 6 | off="\e[0m" 7 | red="\e[1;37;1;41m" 8 | else 9 | # echo "not a terminal", e.g. being piped out 10 | green="" 11 | off="" 12 | red="" 13 | fi 14 | 15 | # just in case PATH is not set correctly 16 | PATH="./target/debug/:./target/release/:../target/debug/:../target/release/:.:./matrix_commander-rs:../matrix_commander-rs:$PATH" 17 | 18 | # One may set similar values in the terminal before calling the script. 19 | # export MCRS_OPTIONS="-d --room \!...some.room.id:matrix.example.org " 20 | 21 | # getting some optional arguments 22 | if [ "$MCRS_OPTIONS" != "" ]; then 23 | echo "Exellent. Variable MCRS_OPTIONS already set. " \ 24 | "Using \"$MCRS_OPTIONS\" as additional options for testing." 25 | else 26 | echo "Optionally, set variable \"MCRS_OPTIONS\" for further options." 27 | fi 28 | 29 | echo "rustc version is: $(rustc -vV | xargs)" 30 | echo "rustup version is: $(rustup --version)" 31 | echo "cargo version is: $(cargo --version)" 32 | echo "GITHUB_WORKFLOW = $GITHUB_WORKFLOW" 33 | echo "GITHUB_REPOSITORY = $GITHUB_REPOSITORY" 34 | echo "MCRS_OPTIONS = $MCRS_OPTIONS" 35 | 36 | if [[ "$GITHUB_WORKFLOW" != "" ]]; then # if in Github Action Workflow 37 | echo "I am in Github Action Workflow $GITHUB_WORKFLOW." 38 | fi 39 | 40 | failures=0 41 | 42 | function test1() { 43 | echo "=== Test 1: get display-name in text format ===" 44 | matrix-commander-rs --get-display-name $MCRS_OPTIONS 45 | res=$? 46 | if [ "$res" == "0" ]; then 47 | echo "SUCCESS" 48 | else 49 | echo >&2 "FAILURE" 50 | let failures++ 51 | fi 52 | } 53 | 54 | function test2() { 55 | echo "=== Test 2: get display-name in JSON format ===" 56 | fofile="/tmp/matrix-comander-rs-test-get-display-name.json" 57 | matrix-commander-rs --get-display-name --output json $MCRS_OPTIONS >$fofile 58 | res=$? 59 | if [ "$res" == "0" ]; then 60 | if cat $fofile | jq -e . >/dev/null 2>&1; then 61 | echo "Parsed JSON successfully and got something other than false/null" 62 | echo "SUCCESS" 63 | else 64 | echo "Failed to parse JSON, or got false/null" 65 | echo >&2 "FAILURE" 66 | let failures++ 67 | fi 68 | else 69 | echo >&2 "FAILURE" 70 | let failures++ 71 | fi 72 | rm $fofile 73 | } 74 | 75 | test1 76 | test2 77 | 78 | failtext="failure" 79 | if [ "$failures" != "1" ]; then 80 | failtext+="s" ## append an "s" to the end 81 | fi 82 | if [ "$failures" == "0" ]; then 83 | echo -e "${green}OK: Finished test series with $failures failures.${off}" 84 | else 85 | echo -e "${red}ERROR: Finished test series with $failures $failtext.${off}" 86 | fi 87 | 88 | exit $failures 89 | -------------------------------------------------------------------------------- /tests/test-get-profile.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -t 1 ]; then 4 | # echo terminal 5 | green="\e[1;37;1;42m" 6 | off="\e[0m" 7 | red="\e[1;37;1;41m" 8 | else 9 | # echo "not a terminal", e.g. being piped out 10 | green="" 11 | off="" 12 | red="" 13 | fi 14 | 15 | # just in case PATH is not set correctly 16 | PATH="./target/debug/:./target/release/:../target/debug/:../target/release/:.:./matrix_commander-rs:../matrix_commander-rs:$PATH" 17 | 18 | # One may set similar values in the terminal before calling the script. 19 | # export MCRS_OPTIONS="-d --room \!...some.room.id:matrix.example.org " 20 | 21 | # getting some optional arguments 22 | if [ "$MCRS_OPTIONS" != "" ]; then 23 | echo "Exellent. Variable MCRS_OPTIONS already set. " \ 24 | "Using \"$MCRS_OPTIONS\" as additional options for testing." 25 | else 26 | echo "Optionally, set variable \"MCRS_OPTIONS\" for further options." 27 | fi 28 | 29 | echo "rustc version is: $(rustc -vV | xargs)" 30 | echo "rustup version is: $(rustup --version)" 31 | echo "cargo version is: $(cargo --version)" 32 | echo "GITHUB_WORKFLOW = $GITHUB_WORKFLOW" 33 | echo "GITHUB_REPOSITORY = $GITHUB_REPOSITORY" 34 | echo "MCRS_OPTIONS = $MCRS_OPTIONS" 35 | 36 | if [[ "$GITHUB_WORKFLOW" != "" ]]; then # if in Github Action Workflow 37 | echo "I am in Github Action Workflow $GITHUB_WORKFLOW." 38 | fi 39 | 40 | failures=0 41 | 42 | function test1() { 43 | echo "=== Test 1: get profile in text format ===" 44 | matrix-commander-rs --get-profile $MCRS_OPTIONS 45 | res=$? 46 | if [ "$res" == "0" ]; then 47 | echo "SUCCESS" 48 | else 49 | echo >&2 "FAILURE" 50 | let failures++ 51 | fi 52 | } 53 | 54 | function test2() { 55 | echo "=== Test 2: get profile in JSON format ===" 56 | fofile="/tmp/matrix-comander-rs-test-get-profile.json" 57 | matrix-commander-rs --get-profile --output json $MCRS_OPTIONS >$fofile 58 | res=$? 59 | if [ "$res" == "0" ]; then 60 | if cat $fofile | jq -e . >/dev/null 2>&1; then 61 | echo "Parsed JSON successfully and got something other than false/null" 62 | echo "SUCCESS" 63 | else 64 | echo "Failed to parse JSON, or got false/null" 65 | echo >&2 "FAILURE" 66 | let failures++ 67 | fi 68 | else 69 | echo >&2 "FAILURE" 70 | let failures++ 71 | fi 72 | rm $fofile 73 | } 74 | 75 | test1 76 | test2 77 | 78 | failtext="failure" 79 | if [ "$failures" != "1" ]; then 80 | failtext+="s" ## append an "s" to the end 81 | fi 82 | if [ "$failures" == "0" ]; then 83 | echo -e "${green}OK: Finished test series with $failures failures.${off}" 84 | else 85 | echo -e "${red}ERROR: Finished test series with $failures $failtext.${off}" 86 | fi 87 | 88 | exit $failures 89 | -------------------------------------------------------------------------------- /tests/test-rooms.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -t 1 ]; then 4 | # echo terminal 5 | green="\e[1;37;1;42m" 6 | off="\e[0m" 7 | red="\e[1;37;1;41m" 8 | else 9 | # echo "not a terminal", e.g. being piped out 10 | green="" 11 | off="" 12 | red="" 13 | fi 14 | 15 | # just in case PATH is not set correctly 16 | PATH="./target/debug/:./target/release/:../target/debug/:../target/release/:.:./matrix_commander-rs:../matrix_commander-rs:$PATH" 17 | 18 | # One may set similar values in the terminal before calling the script. 19 | # export MCRS_OPTIONS="-d --room \!...some.room.id:matrix.example.org " 20 | 21 | # getting some optional arguments 22 | if [ "$MCRS_OPTIONS" != "" ]; then 23 | echo "Exellent. Variable MCRS_OPTIONS already set. " \ 24 | "Using \"$MCRS_OPTIONS\" as additional options for testing." 25 | else 26 | echo "Optionally, set variable \"MCRS_OPTIONS\" for further options." 27 | fi 28 | 29 | echo "rustc version is: $(rustc -vV | xargs)" 30 | echo "rustup version is: $(rustup --version)" 31 | echo "cargo version is: $(cargo --version)" 32 | echo "GITHUB_WORKFLOW = $GITHUB_WORKFLOW" 33 | echo "GITHUB_REPOSITORY = $GITHUB_REPOSITORY" 34 | echo "MCRS_OPTIONS = $MCRS_OPTIONS" 35 | 36 | if [[ "$GITHUB_WORKFLOW" != "" ]]; then # if in Github Action Workflow 37 | echo "I am in Github Action Workflow $GITHUB_WORKFLOW." 38 | fi 39 | 40 | failures=0 41 | 42 | function test1() { 43 | echo "=== Test 1: get rooms in text format ===" 44 | matrix-commander-rs --rooms $MCRS_OPTIONS 45 | res=$? 46 | if [ "$res" == "0" ]; then 47 | echo "SUCCESS" 48 | else 49 | echo >&2 "FAILURE" 50 | let failures++ 51 | fi 52 | } 53 | 54 | function test2() { 55 | echo "=== Test 2: get rooms in JSON format ===" 56 | fofile="/tmp/matrix-comander-rs-test-rooms.json" 57 | matrix-commander-rs --rooms --output json $MCRS_OPTIONS >$fofile 58 | res=$? 59 | if [ "$res" == "0" ]; then 60 | if cat $fofile | jq -e . >/dev/null 2>&1; then 61 | echo "Parsed JSON successfully and got something other than false/null" 62 | echo "SUCCESS" 63 | else 64 | echo "Failed to parse JSON, or got false/null" 65 | echo >&2 "FAILURE" 66 | let failures++ 67 | fi 68 | else 69 | echo >&2 "FAILURE" 70 | let failures++ 71 | fi 72 | rm $fofile 73 | } 74 | 75 | test1 76 | test2 77 | 78 | failtext="failure" 79 | if [ "$failures" != "1" ]; then 80 | failtext+="s" ## append an "s" to the end 81 | fi 82 | if [ "$failures" == "0" ]; then 83 | echo -e "${green}OK: Finished test series with $failures failures.${off}" 84 | else 85 | echo -e "${red}ERROR: Finished test series with $failures $failtext.${off}" 86 | fi 87 | 88 | exit $failures 89 | -------------------------------------------------------------------------------- /tests/test-send.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -t 1 ]; then 4 | # echo terminal 5 | green="\e[1;37;1;42m" 6 | off="\e[0m" 7 | red="\e[1;37;1;41m" 8 | else 9 | # echo "not a terminal", e.g. being piped out 10 | green="" 11 | off="" 12 | red="" 13 | fi 14 | 15 | # just in case PATH is not set correctly 16 | PATH="./target/debug/:./target/release/:../target/debug/:../target/release/:.:./matrix_commander-rs:../matrix_commander-rs:$PATH" 17 | 18 | # One may set similar values in the terminal before calling the script. 19 | # export MCRS_OPTIONS="-d --room \!...some.room.id:matrix.example.org " 20 | 21 | # getting some optional arguments 22 | if [ "$MCRS_OPTIONS" != "" ]; then 23 | echo "Exellent. Variable MCRS_OPTIONS already set. " \ 24 | "Using \"$MCRS_OPTIONS\" as additional options for testing." 25 | else 26 | echo "If desired, set variable \"MCRS_OPTIONS\" for further options." 27 | fi 28 | 29 | echo "rustc version is: $(rustc -vV | xargs)" 30 | echo "rustup version is: $(rustup --version)" 31 | echo "cargo version is: $(cargo --version)" 32 | echo "GITHUB_WORKFLOW = $GITHUB_WORKFLOW" 33 | echo "GITHUB_REPOSITORY = $GITHUB_REPOSITORY" 34 | echo "MCRS_OPTIONS = $MCRS_OPTIONS" 35 | 36 | if [[ "$GITHUB_WORKFLOW" != "" ]]; then # if in Github Action Workflow 37 | echo "I am in Github Action Workflow $GITHUB_WORKFLOW." 38 | fi 39 | 40 | failures=0 41 | 42 | function test1() { 43 | echo "=== Test 1: send a message ===" 44 | matrix-commander-rs -m foo $MCRS_OPTIONS 45 | res=$? 46 | if [ "$res" == "0" ]; then 47 | echo "SUCCESS" 48 | else 49 | echo >&2 "FAILURE" 50 | let failures++ 51 | fi 52 | } 53 | 54 | function test2() { 55 | echo "=== Test 2: send two messages ===" 56 | matrix-commander-rs -m "foo" "bar" $MCRS_OPTIONS 57 | res=$? 58 | if [ "$res" == "0" ]; then 59 | echo "SUCCESS" 60 | else 61 | echo >&2 "FAILURE" 62 | let failures++ 63 | fi 64 | } 65 | function test3() { 66 | echo "=== Test 3: send two messages ===" 67 | res=$(matrix-commander-rs -m "foo" "bar" -d $MCRS_OPTIONS 2>&1 >/dev/null | grep "message send successful" | wc -l) 68 | if [ "$res" == "2" ]; then 69 | echo "SUCCESS" 70 | else 71 | echo >&2 "FAILURE" 72 | let failures++ 73 | fi 74 | } 75 | 76 | test1 77 | test2 78 | test3 79 | 80 | failtext="failure" 81 | if [ "$failures" != "1" ]; then 82 | failtext+="s" ## append an "s" to the end 83 | fi 84 | if [ "$failures" == "0" ]; then 85 | echo -e "${green}OK: Finished test series with $failures failures.${off}" 86 | else 87 | echo -e "${red}ERROR: Finished test series with $failures $failtext.${off}" 88 | fi 89 | 90 | exit $failures 91 | -------------------------------------------------------------------------------- /tests/test-version.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -t 1 ]; then 4 | # echo terminal 5 | green="\e[1;37;1;42m" 6 | off="\e[0m" 7 | red="\e[1;37;1;41m" 8 | else 9 | # echo "not a terminal", e.g. being piped out 10 | green="" 11 | off="" 12 | red="" 13 | fi 14 | 15 | # just in case PATH is not set correctly 16 | PATH="./target/debug/:./target/release/:../target/debug/:../target/release/:.:./matrix_commander-rs:../matrix_commander-rs:$PATH" 17 | 18 | # One may set similar values in the terminal before calling the script. 19 | # export MCRS_OPTIONS="-d --room \!...some.room.id:matrix.example.org " 20 | 21 | # getting some optional arguments 22 | if [ "$MCRS_OPTIONS" != "" ]; then 23 | echo "Exellent. Variable MCRS_OPTIONS already set. " \ 24 | "Using \"$MCRS_OPTIONS\" as additional options for testing." 25 | else 26 | echo "Optionally, set variable \"MCRS_OPTIONS\" for further options." 27 | fi 28 | 29 | echo "rustc version is: $(rustc -vV | xargs)" 30 | echo "rustup version is: $(rustup --version)" 31 | echo "cargo version is: $(cargo --version)" 32 | echo "GITHUB_WORKFLOW = $GITHUB_WORKFLOW" 33 | echo "GITHUB_REPOSITORY = $GITHUB_REPOSITORY" 34 | echo "MCRS_OPTIONS = $MCRS_OPTIONS" 35 | 36 | if [[ "$GITHUB_WORKFLOW" != "" ]]; then # if in Github Action Workflow 37 | echo "I am in Github Action Workflow $GITHUB_WORKFLOW." 38 | fi 39 | 40 | failures=0 41 | 42 | function test1() { 43 | echo "=== Test 1: get version in text format ===" 44 | matrix-commander-rs --version $MCRS_OPTIONS 45 | res=$? 46 | if [ "$res" == "0" ]; then 47 | echo "SUCCESS" 48 | else 49 | echo >&2 "FAILURE" echo "FAILURE" 50 | let failures++ 51 | fi 52 | } 53 | 54 | function test2() { 55 | echo "=== Test 2: get version in JSON format ===" 56 | fofile="/tmp/matrix-comander-rs-test-version.json" 57 | matrix-commander-rs --version --output json $MCRS_OPTIONS >$fofile 58 | res=$? 59 | if [ "$res" == "0" ]; then 60 | if cat $fofile | jq -e . >/dev/null 2>&1; then 61 | echo "Parsed JSON successfully and got something other than false/null" 62 | echo "SUCCESS" 63 | else 64 | echo "Failed to parse JSON, or got false/null" 65 | echo >&2 "FAILURE" echo "FAILURE" 66 | let failures++ 67 | fi 68 | else 69 | echo >&2 "FAILURE" echo "FAILURE" 70 | let failures++ 71 | fi 72 | rm $fofile 73 | } 74 | 75 | test1 76 | test2 77 | 78 | failtext="failure" 79 | if [ "$failures" != "1" ]; then 80 | failtext+="s" ## append an "s" to the end 81 | fi 82 | if [ "$failures" == "0" ]; then 83 | echo -e "${green}OK: Finished test series with $failures failures.${off}" 84 | else 85 | echo -e "${red}ERROR: Finished test series with $failures $failtext.${off}" 86 | fi 87 | 88 | exit $failures 89 | -------------------------------------------------------------------------------- /tests/test.l.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/8go/matrix-commander-rs/a4acbf7f1abcaf86a0341e98b555c38163a1b830/tests/test.l.jpg -------------------------------------------------------------------------------- /tests/test.s.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/8go/matrix-commander-rs/a4acbf7f1abcaf86a0341e98b555c38163a1b830/tests/test.s.jpg -------------------------------------------------------------------------------- /tests/test.s.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/8go/matrix-commander-rs/a4acbf7f1abcaf86a0341e98b555c38163a1b830/tests/test.s.png -------------------------------------------------------------------------------- /tests/test.s.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 16 | 35 | 37 | 41 | 48 | 55 | 56 | 57 | --------------------------------------------------------------------------------