commit 6bac95dce6cf11702af488650085afa93c818018 Author: Mystara Date: Mon Jul 7 23:27:18 2025 -0500 Inital bot files diff --git a/.env.template b/.env.template new file mode 100755 index 0000000..f567e67 --- /dev/null +++ b/.env.template @@ -0,0 +1,9 @@ +DISCORD_BOT_TOKEN= +DISCORD_DAYS_TO_DELETE_REACTION=999 +DISCORD_LOG_CHANNEL_ID= +DISCORD_WELCOME_CHANNEL_ID= + +#BOT_REDIS_URL="redis://localhost:3278" + +RUST_LOG="refraction=info,warn" +RUST_BACKTRACE=1 diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..1d67506 --- /dev/null +++ b/.envrc @@ -0,0 +1,5 @@ +if has nix_direnv_version; then + use flake +fi + +dotenv_if_exists diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..efc6b6d --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,79 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +jobs: + build: + name: Build (${{ matrix.os }}) + + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + use-nix: true + - os: windows-latest + use-nix: false + + runs-on: ${{ matrix.os }} + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install Rust + if: ${{ !matrix.use-nix }} + uses: actions-rust-lang/setup-rust-toolchain@v1 + + - name: Install Nix + if: ${{ matrix.use-nix }} + uses: DeterminateSystems/nix-installer-action@v17 + + - name: Setup Nix cache + if: ${{ matrix.use-nix }} + uses: DeterminateSystems/magic-nix-cache-action@v9 + + - name: Build + if: ${{ !matrix.use-nix }} + run: cargo build --locked + + - name: Build + if: ${{ matrix.use-nix }} + run: nix build --print-build-logs .#refraction-debug + + flake: + name: Flake checks + + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install Nix + uses: DeterminateSystems/nix-installer-action@v17 + + - name: Setup Nix cache + uses: DeterminateSystems/magic-nix-cache-action@v9 + + - name: Run checks + run: | + nix flake check --print-build-logs --show-trace + + # Make sure all above jobs finished successfully + release-gate: + name: CI Release gate + needs: [build, flake] + + if: ${{ always() }} + + runs-on: ubuntu-latest + + steps: + - name: Exit with error + if: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }} + run: exit 1 diff --git a/.github/workflows/clippy.yml b/.github/workflows/clippy.yml new file mode 100644 index 0000000..87ac141 --- /dev/null +++ b/.github/workflows/clippy.yml @@ -0,0 +1,47 @@ +name: Clippy + +on: + push: + branches: [main] + paths: + - 'Cargo.toml' + - 'Cargo.lock' + - '**.rs' + pull_request: + paths: + - 'Cargo.toml' + - 'Cargo.lock' + - '**.rs' + workflow_dispatch: + +jobs: + clippy: + name: Run scan + + runs-on: ubuntu-latest + + permissions: + security-events: write + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install Nix + uses: DeterminateSystems/nix-installer-action@v17 + + - name: Setup Nix cache + uses: DeterminateSystems/magic-nix-cache-action@v9 + + - name: Generate sarif report + id: clippy-run + run: | + nix build --print-build-logs .#clippy-report + [ -L result ] || exit 1 + echo "sarif-file=$(readlink -f result)" >> "$GITHUB_OUTPUT" + + - name: Upload results + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: ${{ steps.clippy-run.outputs.sarif-file }} + wait-for-processing: true diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000..888829c --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,115 @@ +name: Docker + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +jobs: + build: + name: Build image + + strategy: + fail-fast: false + matrix: + arch: [amd64, arm64] + + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install Nix + uses: DeterminateSystems/nix-installer-action@v17 + + - name: Setup Nix cache + uses: DeterminateSystems/magic-nix-cache-action@v9 + + - name: Build Docker image + id: build + env: + ARCH: ${{ matrix.arch }} + run: | + nix build --print-build-logs .#container-"$ARCH" + [ ! -L result ] && exit 1 + echo "path=$(readlink -f result)" >> "$GITHUB_OUTPUT" + + - name: Upload image + uses: actions/upload-artifact@v4 + with: + name: container-${{ matrix.arch }} + path: ${{ steps.build.outputs.path }} + if-no-files-found: error + retention-days: 3 + + # Make sure all above jobs finished successfully + release-gate: + name: Docker Release gate + needs: [build] + + if: ${{ always() }} + + runs-on: ubuntu-latest + + steps: + - name: Exit with error + if: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }} + run: exit 1 + + push: + name: Push image + needs: build + + if: ${{ github.event_name == 'push' }} + + runs-on: ubuntu-latest + + permissions: + packages: write + + env: + REGISTRY: ghcr.io + USERNAME: ${{ github.actor }} + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Determine image name + run: | + echo "IMAGE_NAME=${REPOSITORY,,}" >> "$GITHUB_ENV" + env: + REPOSITORY: ${{ github.repository }} + + - name: Download images + uses: actions/download-artifact@v4 + with: + path: images + + - name: Login to registry + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ env.USERNAME }} + password: ${{ github.token }} + + - name: Push to registry + env: + TAG: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest + run: | + set -eu + + architectures=("amd64" "arm64") + for arch in "${architectures[@]}"; do + docker load < images/container-"$arch"/*.tar.gz + docker tag refraction:latest-"$arch" "$TAG"-"$arch" + docker push "$TAG"-"$arch" + done + + docker manifest create "$TAG" \ + --amend "$TAG"-amd64 \ + --amend "$TAG"-arm64 + + docker manifest push "$TAG" diff --git a/.github/workflows/update-flake.yml b/.github/workflows/update-flake.yml new file mode 100644 index 0000000..25ff02a --- /dev/null +++ b/.github/workflows/update-flake.yml @@ -0,0 +1,36 @@ +name: Update flake.lock + +on: + schedule: + # run every saturday + - cron: '0 0 * * 6' + workflow_dispatch: + +jobs: + update: + name: Run update + runs-on: ubuntu-latest + + permissions: + contents: write + pull-requests: write + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install Nix + uses: DeterminateSystems/nix-installer-action@v17 + + - name: Update flake.lock + id: update + uses: DeterminateSystems/update-flake-lock@v25 + with: + pr-title: 'nix: update flake.lock' + + - name: Enable Pull Request Automerge + uses: peter-evans/enable-pull-request-automerge@v3 + with: + pull-request-number: ${{ steps.update.outputs.pull-request-number }} + merge-method: rebase + github-token: ${{ secrets.AUTOMATA_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b0e79ce --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + + +# direnv secrets +.env +.env.* +!.env.template + +# Nix +.direnv/ +.pre-commit-config.yaml +result* +repl-result-out* + +.DS_Store +*.rdb + +# JetBrains +.idea/ diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..7d269a8 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,7 @@ +{ + "singleQuote": true, + "trailingComma": "es5", + "useTabs": false, + "tabWidth": 2, + "semi": true +} diff --git a/.rustfmt.toml b/.rustfmt.toml new file mode 100644 index 0000000..218e203 --- /dev/null +++ b/.rustfmt.toml @@ -0,0 +1 @@ +hard_tabs = true diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..a8a0e1b --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,50 @@ +[package] +name = "refraction" +version = "2.0.0" +edition = "2021" +repository = "https://github.com/PrismLauncher/refraction" +license = "GPL-3.0-or-later" +readme = "README.md" +build = "build.rs" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[build-dependencies] +gray_matter = "0.2.6" +poise = "0.6.1" +serde = "1.0.200" +serde_json = "1.0.116" + +[dependencies] +color-eyre = "0.6.3" +dotenvy = "0.15.7" +enum_dispatch = "0.3.13" +env_logger = "0.11.3" +eyre = "0.6.12" +log = "0.4.21" +poise = "0.6.1" +octocrab = "0.44.0" +redis = { version = "0.32.0", features = ["tokio-comp", "tokio-rustls-comp"] } +regex = "1.10.4" +reqwest = { version = "0.12.4", default-features = false, features = [ + "rustls-tls", + "json", +] } +serde = "1.0.200" +serde_json = "1.0.116" +tokio = { version = "1.37.0", features = [ + "macros", + "rt-multi-thread", + "signal", +] } +rustls = "0.23.13" + +[lints.rust] +unsafe_code = "forbid" + +[lints.clippy] +complexity = "warn" +correctness = "deny" +pedantic = "warn" +perf = "warn" +style = "warn" +suspicious = "deny" diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..0ca6af8 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,637 @@ +# GNU GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright (C) 2007 [Free Software Foundation, Inc.](http://fsf.org/) + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +## Preamble + +The GNU General Public License is a free, copyleft license for software and +other kinds of works. + +The licenses for most software and other practical works are designed to take +away your freedom to share and change the works. By contrast, the GNU General +Public License is intended to guarantee your freedom to share and change all +versions of a program--to make sure it remains free software for all its users. +We, the Free Software Foundation, use the GNU General Public License for most +of our software; it applies also to any other work released this way by its +authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom to +distribute copies of free software (and charge for them if you wish), that you +receive source code or can get it if you want it, that you can change the +software or use pieces of it in new free programs, and that you know you can do +these things. + +To protect your rights, we need to prevent others from denying you these rights +or asking you to surrender the rights. Therefore, you have certain +responsibilities if you distribute copies of the software, or if you modify it: +responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for +a fee, you must pass on to the recipients the same freedoms that you received. +You must make sure that they, too, receive or can get the source code. And you +must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: + +1. assert copyright on the software, and +2. offer you this License giving you legal permission to copy, distribute + and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that +there is no warranty for this free software. For both users' and authors' sake, +the GPL requires that modified versions be marked as changed, so that their +problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified +versions of the software inside them, although the manufacturer can do so. This +is fundamentally incompatible with the aim of protecting users' freedom to +change the software. The systematic pattern of such abuse occurs in the area of +products for individuals to use, which is precisely where it is most +unacceptable. Therefore, we have designed this version of the GPL to prohibit +the practice for those products. If such problems arise substantially in other +domains, we stand ready to extend this provision to those domains in future +versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States +should not allow patents to restrict development and use of software on +general-purpose computers, but in those that do, we wish to avoid the special +danger that patents applied to a free program could make it effectively +proprietary. To prevent this, the GPL assures that patents cannot be used to +render the program non-free. + +The precise terms and conditions for copying, distribution and modification +follow. + +## TERMS AND CONDITIONS + +### 0. Definitions. + +_This License_ refers to version 3 of the GNU General Public License. + +_Copyright_ also means copyright-like laws that apply to other kinds of works, +such as semiconductor masks. + +_The Program_ refers to any copyrightable work licensed under this License. +Each licensee is addressed as _you_. _Licensees_ and _recipients_ may be +individuals or organizations. + +To _modify_ a work means to copy from or adapt all or part of the work in a +fashion requiring copyright permission, other than the making of an exact copy. +The resulting work is called a _modified version_ of the earlier work or a work +_based on_ the earlier work. + +A _covered work_ means either the unmodified Program or a work based on the +Program. + +To _propagate_ a work means to do anything with it that, without permission, +would make you directly or secondarily liable for infringement under applicable +copyright law, except executing it on a computer or modifying a private copy. +Propagation includes copying, distribution (with or without modification), +making available to the public, and in some countries other activities as well. + +To _convey_ a work means any kind of propagation that enables other parties to +make or receive copies. Mere interaction with a user through a computer +network, with no transfer of a copy, is not conveying. + +An interactive user interface displays _Appropriate Legal Notices_ to the +extent that it includes a convenient and prominently visible feature that + +1. displays an appropriate copyright notice, and +2. tells the user that there is no warranty for the work (except to the + extent that warranties are provided), that licensees may convey the work + under this License, and how to view a copy of this License. + +If the interface presents a list of user commands or options, such as a menu, a +prominent item in the list meets this criterion. + +### 1. Source Code. + +The _source code_ for a work means the preferred form of the work for making +modifications to it. _Object code_ means any non-source form of a work. + +A _Standard Interface_ means an interface that either is an official standard +defined by a recognized standards body, or, in the case of interfaces specified +for a particular programming language, one that is widely used among developers +working in that language. + +The _System Libraries_ of an executable work include anything, other than the +work as a whole, that (a) is included in the normal form of packaging a Major +Component, but which is not part of that Major Component, and (b) serves only +to enable use of the work with that Major Component, or to implement a Standard +Interface for which an implementation is available to the public in source code +form. A _Major Component_, in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system (if any) on +which the executable work runs, or a compiler used to produce the work, or an +object code interpreter used to run it. + +The _Corresponding Source_ for a work in object code form means all the source +code needed to generate, install, and (for an executable work) run the object +code and to modify the work, including scripts to control those activities. +However, it does not include the work's System Libraries, or general-purpose +tools or generally available free programs which are used unmodified in +performing those activities but which are not part of the work. For example, +Corresponding Source includes interface definition files associated with source +files for the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, such as +by intimate data communication or control flow between those subprograms and +other parts of the work. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +### 2. Basic Permissions. + +All rights granted under this License are granted for the term of copyright on +the Program, and are irrevocable provided the stated conditions are met. This +License explicitly affirms your unlimited permission to run the unmodified +Program. The output from running a covered work is covered by this License only +if the output, given its content, constitutes a covered work. This License +acknowledges your rights of fair use or other equivalent, as provided by +copyright law. + +You may make, run and propagate covered works that you do not convey, without +conditions so long as your license otherwise remains in force. You may convey +covered works to others for the sole purpose of having them make modifications +exclusively for you, or provide you with facilities for running those works, +provided that you comply with the terms of this License in conveying all +material for which you do not control copyright. Those thus making or running +the covered works for you must do so exclusively on your behalf, under your +direction and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes it +unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological measure +under any applicable law fulfilling obligations under article 11 of the WIPO +copyright treaty adopted on 20 December 1996, or similar laws prohibiting or +restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention is +effected by exercising rights under this License with respect to the covered +work, and you disclaim any intention to limit operation or modification of the +work as a means of enforcing, against the work's users, your or third parties' +legal rights to forbid circumvention of technological measures. + +### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you receive it, +in any medium, provided that you conspicuously and appropriately publish on +each copy an appropriate copyright notice; keep intact all notices stating that +this License and any non-permissive terms added in accord with section 7 apply +to the code; keep intact all notices of the absence of any warranty; and give +all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may +offer support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to produce it +from the Program, in the form of source code under the terms of section 4, +provided that you also meet all of these conditions: + +- a) The work must carry prominent notices stating that you modified it, and + giving a relevant date. +- b) The work must carry prominent notices stating that it is released under + this License and any conditions added under section 7. This requirement + modifies the requirement in section 4 to _keep intact all notices_. +- c) You must license the entire work, as a whole, under this License to + anyone who comes into possession of a copy. This License will therefore + apply, along with any applicable section 7 additional terms, to the whole + of the work, and all its parts, regardless of how they are packaged. This + License gives no permission to license the work in any other way, but it + does not invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your work need + not make them do so. + +A compilation of a covered work with other separate and independent works, +which are not by their nature extensions of the covered work, and which are not +combined with it such as to form a larger program, in or on a volume of a +storage or distribution medium, is called an _aggregate_ if the compilation and +its resulting copyright are not used to limit the access or legal rights of the +compilation's users beyond what the individual works permit. Inclusion of a +covered work in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of sections 4 +and 5, provided that you also convey the machine-readable Corresponding Source +under the terms of this License, in one of these ways: + +- a) Convey the object code in, or embodied in, a physical product (including + a physical distribution medium), accompanied by the Corresponding Source + fixed on a durable physical medium customarily used for software + interchange. +- b) Convey the object code in, or embodied in, a physical product (including + a physical distribution medium), accompanied by a written offer, valid for + at least three years and valid for as long as you offer spare parts or + customer support for that product model, to give anyone who possesses the + object code either + 1. a copy of the Corresponding Source for all the software in the product + that is covered by this License, on a durable physical medium + customarily used for software interchange, for a price no more than your + reasonable cost of physically performing this conveying of source, or + 2. access to copy the Corresponding Source from a network server at no + charge. +- c) Convey individual copies of the object code with a copy of the written + offer to provide the Corresponding Source. This alternative is allowed only + occasionally and noncommercially, and only if you received the object code + with such an offer, in accord with subsection 6b. +- d) Convey the object code by offering access from a designated place + (gratis or for a charge), and offer equivalent access to the Corresponding + Source in the same way through the same place at no further charge. You + need not require recipients to copy the Corresponding Source along with the + object code. If the place to copy the object code is a network server, the + Corresponding Source may be on a different server operated by you or a + third party) that supports equivalent copying facilities, provided you + maintain clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the Corresponding + Source, you remain obligated to ensure that it is available for as long as + needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, provided you + inform other peers where the object code and Corresponding Source of the + work are being offered to the general public at no charge under subsection + 6d. + +A separable portion of the object code, whose source code is excluded from the +Corresponding Source as a System Library, need not be included in conveying the +object code work. + +A _User Product_ is either + +1. a _consumer product_, which means any tangible personal property which is + normally used for personal, family, or household purposes, or +2. anything designed or sold for incorporation into a dwelling. + +In determining whether a product is a consumer product, doubtful cases shall be +resolved in favor of coverage. For a particular product received by a +particular user, _normally used_ refers to a typical or common use of that +class of product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected to use, +the product. A product is a consumer product regardless of whether the product +has substantial commercial, industrial or non-consumer uses, unless such uses +represent the only significant mode of use of the product. + +_Installation Information_ for a User Product means any methods, procedures, +authorization keys, or other information required to install and execute +modified versions of a covered work in that User Product from a modified +version of its Corresponding Source. The information must suffice to ensure +that the continued functioning of the modified object code is in no case +prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as part of a +transaction in which the right of possession and use of the User Product is +transferred to the recipient in perpetuity or for a fixed term (regardless of +how the transaction is characterized), the Corresponding Source conveyed under +this section must be accompanied by the Installation Information. But this +requirement does not apply if neither you nor any third party retains the +ability to install modified object code on the User Product (for example, the +work has been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates for a +work that has been modified or installed by the recipient, or for the User +Product in which it has been modified or installed. Access to a network may be +denied when the modification itself materially and adversely affects the +operation of the network or violates the rules and protocols for communication +across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord +with this section must be in a format that is publicly documented (and with an +implementation available to the public in source code form), and must require +no special password or key for unpacking, reading or copying. + +### 7. Additional Terms. + +_Additional permissions_ are terms that supplement the terms of this License by +making exceptions from one or more of its conditions. Additional permissions +that are applicable to the entire Program shall be treated as though they were +included in this License, to the extent that they are valid under applicable +law. If additional permissions apply only to part of the Program, that part may +be used separately under those permissions, but the entire Program remains +governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any +additional permissions from that copy, or from any part of it. (Additional +permissions may be written to require their own removal in certain cases when +you modify the work.) You may place additional permissions on material, added +by you to a covered work, for which you have or can give appropriate copyright +permission. + +Notwithstanding any other provision of this License, for material you add to a +covered work, you may (if authorized by the copyright holders of that material) +supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the terms of + sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or author + attributions in that material or in the Appropriate Legal Notices displayed + by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in reasonable + ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors or authors + of the material; or +- e) Declining to grant rights under trademark law for use of some trade + names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that material by + anyone who conveys the material (or modified versions of it) with + contractual assumptions of liability to the recipient, for any liability + that these contractual assumptions directly impose on those licensors and + authors. + +All other non-permissive additional terms are considered _further restrictions_ +within the meaning of section 10. If the Program as you received it, or any +part of it, contains a notice stating that it is governed by this License along +with a term that is a further restriction, you may remove that term. If a +license document contains a further restriction but permits relicensing or +conveying under this License, you may add to a covered work material governed +by the terms of that license document, provided that the further restriction +does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, +in the relevant source files, a statement of the additional terms that apply to +those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a +separately written license, or stated as exceptions; the above requirements +apply either way. + +### 8. Termination. + +You may not propagate or modify a covered work except as expressly provided +under this License. Any attempt otherwise to propagate or modify it is void, +and will automatically terminate your rights under this License (including any +patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a +particular copyright holder is reinstated + +- a) provisionally, unless and until the copyright holder explicitly and + finally terminates your license, and +- b) permanently, if the copyright holder fails to notify you of the + violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated +permanently if the copyright holder notifies you of the violation by some +reasonable means, this is the first time you have received notice of violation +of this License (for any work) from that copyright holder, and you cure the +violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses +of parties who have received copies or rights from you under this License. If +your rights have been terminated and not permanently reinstated, you do not +qualify to receive new licenses for the same material under section 10. + +### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy +of the Program. Ancillary propagation of a covered work occurring solely as a +consequence of using peer-to-peer transmission to receive a copy likewise does +not require acceptance. However, nothing other than this License grants you +permission to propagate or modify any covered work. These actions infringe +copyright if you do not accept this License. Therefore, by modifying or +propagating a covered work, you indicate your acceptance of this License to do +so. + +### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a +license from the original licensors, to run, modify and propagate that work, +subject to this License. You are not responsible for enforcing compliance by +third parties with this License. + +An _entity transaction_ is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered work +results from an entity transaction, each party to that transaction who receives +a copy of the work also receives whatever licenses to the work the party's +predecessor in interest had or could give under the previous paragraph, plus a +right to possession of the Corresponding Source of the work from the +predecessor in interest, if the predecessor has it or can get it with +reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights +granted or affirmed under this License. For example, you may not impose a +license fee, royalty, or other charge for exercise of rights granted under this +License, and you may not initiate litigation (including a cross-claim or +counterclaim in a lawsuit) alleging that any patent claim is infringed by +making, using, selling, offering for sale, or importing the Program or any +portion of it. + +### 11. Patents. + +A _contributor_ is a copyright holder who authorizes use under this License of +the Program or a work on which the Program is based. The work thus licensed is +called the contributor's _contributor version_. + +A contributor's _essential patent claims_ are all patent claims owned or +controlled by the contributor, whether already acquired or hereafter acquired, +that would be infringed by some manner, permitted by this License, of making, +using, or selling its contributor version, but do not include claims that would +be infringed only as a consequence of further modification of the contributor +version. For purposes of this definition, _control_ includes the right to grant +patent sublicenses in a manner consistent with the requirements of this +License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent +license under the contributor's essential patent claims, to make, use, sell, +offer for sale, import and otherwise run, modify and propagate the contents of +its contributor version. + +In the following three paragraphs, a _patent license_ is any express agreement +or commitment, however denominated, not to enforce a patent (such as an express +permission to practice a patent or covenant not to sue for patent +infringement). To _grant_ such a patent license to a party means to make such +an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the +Corresponding Source of the work is not available for anyone to copy, free of +charge and under the terms of this License, through a publicly available +network server or other readily accessible means, then you must either + +1. cause the Corresponding Source to be so available, or +2. arrange to deprive yourself of the benefit of the patent license for this + particular work, or +3. arrange, in a manner consistent with the requirements of this License, to + extend the patent license to downstream recipients. + +_Knowingly relying_ means you have actual knowledge that, but for the patent +license, your conveying the covered work in a country, or your recipient's use +of the covered work in a country, would infringe one or more identifiable +patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you +convey, or propagate by procuring conveyance of, a covered work, and grant a +patent license to some of the parties receiving the covered work authorizing +them to use, propagate, modify or convey a specific copy of the covered work, +then the patent license you grant is automatically extended to all recipients +of the covered work and works based on it. + +A patent license is _discriminatory_ if it does not include within the scope of +its coverage, prohibits the exercise of, or is conditioned on the non-exercise +of one or more of the rights that are specifically granted under this License. +You may not convey a covered work if you are a party to an arrangement with a +third party that is in the business of distributing software, under which you +make payment to the third party based on the extent of your activity of +conveying the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory patent +license + +- a) in connection with copies of the covered work conveyed by you (or copies + made from those copies), or +- b) primarily for and in connection with specific products or compilations + that contain the covered work, unless you entered into that arrangement, or + that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied +license or other defenses to infringement that may otherwise be available to +you under applicable patent law. + +### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not excuse +you from the conditions of this License. If you cannot convey a covered work so +as to satisfy simultaneously your obligations under this License and any other +pertinent obligations, then as a consequence you may not convey it at all. For +example, if you agree to terms that obligate you to collect a royalty for +further conveying from those to whom you convey the Program, the only way you +could satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +### 13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have permission to +link or combine any covered work with a work licensed under version 3 of the +GNU Affero General Public License into a single combined work, and to convey +the resulting work. The terms of this License will continue to apply to the +part which is the covered work, but the special requirements of the GNU Affero +General Public License, section 13, concerning interaction through a network +will apply to the combination as such. + +### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU +General Public License from time to time. Such new versions will be similar in +spirit to the present version, but may differ in detail to address new problems +or concerns. + +Each version is given a distinguishing version number. If the Program specifies +that a certain numbered version of the GNU General Public License _or any later +version_ applies to it, you have the option of following the terms and +conditions either of that numbered version or of any later version published by +the Free Software Foundation. If the Program does not specify a version number +of the GNU General Public License, you may choose any version ever published by +the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the +GNU General Public License can be used, that proxy's public statement of +acceptance of a version permanently authorizes you to choose that version for +the Program. + +Later license versions may give you additional or different permissions. +However, no additional obligations are imposed on any author or copyright +holder as a result of your choosing to follow a later version. + +### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE +LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER +PARTIES PROVIDE THE PROGRAM _AS IS_ WITHOUT WARRANTY OF ANY KIND, EITHER +EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE +QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY +COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS +PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, +INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE +THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED +INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE +PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY +HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot +be given local legal effect according to their terms, reviewing courts shall +apply local law that most closely approximates an absolute waiver of all civil +liability in connection with the Program, unless a warranty or assumption of +liability accompanies a copy of the Program in return for a fee. + +## END OF TERMS AND CONDITIONS + +### How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible +use to the public, the best way to achieve this is to make it free software +which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach +them to the start of each source file to most effectively state the exclusion +of warranty; and each file should have at least the _copyright_ line and a +pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like +this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w` and `show c` should show the appropriate +parts of the General Public License. Of course, your program's commands might +be different; for a GUI interface, you would use an _about box_. + +You should also get your employer (if you work as a programmer) or school, if +any, to sign a _copyright disclaimer_ for the program, if necessary. For more +information on this, and how to apply and follow the GNU GPL, see +[http://www.gnu.org/licenses/](http://www.gnu.org/licenses/). + +The GNU General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may consider +it more useful to permit linking proprietary applications with the library. If +this is what you want to do, use the GNU Lesser General Public License instead +of this License. But first, please read +[http://www.gnu.org/philosophy/why-not-lgpl.html](http://www.gnu.org/philosophy/why-not-lgpl.html). diff --git a/README.md b/README.md new file mode 100644 index 0000000..5af7b1f --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# Refraction bot + +The Refraction Bot used in the [Prism Launcher Discord](https://discord.gg/prismlauncher). diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..5638757 --- /dev/null +++ b/build.rs @@ -0,0 +1,88 @@ +use std::io::Write; +use std::path::Path; +use std::{env, fs}; + +use gray_matter::{engine, Matter}; + +include!("src/tags.rs"); + +/// generate the `ChoiceParameter` enum and tag data we will use in the `tag` command +#[allow(dead_code)] +fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + let dest_file = Path::new(&out_dir).join("generated.rs"); + let mut file = fs::File::create(dest_file).unwrap(); + + let tag_files: Vec = fs::read_dir(TAG_DIR) + .unwrap() + .map(|f| f.unwrap().file_name().to_string_lossy().to_string()) + .collect(); + + let mut tags: Vec = tag_files + .clone() + .into_iter() + .map(|name| { + let file_name = format!("{TAG_DIR}/{name}"); + let file_content = fs::read_to_string(&file_name).unwrap(); + + let matter = Matter::::new(); + let parsed = matter.parse(&file_content); + let content = parsed.content; + let data = parsed + .data + .unwrap() + .deserialize() + .unwrap_or_else(|e| { + // actually handling the error since this is the most likely thing to fail -getchoo + panic!( + "Failed to parse file {file_name}! Here's what it looked like:\n{content}\n\nReported Error:\n{e}\n", + ) + }); + + Tag { + content, + id: name.trim_end_matches(".md").to_string(), + frontmatter: data, + } + }) + .collect(); + + tags.sort_by(|t1, t2| t1.id.cmp(&t2.id)); + + let tag_names: Vec = tags.iter().map(|t| format!("{},", t.id)).collect(); + + let tag_matches: Vec = tags + .iter() + .map(|t| format!("Self::{} => \"{}\",", t.id, t.id)) + .collect(); + + writeln!( + file, + r#"#[allow(non_camel_case_types, clippy::upper_case_acronyms)] +#[derive(Clone, Debug, poise::ChoiceParameter)] +pub enum Choice {{ + {} +}}"#, + tag_names.join("\n") + ) + .unwrap(); + + writeln!( + file, + r#"impl Choice {{ + fn as_str(&self) -> &str {{ + match &self {{ + {} + }} + }} +}}"#, + tag_matches.join("\n") + ) + .unwrap(); + + println!( + "cargo:rustc-env=TAGS={}", + // make sure we can deserialize with env! at runtime + serde_json::to_string(&tags).unwrap() + ); +} diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..563ec7d --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1750898778, + "narHash": "sha256-DXI7+SKDlTyA+C4zp0LoIywQ+BfdH5m4nkuxbWgV4UU=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "322d8a3c6940039f7cff179a8b09c5d7ca06359d", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..52f0c33 --- /dev/null +++ b/flake.nix @@ -0,0 +1,127 @@ +{ + description = "Discord bot for Prism Launcher"; + + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; + + outputs = + { + self, + nixpkgs, + }: + let + inherit (nixpkgs) lib; + systems = [ + "x86_64-linux" + "aarch64-linux" + "x86_64-darwin" + "aarch64-darwin" + ]; + + forAllSystems = lib.genAttrs systems; + nixpkgsFor = nixpkgs.legacyPackages; + in + { + checks = forAllSystems ( + system: + let + pkgs = nixpkgsFor.${system}; + mkCheck = + name: deps: script: + pkgs.runCommand name { nativeBuildInputs = deps; } '' + ${script} + touch $out + ''; + in + { + actionlint = mkCheck "check-actionlint" [ pkgs.actionlint ] "actionlint ${./.github/workflows}/*"; + deadnix = mkCheck "check-deadnix" [ pkgs.deadnix ] "deadnix --fail ${self}"; + statix = mkCheck "check-statix" [ pkgs.statix ] "statix check ${self}"; + nixfmt = mkCheck "check-nixfmt" [ pkgs.nixfmt-rfc-style ] "nixfmt --check ${self}"; + rustfmt = mkCheck "check-rustfmt" [ + pkgs.cargo + pkgs.rustfmt + ] "cd ${self} && cargo fmt -- --check"; + } + ); + + devShells = forAllSystems ( + system: + let + pkgs = nixpkgsFor.${system}; + in + { + default = pkgs.mkShell { + packages = with pkgs; [ + redis + + # linters & formatters + actionlint + nodePackages.prettier + + # rust tools + clippy + rustfmt + rust-analyzer + + # nix tools + self.formatter.${system} + nil + statix + ]; + + inputsFrom = [ self.packages.${pkgs.system}.refraction ]; + RUST_SRC_PATH = "${pkgs.rustPlatform.rustLibSrc}"; + }; + } + ); + + formatter = forAllSystems (system: nixpkgsFor.${system}.nixfmt-rfc-style); + + nixosModules.default = import ./nix/module.nix self; + + # For CI + legacyPackages = forAllSystems ( + system: + let + pkgs = nixpkgsFor.${system}; + in + { + clippy-report = pkgs.callPackage ./nix/clippy.nix { inherit (self.packages.${system}) refraction; }; + + refraction-debug = (self.packages.${system}.refraction.override { lto = false; }).overrideAttrs ( + finalAttrs: _: { + cargoBuildType = "debug"; + cargoCheckType = finalAttrs.cargoBuildType; + } + ); + } + ); + + packages = forAllSystems ( + system: + let + pkgs = nixpkgsFor.${system}; + packages' = self.packages.${system}; + + refractionPackages = lib.makeScope pkgs.newScope (lib.flip self.overlays.default pkgs); + + mkStatic = pkgs.callPackage ./nix/static.nix { }; + containerize = pkgs.callPackage ./nix/containerize.nix { }; + in + { + inherit (refractionPackages) refraction; + + static-x86_64 = mkStatic { arch = "x86_64"; }; + static-aarch64 = mkStatic { arch = "aarch64"; }; + container-amd64 = containerize packages'.static-x86_64; + container-arm64 = containerize packages'.static-aarch64; + + default = packages'.refraction; + } + ); + + overlays.default = final: _: { + refraction = final.callPackage ./nix/package.nix { }; + }; + }; +} diff --git a/nix/clippy.nix b/nix/clippy.nix new file mode 100644 index 0000000..9c360a9 --- /dev/null +++ b/nix/clippy.nix @@ -0,0 +1,39 @@ +{ + cargo, + clippy, + clippy-sarif, + refraction, + rustPlatform, + sarif-fmt, + stdenv, +}: + +stdenv.mkDerivation { + pname = "${refraction.pname}-sarif-report"; + inherit (refraction) + version + src + cargoDeps + buildInputs + ; + + nativeBuildInputs = [ + cargo + clippy + clippy-sarif + rustPlatform.cargoSetupHook + sarif-fmt + ]; + + buildPhase = '' + cargo clippy \ + --all-features \ + --all-targets \ + --tests \ + --message-format=json \ + | clippy-sarif | tee $out | sarif-fmt + ''; + + dontInstall = true; + dontFixup = true; +} diff --git a/nix/containerize.nix b/nix/containerize.nix new file mode 100644 index 0000000..558a7c8 --- /dev/null +++ b/nix/containerize.nix @@ -0,0 +1,9 @@ +{ lib, dockerTools }: +refraction: + +dockerTools.buildLayeredImage { + name = "refraction"; + tag = "latest-${refraction.passthru.dockerArchitecture}"; + config.Cmd = [ (lib.getExe refraction) ]; + architecture = refraction.passthru.dockerArchitecture; +} diff --git a/nix/module.nix b/nix/module.nix new file mode 100644 index 0000000..4e6d8a6 --- /dev/null +++ b/nix/module.nix @@ -0,0 +1,147 @@ +self: +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.services.refraction; + defaultUser = "refraction"; + + inherit (lib) + getExe + literalExpression + mkEnableOption + mkIf + mkOption + mkPackageOption + optionals + types + ; +in +{ + options.services.refraction = { + enable = mkEnableOption "refraction"; + package = mkPackageOption self.packages.${pkgs.stdenv.hostPlatform.system} "refraction" { }; + + user = mkOption { + description = '' + User under which the service should run. If this is the default value, + the user will be created, with the specified group as the primary + group. + ''; + type = types.str; + default = defaultUser; + example = literalExpression '' + "bob" + ''; + }; + + group = mkOption { + description = '' + Group under which the service should run. If this is the default value, + the group will be created. + ''; + type = types.str; + default = defaultUser; + example = literalExpression '' + "discordbots" + ''; + }; + + redisUrl = mkOption { + description = '' + Connection to a redis server. If this needs to include credentials + that shouldn't be world-readable in the Nix store, set environmentFile + and override the `REDIS_URL` entry. + Pass the string `local` to setup a local Redis database. + ''; + type = types.str; + default = "local"; + example = literalExpression '' + "redis://localhost/" + ''; + }; + + environmentFile = mkOption { + description = '' + Environment file as defined in {manpage}`systemd.exec(5)` + ''; + type = types.nullOr types.path; + default = null; + example = literalExpression '' + "/run/agenix.d/1/refraction" + ''; + }; + }; + + config = mkIf cfg.enable { + services.redis.servers.refraction = mkIf (cfg.redisUrl == "local") { + enable = true; + inherit (cfg) user; + port = 0; # disable tcp listener + }; + + systemd.services."refraction" = { + enable = true; + wantedBy = [ "multi-user.target" ]; + after = [ "network.target" ] ++ optionals (cfg.redisUrl == "local") [ "redis-refraction.service" ]; + + script = '' + ${getExe cfg.package} + ''; + + environment = { + BOT_REDIS_URL = + if cfg.redisUrl == "local" then + "unix:${config.services.redis.servers.refraction.unixSocket}" + else + cfg.redisUrl; + }; + + serviceConfig = { + Type = "simple"; + Restart = "on-failure"; + + EnvironmentFile = mkIf (cfg.environmentFile != null) cfg.environmentFile; + + User = cfg.user; + Group = cfg.group; + + # hardening + NoNewPrivileges = true; + PrivateDevices = true; + PrivateTmp = true; + PrivateUsers = true; + ProtectClock = true; + ProtectControlGroups = true; + ProtectHome = true; + ProtectHostname = true; + ProtectKernelLogs = true; + ProtectKernelModules = true; + ProtectKernelTunables = true; + ProtectSystem = "strict"; + RestrictNamespaces = true; + RestrictSUIDSGID = true; + SystemCallArchitectures = "native"; + SystemCallFilter = [ + "@system-service" + "~@resources" + "~@privileged" + ]; + }; + }; + + users = { + users = mkIf (cfg.user == defaultUser) { + ${defaultUser} = { + isSystemUser = true; + inherit (cfg) group; + }; + }; + + groups = mkIf (cfg.group == defaultUser) { ${defaultUser} = { }; }; + }; + }; +} diff --git a/nix/package.nix b/nix/package.nix new file mode 100644 index 0000000..92f80df --- /dev/null +++ b/nix/package.nix @@ -0,0 +1,68 @@ +{ + lib, + stdenv, + go, + rustPlatform, + lto ? !optimizeSize, + optimizeSize ? false, +}: + +let + fs = lib.fileset; + toRustFlags = flags: toString (lib.mapAttrsToList (name: value: "-C ${name}=${value}") flags); +in +assert lib.assertMsg (lto -> !optimizeSize) "`lto` and `optimizeSize` are mutually exclusive"; +rustPlatform.buildRustPackage rec { + pname = "refraction"; + inherit (passthru.cargoToml.package) version; + + src = fs.toSource { + root = ../.; + fileset = fs.intersection (fs.gitTracked ../.) ( + fs.unions [ + ../src + ../build.rs + ../Cargo.lock + ../Cargo.toml + ../tags + ] + ); + }; + + cargoLock.lockFile = ../Cargo.lock; + + # `panic=abort` breaks tests womp womp + doCheck = stdenv.buildPlatform.canExecute stdenv.hostPlatform && !optimizeSize; + + env = { + RUSTFLAGS = toRustFlags ( + lib.optionalAttrs lto { + lto = "thin"; + embed-bitcode = "yes"; + } + // lib.optionalAttrs optimizeSize { + codegen-units = "1"; + opt-level = "s"; + panic = "abort"; + strip = "symbols"; + } + ); + }; + + passthru = { + cargoToml = lib.importTOML ../Cargo.toml; + # For container images + dockerArchitecture = go.GOARCH; + }; + + meta = { + description = "Discord bot for Prism Launcher"; + homepage = "https://github.com/PrismLauncher/refraction"; + license = lib.licenses.gpl3Plus; + maintainers = with lib.maintainers; [ + getchoo + Scrumplex + ]; + mainProgram = "refraction"; + }; +} diff --git a/nix/static.nix b/nix/static.nix new file mode 100644 index 0000000..8df03c8 --- /dev/null +++ b/nix/static.nix @@ -0,0 +1,9 @@ +{ pkgsCross }: +let + crossPlatformFor = with pkgsCross; { + x86_64 = musl64.pkgsStatic; + aarch64 = aarch64-multiplatform.pkgsStatic; + }; +in +{ arch }: +crossPlatformFor.${arch}.callPackage ./package.nix { optimizeSize = true; } diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..b21456f --- /dev/null +++ b/renovate.json @@ -0,0 +1,7 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": ["config:recommended", "config:recommended", ":automergeMinor"], + "lockFileMaintenance": { + "enabled": true + } +} diff --git a/src/api/dadjoke.rs b/src/api/dadjoke.rs new file mode 100644 index 0000000..00a284e --- /dev/null +++ b/src/api/dadjoke.rs @@ -0,0 +1,17 @@ +use super::HttpClient; + +use eyre::Result; + +const DADJOKE: &str = "https://icanhazdadjoke.com"; + +pub async fn get_joke(http: &HttpClient) -> Result { + let joke = http + .get(DADJOKE) + .header("Accept", "text/plain") + .send() + .await? + .text() + .await?; + + Ok(joke) +} diff --git a/src/api/github.rs b/src/api/github.rs new file mode 100644 index 0000000..18b533a --- /dev/null +++ b/src/api/github.rs @@ -0,0 +1,30 @@ +use eyre::{OptionExt, Result, WrapErr}; +use log::debug; +use octocrab::Octocrab; + +pub async fn get_latest_prism_version(octocrab: &Octocrab) -> Result { + debug!("Fetching the latest version of Prism Launcher"); + + let version = octocrab + .repos("PrismLauncher", "PrismLauncher") + .releases() + .get_latest() + .await? + .tag_name; + + Ok(version) +} + +pub async fn get_prism_stargazers_count(octocrab: &Octocrab) -> Result { + debug!("Fetching Prism Launcher's stargazer count"); + + let stargazers_count = octocrab + .repos("PrismLauncher", "PrismLauncher") + .get() + .await + .wrap_err("Couldn't fetch PrismLauncher/PrismLauncher!")? + .stargazers_count + .ok_or_eyre("Couldn't retrieve stargazers_coutn from GitHub!")?; + + Ok(stargazers_count) +} diff --git a/src/api/mod.rs b/src/api/mod.rs new file mode 100644 index 0000000..cb1c7bf --- /dev/null +++ b/src/api/mod.rs @@ -0,0 +1,36 @@ +use log::trace; +use reqwest::Response; + +pub mod dadjoke; +pub mod github; +pub mod paste_gg; +pub mod pluralkit; +pub mod prism_meta; +pub mod rory; + +pub type HttpClient = reqwest::Client; + +pub trait HttpClientExt { + // sadly i can't implement the actual Default trait :/ + fn default() -> Self; + async fn get_request(&self, url: &str) -> Result; +} + +impl HttpClientExt for HttpClient { + fn default() -> Self { + let version = option_env!("CARGO_PKG_VERSION").unwrap_or("development"); + let user_agent = format!("refraction/{version}"); + reqwest::ClientBuilder::new() + .user_agent(user_agent) + .build() + .unwrap_or_default() + } + + async fn get_request(&self, url: &str) -> Result { + trace!("Making request to {url}"); + let resp = self.get(url).send().await?; + resp.error_for_status_ref()?; + + Ok(resp) + } +} diff --git a/src/api/paste_gg.rs b/src/api/paste_gg.rs new file mode 100644 index 0000000..a4004cb --- /dev/null +++ b/src/api/paste_gg.rs @@ -0,0 +1,55 @@ +use super::{HttpClient, HttpClientExt}; + +use eyre::{eyre, OptionExt, Result}; +use serde::{Deserialize, Serialize}; + +const PASTE_GG: &str = "https://api.paste.gg/v1"; +const PASTES: &str = "/pastes"; + +#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Deserialize, Serialize)] +pub enum Status { + #[serde(rename = "success")] + Success, + #[serde(rename = "error")] + Error, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Response { + pub status: Status, + pub result: Option>, + pub error: Option, + pub message: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Files { + pub id: String, + pub name: Option, +} + +pub async fn files_from(http: &HttpClient, id: &str) -> Result> { + let url = format!("{PASTE_GG}{PASTES}/{id}/files"); + let resp: Response = http.get_request(&url).await?.json().await?; + + if resp.status == Status::Error { + let message = resp + .error + .ok_or_eyre("Paste.gg gave us an error but with no message!")?; + + Err(eyre!(message)) + } else { + Ok(resp) + } +} + +pub async fn get_raw_file( + http: &HttpClient, + paste_id: &str, + file_id: &str, +) -> eyre::Result { + let url = format!("{PASTE_GG}{PASTES}/{paste_id}/files/{file_id}/raw"); + let text = http.get_request(&url).await?.text().await?; + + Ok(text) +} diff --git a/src/api/pluralkit.rs b/src/api/pluralkit.rs new file mode 100644 index 0000000..0b16793 --- /dev/null +++ b/src/api/pluralkit.rs @@ -0,0 +1,26 @@ +use super::{HttpClient, HttpClientExt}; + +use eyre::{Context, Result}; +use poise::serenity_prelude::{MessageId, UserId}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Message { + pub sender: String, +} + +const PLURAL_KIT: &str = "https://api.pluralkit.me/v2"; +const MESSAGES: &str = "/messages"; + +pub async fn sender_from(http: &HttpClient, message_id: MessageId) -> Result { + let url = format!("{PLURAL_KIT}{MESSAGES}/{message_id}"); + let resp: Message = http.get_request(&url).await?.json().await?; + + let id: u64 = + resp.sender.parse().wrap_err_with(|| { + format!("Couldn't parse response from PluralKit as a UserId! Here's the response:\n{resp:#?}") + })?; + let sender = UserId::from(id); + + Ok(sender) +} diff --git a/src/api/prism_meta.rs b/src/api/prism_meta.rs new file mode 100644 index 0000000..f7efb0a --- /dev/null +++ b/src/api/prism_meta.rs @@ -0,0 +1,28 @@ +use super::{HttpClient, HttpClientExt}; + +use eyre::{OptionExt, Result}; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MinecraftPackageJson { + pub format_version: u8, + pub name: String, + pub recommended: Vec, + pub uid: String, +} + +const META: &str = "https://meta.prismlauncher.org/v1"; +const MINECRAFT_PACKAGEJSON: &str = "/net.minecraft/package.json"; + +pub async fn latest_minecraft_version(http: &HttpClient) -> Result { + let url = format!("{META}{MINECRAFT_PACKAGEJSON}"); + let data: MinecraftPackageJson = http.get_request(&url).await?.json().await?; + + let version = data + .recommended + .first() + .ok_or_eyre("Couldn't find latest version of Minecraft!")?; + + Ok(version.clone()) +} diff --git a/src/api/rory.rs b/src/api/rory.rs new file mode 100644 index 0000000..3fffbbe --- /dev/null +++ b/src/api/rory.rs @@ -0,0 +1,28 @@ +use super::{HttpClient, HttpClientExt}; + +use eyre::{Context, Result}; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +pub struct Response { + pub id: u64, + pub url: String, + pub error: Option, +} + +const RORY: &str = "https://rory.cat"; +const PURR: &str = "/purr"; + +pub async fn get(http: &HttpClient, id: Option) -> Result { + let target = id.map(|id| id.to_string()).unwrap_or_default(); + let url = format!("{RORY}{PURR}/{target}"); + + let data: Response = http + .get_request(&url) + .await? + .json() + .await + .wrap_err("Couldn't parse the rory response!")?; + + Ok(data) +} diff --git a/src/commands/general/help.rs b/src/commands/general/help.rs new file mode 100644 index 0000000..bc6cb76 --- /dev/null +++ b/src/commands/general/help.rs @@ -0,0 +1,22 @@ +use crate::{Context, Error}; + +use log::trace; +use poise::samples::HelpConfiguration; + +/// View the help menu +#[poise::command(slash_command, prefix_command, track_edits = true)] +pub async fn help( + ctx: Context<'_>, + #[description = "Provide information about a specific command"] command: Option, +) -> Result<(), Error> { + trace!("Running help command"); + + let configuration = HelpConfiguration { + extra_text_at_bottom: "Use /help for more information about a specific command!", + ..Default::default() + }; + + poise::builtins::help(ctx, command.as_deref(), configuration).await?; + + Ok(()) +} diff --git a/src/commands/general/joke.rs b/src/commands/general/joke.rs new file mode 100644 index 0000000..e08282e --- /dev/null +++ b/src/commands/general/joke.rs @@ -0,0 +1,16 @@ +use crate::{api::dadjoke, Context, Error}; + +use eyre::Result; +use log::trace; + +/// It's a joke +#[poise::command(slash_command, prefix_command, track_edits = true)] +pub async fn joke(ctx: Context<'_>) -> Result<(), Error> { + trace!("Running joke command"); + + ctx.defer().await?; + let joke = dadjoke::get_joke(&ctx.data().http_client).await?; + ctx.say(joke).await?; + + Ok(()) +} diff --git a/src/commands/general/members.rs b/src/commands/general/members.rs new file mode 100644 index 0000000..0476972 --- /dev/null +++ b/src/commands/general/members.rs @@ -0,0 +1,37 @@ +use crate::{consts::Colors, Context, Error}; + +use eyre::{eyre, Context as _, OptionExt}; +use log::trace; +use poise::serenity_prelude::CreateEmbed; +use poise::CreateReply; + +/// Returns the number of members in the server +#[poise::command(slash_command, prefix_command, guild_only = true, track_edits = true)] +pub async fn members(ctx: Context<'_>) -> Result<(), Error> { + trace!("Running members command"); + + ctx.defer().await?; + + let guild_id = ctx.guild_id().ok_or_eyre("Couldn't get guild ID!")?; + let guild = ctx + .http() + .get_guild_with_counts(guild_id) + .await + .wrap_err_with(|| format!("Couldn't fetch guild {guild_id} with counts!"))?; + + let member_count = guild + .approximate_member_count + .ok_or_else(|| eyre!("Couldn't get member count for guild {guild_id}!"))?; + let online_count = guild + .approximate_presence_count + .ok_or_else(|| eyre!("Couldn't get online count for guild {guild_id}!"))?; + + let embed = CreateEmbed::new() + .title(format!("{member_count} total members!",)) + .description(format!("{online_count} online members",)) + .color(Colors::Blue); + let reply = CreateReply::default().embed(embed); + + ctx.send(reply).await?; + Ok(()) +} diff --git a/src/commands/general/mod.rs b/src/commands/general/mod.rs new file mode 100644 index 0000000..7e2d92f --- /dev/null +++ b/src/commands/general/mod.rs @@ -0,0 +1,8 @@ +pub mod help; +pub mod joke; +pub mod members; +pub mod ping; +pub mod rory; +pub mod say; +pub mod stars; +pub mod tag; diff --git a/src/commands/general/ping.rs b/src/commands/general/ping.rs new file mode 100644 index 0000000..f4bd501 --- /dev/null +++ b/src/commands/general/ping.rs @@ -0,0 +1,34 @@ +use std::time::{Duration, Instant}; + +use crate::{Context, Error}; + +use log::trace; +use poise::CreateReply; + +const PING_PREFIX: &str = "<:catstareback:1078622789885497414> Pong!"; + +/// Replies with pong! +#[poise::command(slash_command, prefix_command, track_edits = true, ephemeral)] +pub async fn ping(ctx: Context<'_>) -> Result<(), Error> { + trace!("Running ping command!"); + + let start = Instant::now(); + let response = ctx.say(PING_PREFIX).await?; + + let rtt = start.elapsed().as_millis(); + let gateway_ping = match ctx.ping().await { + Duration::ZERO => "Undetermined".to_string(), + duration => format!("{}ms", duration.as_millis()), + }; + + response + .edit( + ctx, + CreateReply::default().content(format!( + "{PING_PREFIX}\n\nRTT: {rtt}ms\nGateway: {gateway_ping}", + )), + ) + .await?; + + Ok(()) +} diff --git a/src/commands/general/rory.rs b/src/commands/general/rory.rs new file mode 100644 index 0000000..f02783d --- /dev/null +++ b/src/commands/general/rory.rs @@ -0,0 +1,37 @@ +use crate::{api::rory, Context, Error}; + +use log::trace; +use poise::serenity_prelude::{CreateEmbed, CreateEmbedFooter}; +use poise::CreateReply; + +/// Gets a Rory photo! +#[poise::command(slash_command, prefix_command, track_edits = true)] +pub async fn rory( + ctx: Context<'_>, + #[description = "specify a Rory ID"] id: Option, +) -> Result<(), Error> { + trace!("Running rory command"); + + ctx.defer().await?; + + let rory = rory::get(&ctx.data().http_client, id).await?; + + let embed = { + let embed = CreateEmbed::new(); + if let Some(error) = rory.error { + embed.title("Error!").description(error) + } else { + let footer = CreateEmbedFooter::new(format!("ID {}", rory.id)); + embed + .title("Rory :3") + .url(&rory.url) + .image(rory.url) + .footer(footer) + } + }; + + let reply = CreateReply::default().embed(embed); + ctx.send(reply).await?; + + Ok(()) +} diff --git a/src/commands/general/say.rs b/src/commands/general/say.rs new file mode 100644 index 0000000..eeb1a4a --- /dev/null +++ b/src/commands/general/say.rs @@ -0,0 +1,42 @@ +use crate::{utils, Context, Error}; + +use log::trace; +use poise::serenity_prelude::{CreateEmbed, CreateMessage}; + +/// Say something through the bot +#[poise::command( + slash_command, + ephemeral, + default_member_permissions = "MODERATE_MEMBERS", + required_permissions = "MODERATE_MEMBERS", + guild_only +)] +pub async fn say( + ctx: Context<'_>, + #[description = "the message content"] content: String, +) -> Result<(), Error> { + let channel = ctx.channel_id(); + let content = content.replace("\\n", "\n"); + let message = channel.say(ctx, &content).await?; + ctx.say("I said what you said!").await?; + + if let Some(channel_id) = ctx.data().config.discord.channels.log_channel_id { + let author = utils::embed_author_from_user(ctx.author()); + + let embed = CreateEmbed::default() + .title("Say command used!") + .description(format!( + "{}\n\n[Jump to message]({})", + content, + message.link() + )) + .author(author); + + let message = CreateMessage::new().embed(embed); + channel_id.send_message(ctx, message).await?; + } else { + trace!("Not sending /say log as no channel is set"); + } + + Ok(()) +} diff --git a/src/commands/general/stars.rs b/src/commands/general/stars.rs new file mode 100644 index 0000000..603f435 --- /dev/null +++ b/src/commands/general/stars.rs @@ -0,0 +1,36 @@ +use crate::{api, consts::Colors, Context, Error}; + +use log::trace; +use poise::serenity_prelude::CreateEmbed; +use poise::CreateReply; + +/// Returns GitHub stargazer count +#[poise::command(slash_command, prefix_command, track_edits = true)] +pub async fn stars(ctx: Context<'_>) -> Result<(), Error> { + trace!("Running stars command"); + let octocrab = &ctx.data().octocrab; + + ctx.defer().await?; + + let count = if let Some(storage) = &ctx.data().storage { + if let Ok(count) = storage.launcher_stargazer_count().await { + count + } else { + let count = api::github::get_prism_stargazers_count(octocrab).await?; + storage.cache_launcher_stargazer_count(count).await?; + count + } + } else { + trace!("Not caching launcher stargazer count, as we're running without a storage backend"); + api::github::get_prism_stargazers_count(octocrab).await? + }; + + let embed = CreateEmbed::new() + .title(format!("⭐ {count} total stars!")) + .color(Colors::Yellow); + let reply = CreateReply::default().embed(embed); + + ctx.send(reply).await?; + + Ok(()) +} diff --git a/src/commands/general/tag.rs b/src/commands/general/tag.rs new file mode 100644 index 0000000..31d960c --- /dev/null +++ b/src/commands/general/tag.rs @@ -0,0 +1,91 @@ +#![allow(non_camel_case_types, clippy::upper_case_acronyms)] +use crate::{consts::Colors, tags::Tag, Context, Error}; +use std::env; +use std::str::FromStr; +use std::sync::OnceLock; + +use eyre::eyre; +use log::trace; +use poise::serenity_prelude::{Color, CreateAllowedMentions, CreateEmbed, User}; +use poise::CreateReply; + +include!(concat!(env!("OUT_DIR"), "/generated.rs")); +fn tags() -> &'static Vec { + static TAGS: OnceLock> = OnceLock::new(); + TAGS.get_or_init(|| serde_json::from_str(env!("TAGS")).unwrap()) +} + +/// Send a tag +#[poise::command( + slash_command, + prefix_command, + track_edits = true, + help_text_fn = help +)] +pub async fn tag( + ctx: Context<'_>, + #[description = "the tag to send"] name: Choice, + #[description = "a user to mention"] user: Option, +) -> Result<(), Error> { + trace!("Running tag command"); + + let tag_id = name.as_str(); + let tag = tags() + .iter() + .find(|t| t.id == tag_id) + .ok_or_else(|| eyre!("Tried to get non-existent tag: {tag_id}"))?; + + let frontmatter = &tag.frontmatter; + + let embed = { + let mut e = CreateEmbed::new(); + + if let Some(color) = &frontmatter.color { + let color = Colors::from_str(color.as_str()) + .map(Color::from) + .unwrap_or_default(); + + e = e.color(color); + } + + if let Some(image) = &frontmatter.image { + e = e.image(image); + } + + if let Some(fields) = &frontmatter.fields { + for field in fields { + e = e.field(&field.name, &field.value, field.inline); + } + } + + e = e.title(&frontmatter.title); + e = e.description(&tag.content); + + e + }; + + let reply = { + let mut r = CreateReply::default(); + + if let Some(user) = user { + r = r.content(format!("<@{}>", user.id)); + r = r.allowed_mentions(CreateAllowedMentions::new().users(vec![user.id])); + } + + r.embed(embed) + }; + + ctx.send(reply).await?; + + Ok(()) +} + +fn help() -> String { + let tag_list = tags() + .iter() + .map(|tag| format!("`{}`", tag.id)) + .collect::>() + .join(", "); + + format!("Available tags: {tag_list}") +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs new file mode 100644 index 0000000..2292afd --- /dev/null +++ b/src/commands/mod.rs @@ -0,0 +1,47 @@ +use crate::{Data, Error}; + +mod general; +mod moderation; + +macro_rules! command { + ($module: ident, $name: ident) => { + $module::$name::$name() + }; + + ($module: ident, $name: ident, $func: ident) => { + $module::$name::$func() + }; +} + +macro_rules! module_macro { + ($module: ident) => { + macro_rules! $module { + ($name: ident) => { + command!($module, $name) + }; + + ($name: ident, $func: ident) => { + command!($module, $name, $func) + }; + } + }; +} + +module_macro!(general); +module_macro!(moderation); + +pub type Command = poise::Command; + +pub fn all() -> Vec { + vec![ + general!(help), + general!(joke), + general!(members), + general!(ping), + general!(rory), + general!(say), + general!(stars), + general!(tag), + moderation!(set_welcome), + ] +} diff --git a/src/commands/moderation/mod.rs b/src/commands/moderation/mod.rs new file mode 100644 index 0000000..d5578a0 --- /dev/null +++ b/src/commands/moderation/mod.rs @@ -0,0 +1 @@ +pub mod set_welcome; diff --git a/src/commands/moderation/set_welcome.rs b/src/commands/moderation/set_welcome.rs new file mode 100644 index 0000000..0746b81 --- /dev/null +++ b/src/commands/moderation/set_welcome.rs @@ -0,0 +1,198 @@ +use std::{fmt::Write, str::FromStr}; + +use crate::{api::HttpClientExt, utils, Context, Error}; + +use eyre::Result; +use log::trace; +use poise::serenity_prelude::{ + futures::TryStreamExt, Attachment, CreateActionRow, CreateButton, CreateEmbed, CreateMessage, + Mentionable, Message, ReactionType, +}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct WelcomeEmbed { + title: String, + description: Option, + url: Option, + hex_color: Option, + image: Option, +} + +impl From for CreateMessage { + fn from(val: WelcomeEmbed) -> Self { + let mut embed = CreateEmbed::new(); + + embed = embed.title(val.title); + if let Some(description) = val.description { + embed = embed.description(description); + } + + if let Some(url) = val.url { + embed = embed.url(url); + } + + if let Some(color) = val.hex_color { + let hex = i32::from_str_radix(&color, 16).unwrap(); + embed = embed.color(hex); + } + + if let Some(image) = val.image { + embed = embed.image(image); + } + + Self::new().embed(embed) + } +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct WelcomeRole { + title: String, + id: u64, + emoji: Option, +} + +impl From for CreateButton { + fn from(value: WelcomeRole) -> Self { + let mut button = Self::new(value.id.to_string()).label(value.title); + if let Some(emoji) = value.emoji { + button = button.emoji(ReactionType::from_str(&emoji).unwrap()); + } + + button + } +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct WelcomeRoleCategory { + title: String, + description: Option, + roles: Vec, +} + +impl From for CreateMessage { + fn from(value: WelcomeRoleCategory) -> Self { + let mut content = format!("**{}**", value.title); + if let Some(description) = value.description { + write!(content, "\n{description}").ok(); + } + + let buttons: Vec = value + .roles + .iter() + .map(|role| CreateButton::from(role.clone())) + .collect(); + + let components = vec![CreateActionRow::Buttons(buttons)]; + Self::new().content(content).components(components) + } +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct WelcomeLayout { + embeds: Vec, + messages: Vec, + roles: Vec, +} + +/// Sets your welcome channel info +#[poise::command( + slash_command, + guild_only, + ephemeral, + default_member_permissions = "MANAGE_GUILD", + required_permissions = "MANAGE_GUILD" +)] +pub async fn set_welcome( + ctx: Context<'_>, + #[description = "A file to use"] file: Option, + #[description = "A URL for a file to use"] url: Option, +) -> Result<(), Error> { + trace!("Running set_welcome command!"); + + let configured_channels = ctx.data().config.discord.channels; + let Some(channel_id) = configured_channels.welcome_channel_id else { + ctx.say("You don't have a welcome channel ID set, so I can't do anything :(") + .await?; + return Ok(()); + }; + + ctx.defer_ephemeral().await?; + + // download attachment from discord or URL + let file = if let Some(attachment) = file { + let Some(content_type) = &attachment.content_type else { + return Err("Welcome channel attachment was sent without a content type!".into()); + }; + + if !content_type.starts_with("application/json;") { + trace!("Not attempting to read non-json content type {content_type}"); + ctx.say("Invalid file! Please only send json").await?; + return Ok(()); + } + + let downloaded = attachment.download().await?; + String::from_utf8(downloaded)? + } else if let Some(url) = url { + ctx.data() + .http_client + .get_request(&url) + .await? + .text() + .await? + } else { + ctx.say("A text file or URL must be provided!").await?; + return Ok(()); + }; + + // parse and create messages from file + let welcome_layout: WelcomeLayout = serde_json::from_str(&file)?; + let embed_messages: Vec = welcome_layout + .embeds + .iter() + .map(|e| CreateMessage::from(e.clone())) + .collect(); + let roles_messages: Vec = welcome_layout + .roles + .iter() + .map(|c| CreateMessage::from(c.clone())) + .collect(); + + // clear previous messages + let prev_messages: Vec = channel_id.messages_iter(ctx).try_collect().await?; + channel_id.delete_messages(ctx, prev_messages).await?; + + // send our new ones + for embed in embed_messages { + channel_id.send_message(ctx, embed).await?; + } + + for message in welcome_layout.messages { + channel_id.say(ctx, message).await?; + } + + for message in roles_messages { + channel_id.send_message(ctx, message).await?; + } + + if let Some(log_channel) = configured_channels.log_channel_id { + let author = utils::embed_author_from_user(ctx.author()); + let embed = CreateEmbed::new() + .title("set_welcome command used!") + .author(author); + let message = CreateMessage::new().embed(embed); + + log_channel.send_message(ctx, message).await?; + } else { + trace!("Not sending /set_welcome log as no channel is set"); + } + + ctx.reply(format!("Updated {}!", channel_id.mention())) + .await?; + + Ok(()) +} diff --git a/src/config/bot.rs b/src/config/bot.rs new file mode 100644 index 0000000..c34c5b0 --- /dev/null +++ b/src/config/bot.rs @@ -0,0 +1,24 @@ +use log::{info, warn}; + +#[derive(Clone, Debug, Default)] +pub struct Config { + pub redis_url: Option, +} + +impl Config { + pub fn new(redis_url: Option) -> Self { + Self { redis_url } + } + + pub fn from_env() -> Self { + let redis_url = std::env::var("BOT_REDIS_URL").ok(); + + if let Some(url) = &redis_url { + info!("Redis URL is {url}"); + } else { + warn!("BOT_REDIS_URL is empty; features requiring storage will be disabled."); + } + + Self::new(redis_url) + } +} diff --git a/src/config/discord.rs b/src/config/discord.rs new file mode 100644 index 0000000..27782b1 --- /dev/null +++ b/src/config/discord.rs @@ -0,0 +1,60 @@ +use std::str::FromStr; + +use log::{info, warn}; +use poise::serenity_prelude::ChannelId; + +#[derive(Clone, Copy, Debug, Default)] +pub struct RefractionChannels { + pub log_channel_id: Option, + pub welcome_channel_id: Option, +} + +#[derive(Clone, Debug, Default)] +pub struct Config { + pub channels: RefractionChannels, +} + +impl RefractionChannels { + pub fn new(log_channel_id: Option, welcome_channel_id: Option) -> Self { + Self { + log_channel_id, + welcome_channel_id, + } + } + + pub fn new_from_env() -> Self { + let log_channel_id = Self::get_channel_from_env("DISCORD_LOG_CHANNEL_ID"); + if let Some(channel_id) = log_channel_id { + info!("Log channel is {channel_id}"); + } else { + warn!("DISCORD_LOG_CHANNEL_ID is empty; this will disable logging in your server."); + } + + let welcome_channel_id = Self::get_channel_from_env("DISCORD_WELCOME_CHANNEL_ID"); + if let Some(channel_id) = welcome_channel_id { + info!("Welcome channel is {channel_id}"); + } else { + warn!("DISCORD_WELCOME_CHANNEL_ID is empty; this will disable welcome channel features in your server"); + } + + Self::new(log_channel_id, welcome_channel_id) + } + + fn get_channel_from_env(var: &str) -> Option { + std::env::var(var) + .ok() + .and_then(|env_var| ChannelId::from_str(&env_var).ok()) + } +} + +impl Config { + pub fn new(channels: RefractionChannels) -> Self { + Self { channels } + } + + pub fn from_env() -> Self { + let channels = RefractionChannels::new_from_env(); + + Self::new(channels) + } +} diff --git a/src/config/mod.rs b/src/config/mod.rs new file mode 100644 index 0000000..3507670 --- /dev/null +++ b/src/config/mod.rs @@ -0,0 +1,24 @@ +mod bot; +mod discord; + +#[derive(Debug, Clone, Default)] +pub struct Config { + pub bot: bot::Config, + pub discord: discord::Config, +} + +impl Config { + pub fn new(bot_config: bot::Config, discord_config: discord::Config) -> Self { + Self { + bot: bot_config, + discord: discord_config, + } + } + + pub fn new_from_env() -> Self { + let bot = bot::Config::from_env(); + let discord = discord::Config::from_env(); + + Self::new(bot, discord) + } +} diff --git a/src/consts.rs b/src/consts.rs new file mode 100644 index 0000000..3b3f6e4 --- /dev/null +++ b/src/consts.rs @@ -0,0 +1,46 @@ +#![allow(clippy::unreadable_literal)] +use std::str::FromStr; + +use poise::serenity_prelude::Colour; + +const BLUE: u32 = 0x60A5FA; +const GREEN: u32 = 0x22C55E; +const ORANGE: u32 = 0xFB923C; +const RED: u32 = 0xEF4444; +const YELLOW: u32 = 0xFDE047; + +#[derive(Clone, Copy, Debug, Default)] +pub enum Colors { + Blue, + #[default] + Green, + Orange, + Red, + Yellow, +} + +impl From for Colour { + fn from(value: Colors) -> Self { + Self::from(match &value { + Colors::Blue => BLUE, + Colors::Green => GREEN, + Colors::Orange => ORANGE, + Colors::Red => RED, + Colors::Yellow => YELLOW, + }) + } +} + +impl FromStr for Colors { + type Err = (); + fn from_str(s: &str) -> Result { + match s.to_lowercase().as_str() { + "blue" => Ok(Self::Blue), + "green" => Ok(Self::Green), + "orange" => Ok(Self::Orange), + "red" => Ok(Self::Red), + "yellow" => Ok(Self::Yellow), + _ => Err(()), + } + } +} diff --git a/src/handlers/error.rs b/src/handlers/error.rs new file mode 100644 index 0000000..58d7a86 --- /dev/null +++ b/src/handlers/error.rs @@ -0,0 +1,98 @@ +use crate::{consts::Colors, Data, Error}; + +use std::fmt::Write; + +use log::error; +use poise::serenity_prelude::{CreateEmbed, Timestamp}; +use poise::{CreateReply, FrameworkError}; + +// getchoo: i like writeln! and don't like +macro_rules! writelne { + ($dst:expr, $($arg:tt)*) => { + if let Err(why) = writeln!($dst, $($arg)*) { + error!("We somehow cannot write to what should be on the heap. What are you using this macro with? Anyways, here's the error:\n{why:#?}"); + } + } +} + +pub async fn handle(error: FrameworkError<'_, Data, Error>) { + match error { + FrameworkError::Setup { + error, framework, .. + } => { + error!("Error setting up client! Bailing out"); + framework.shard_manager().shutdown_all().await; + + panic!("{error}") + } + + FrameworkError::Command { error, ctx, .. } => { + error!("Error in command {}:\n{error:?}", ctx.command().name); + + let embed = CreateEmbed::new() + .title("Something went wrong!") + .description("oopsie") + .timestamp(Timestamp::now()) + .color(Colors::Red); + + let reply = CreateReply::default().embed(embed); + + ctx.send(reply).await.ok(); + } + + FrameworkError::EventHandler { + error, + ctx: _, + event, + framework: _, + .. + } => { + error!( + "Error while handling event {}:\n{error:?}", + event.snake_case_name() + ); + } + + FrameworkError::ArgumentParse { + error, input, ctx, .. + } => { + let mut response = String::new(); + + if let Some(input) = input { + writelne!( + &mut response, + "**Cannot parse `{input}` as argument: {error}**\n" + ); + } else { + writelne!(&mut response, "**{error}**\n"); + } + + if let Some(help_text) = ctx.command().help_text.as_ref() { + writelne!(&mut response, "{help_text}\n"); + } + + if ctx.command().invoke_on_edit { + writelne!( + &mut response, + "**Tip:** Edit your message to update the response." + ); + } + + writelne!( + &mut response, + "For more information, refer to /help {}.", + ctx.command().name + ); + + if let Err(why) = ctx.say(response).await { + error!("Unhandled error displaying ArgumentParse error\n{why:#?}"); + } + } + + error => { + if let Err(e) = poise::builtins::on_error(error).await { + error!("Unhandled error occurred:\n{e:#?}"); + } + } + } +} diff --git a/src/handlers/event/analyze_logs/issues.rs b/src/handlers/event/analyze_logs/issues.rs new file mode 100644 index 0000000..9cbf598 --- /dev/null +++ b/src/handlers/event/analyze_logs/issues.rs @@ -0,0 +1,472 @@ +use crate::{api, utils::semver_split, Data}; + +use std::sync::OnceLock; + +use eyre::Result; +use log::trace; +use regex::Regex; + +pub type Issue = Option<(String, String)>; + +pub async fn find(log: &str, data: &Data) -> Result> { + trace!("Checking log for issues"); + + let issues = [ + fabric_internal, + flatpak_nvidia, + forge_java, + intel_hd, + java_option, + lwjgl_2_java_9, + macos_ns, + oom, + optinotfine, + pre_1_12_native_transport_java_9, + wrong_java, + forge_missing_dependencies, + legacyjavafixer, + locked_jar, + offline_launch, + frapi, + no_disk_space, + java_32_bit, + intermediary_mappings, + old_forge_new_java, + checksum_mismatch, + nvidia_linux, + linux_openal, + flatpak_crash, + spark_macos, + ]; + + let mut res: Vec<(String, String)> = issues.iter().filter_map(|issue| issue(log)).collect(); + + if let Some(issues) = outdated_launcher(log, data).await? { + res.push(issues); + } + + Ok(res) +} + +fn fabric_internal(log: &str) -> Issue { + const CLASS_NOT_FOUND: &str = "Caused by: java.lang.ClassNotFoundException: "; + + let issue = ( + "Fabric Internal Access".to_string(), + "The mod you are using is using fabric internals that are not meant \ + to be used by anything but the loader itself. + Those mods break both on Quilt and with fabric updates. + If you're using fabric, downgrade your fabric loader could work, \ + on Quilt you can try updating to the latest beta version, \ + but there's nothing much to do unless the mod author stops using them." + .to_string(), + ); + + let errors = [ + &format!("{CLASS_NOT_FOUND}net.fabricmc.fabric.impl"), + &format!("{CLASS_NOT_FOUND}net.fabricmc.fabric.mixin"), + &format!("{CLASS_NOT_FOUND}net.fabricmc.fabric.loader.impl"), + &format!("{CLASS_NOT_FOUND}net.fabricmc.fabric.loader.mixin"), + "org.quiltmc.loader.impl.FormattedException: java.lang.NoSuchMethodError:", + ]; + + let found = errors.iter().any(|e| log.contains(e)); + found.then_some(issue) +} + +fn flatpak_nvidia(log: &str) -> Issue { + let issue = ( + "Outdated Nvidia Flatpak Driver".to_string(), + "The Nvidia driver for flatpak is outdated. + Please run `flatpak update` to fix this issue. \ + If that does not solve it, \ + please wait until the driver is added to Flathub and run it again." + .to_string(), + ); + + let found = log.contains("org.lwjgl.LWJGLException: Could not choose GLX13 config") + || log.contains("GLX: Failed to find a suitable GLXFBConfig"); + + found.then_some(issue) +} + +fn forge_java(log: &str) -> Issue { + let issue = ( + "Forge Java Bug".to_string(), + "Old versions of Forge crash with Java 8u321+. + To fix this, update forge to the latest version via the Versions tab + (right click on Forge, click Change Version, and choose the latest one) + Alternatively, you can download 8u312 or lower. \ + See [archive](https://github.com/adoptium/temurin8-binaries/releases/tag/jdk8u312-b07)" + .to_string(), + ); + + let found = log.contains("java.lang.NoSuchMethodError: sun.security.util.ManifestEntryVerifier.(Ljava/util/jar/Manifest;)V"); + found.then_some(issue) +} + +fn intel_hd(log: &str) -> Issue { + let issue = + ( + "Intel HD Windows 10".to_string(), + "Your drivers don't support Windows 10 officially + See https://prismlauncher.org/wiki/getting-started/installing-java/#a-note-about-intel-hd-20003000-on-windows-10 for more info".to_string() + ); + + let found = log.contains("org.lwjgl.LWJGLException: Pixel format not accelerated") + && !log.contains("1.8.0_51"); + found.then_some(issue) +} + +fn java_option(log: &str) -> Issue { + static VM_OPTION_REGEX: OnceLock = OnceLock::new(); + static UNRECOGNIZED_OPTION_REGEX: OnceLock = OnceLock::new(); + + let vm_option = + VM_OPTION_REGEX.get_or_init(|| Regex::new(r"Unrecognized VM option '(.+)'[\r\n]").unwrap()); + let unrecognized_option = UNRECOGNIZED_OPTION_REGEX + .get_or_init(|| Regex::new(r"Unrecognized option: (.+)[\r\n]").unwrap()); + + if let Some(captures) = vm_option.captures(log) { + let title = if &captures[1] == "UseShenandoahGC" { + "Java 8 and below don't support ShenandoahGC" + } else { + "Wrong Java Arguments" + }; + return Some(( + title.to_string(), + format!("Remove `-XX:{}` from your Java arguments", &captures[1]), + )); + } + + if let Some(captures) = unrecognized_option.captures(log) { + return Some(( + "Wrong Java Arguments".to_string(), + format!("Remove `{}` from your Java arguments", &captures[1]), + )); + } + + None +} + +fn lwjgl_2_java_9(log: &str) -> Issue { + let issue = ( + "Linux: crash with pre-1.13 and Java 9+".to_string(), + "Using pre-1.13 (which uses LWJGL 2) with Java 9 or later usually causes a crash. \ + Switching to Java 8 or below will fix your issue. + Alternatively, you can use [Temurin](https://adoptium.net/temurin/releases). \ + However, multiplayer will not work in versions from 1.8 to 1.11. + For more information, type `/tag java`." + .to_string(), + ); + + let found = log.contains("check_match: Assertion `version->filename == NULL || ! _dl_name_match_p (version->filename, map)' failed!"); + found.then_some(issue) +} + +fn macos_ns(log: &str) -> Issue { + let issue = ( + "MacOS NSInternalInconsistencyException".to_string(), + "You need to downgrade your Java 8 version. See https://prismlauncher.org/wiki/getting-started/installing-java/#older-minecraft-on-macos".to_string() +); + + let found = + log.contains("Terminating app due to uncaught exception 'NSInternalInconsistencyException"); + found.then_some(issue) +} + +fn oom(log: &str) -> Issue { + let issue = ( + "Out of Memory".to_string(), + "Allocating more RAM to your instance could help prevent this crash.".to_string(), + ); + + let found = log.contains("java.lang.OutOfMemoryError"); + found.then_some(issue) +} + +fn optinotfine(log: &str) -> Issue { + let issue = ( + "Potential OptiFine Incompatibilities".to_string(), + "OptiFine is known to cause problems when paired with other mods. \ + Try to disable OptiFine and see if the issue persists. + Check `/tag optifine` for more info & some typically more compatible alternatives you can use." + .to_string(), + ); + + let found = log.contains("[✔] OptiFine_") || log.contains("[✔] optifabric-"); + found.then_some(issue) +} + +async fn outdated_launcher(log: &str, data: &Data) -> Result { + static OUTDATED_LAUNCHER_REGEX: OnceLock = OnceLock::new(); + let outdated_launcher = OUTDATED_LAUNCHER_REGEX.get_or_init(|| { + Regex::new("Prism Launcher version: ((?:([0-9]+)\\.)?([0-9]+)\\.([0-9]+))").unwrap() + }); + + let Some(captures) = outdated_launcher.captures(log) else { + return Ok(None); + }; + + let octocrab = &data.octocrab; + let log_version = &captures[1]; + let log_version_parts = semver_split(log_version); + + let latest_version = if let Some(storage) = &data.storage { + if let Ok(version) = storage.launcher_version().await { + version + } else { + let version = api::github::get_latest_prism_version(octocrab).await?; + storage.cache_launcher_version(&version).await?; + version + } + } else { + trace!("Not caching launcher version, as we're running without a storage backend"); + api::github::get_latest_prism_version(octocrab).await? + }; + let latest_version_parts = semver_split(&latest_version); + + if log_version_parts.len() != 2 + || log_version_parts[0] < latest_version_parts[0] + || (log_version_parts[0] == latest_version_parts[0] + && log_version_parts[1] < latest_version_parts[1]) + { + let issue = if log_version_parts[0] < 8 { + ( + "Outdated Prism Launcher".to_string(), + format!("Your installed version is {log_version}, while the newest version is {latest_version}.\nPlease update; for more info see https://prismlauncher.org/download/") + ) + } else { + ( + "Outdated Prism Launcher".to_string(), + format!("Your installed version is {log_version}, while the newest version is {latest_version}.\nPlease update by pressing the `Update` button in the launcher or using your package manager.") + ) + }; + + Ok(Some(issue)) + } else { + Ok(None) + } +} + +fn pre_1_12_native_transport_java_9(log: &str) -> Issue { + let issue = ( + "Linux: broken multiplayer with 1.8-1.11 and Java 9+".to_string(), + "These versions of Minecraft use an outdated version of Netty which does not properly support Java 9. + +Switching to Java 8 or below will fix this issue. For more information, type `/tag java`. + +If you must use a newer version, do the following: +- Open `options.txt` (in the main window Edit -> Open .minecraft) and change. +- Find `useNativeTransport:true` and change it to `useNativeTransport:false`. +Note: whilst Netty was introduced in 1.7, this option did not exist \ +which is why the issue was not present." + .to_string(), + ); + + let found = log.contains( + "java.lang.RuntimeException: Unable to access address of buffer\n\tat io.netty.channel.epoll" + ); + + found.then_some(issue) +} + +fn wrong_java(log: &str) -> Issue { + static SWITCH_VERSION_REGEX: OnceLock = OnceLock::new(); + let switch_version = SWITCH_VERSION_REGEX.get_or_init(|| Regex::new( + r"(?m)Please switch to one of the following Java versions for this instance:[\r\n]+(Java version [\d.]+)", +).unwrap()); + + if let Some(captures) = switch_version.captures(log) { + let versions = captures[1].split('\n').collect::>().join(", "); + return Some(( + "Wrong Java Version".to_string(), + format!("Please switch to one of the following: `{versions}`\nFor more information, type `/tag java`"), + )); + } + + let issue = ( + "Java compatibility check skipped".to_string(), + "The Java major version may not work with your Minecraft instance. Please switch to a compatible version.".to_string() + ); + + log.contains("Java major version is incompatible. Things might break.") + .then_some(issue) +} + +fn forge_missing_dependencies(log: &str) -> Issue { + let issue = ( + "Missing mod dependencies".to_string(), + "You seem to be missing mod dependencies. + Search for \"mandatory dependencies\" in your log." + .to_string(), + ); + + let found = log.contains("Missing or unsupported mandatory dependencies"); + found.then_some(issue) +} + +fn legacyjavafixer(log: &str) -> Issue { + let issue = ( + "LegacyJavaFixer".to_string(), + "You are using a modern Java version with an old Forge version, which is causing this crash. + MinecraftForge provides a coremod to fix this issue, download it [here](https://dist.creeper.host/FTB2/maven/net/minecraftforge/lex/legacyjavafixer/1.0/legacyjavafixer-1.0.jar)." + .to_string(), + ); + + let found = log.contains( + "[SEVERE] [ForgeModLoader] Unable to launch\njava.util.ConcurrentModificationException", + ); + found.then_some(issue) +} + +fn locked_jar(log: &str) -> Issue { + let issue = ( + "Locked Jars".to_string(), + "Something is locking your library jars. + To fix this, try rebooting your PC." + .to_string(), + ); + + let found = log.contains("Couldn't extract native jar"); + found.then_some(issue) +} + +fn offline_launch(log: &str) -> Issue { + let issue = ( + "Missing Libraries".to_string(), + "You seem to be missing libraries. This is usually caused by launching offline before they can be downloaded. + To fix this, first ensure you are connected to the internet. Then, try selecting Edit > Version > Download All and launching your instance again. + If Minecraft is getting launched offline by default, it's possible your token got expired. To fix this, remove and add back your Microsoft account." + .to_string(), + ); + + let found = log.contains("(missing)\n"); + found.then_some(issue) +} + +fn frapi(log: &str) -> Issue { + let issue = ( + "Missing Indium".to_string(), + "You are using a mod that needs Indium. + Please install it by going to Edit > Mods > Download Mods." + .to_string(), + ); + + let found = log + .contains("Cannot invoke \"net.fabricmc.fabric.api.renderer.v1.Renderer.meshBuilder()\""); + found.then_some(issue) +} + +fn no_disk_space(log: &str) -> Issue { + let issue = ( + "Out of disk space".to_string(), + "You ran out of disk space. You should free up some space on it.".to_string(), + ); + + let found = log.contains("There is not enough space on the disk"); + found.then_some(issue) +} + +fn java_32_bit(log: &str) -> Issue { + let issue = ( + "32 bit Java crash".to_string(), + "You are using a 32 bit Java version. Please select 64 bit Java instead. + Check `/tag java` for more information." + .to_string(), + ); + + let found = log.contains("Could not reserve enough space for ") + || log.contains("Invalid maximum heap size: ") + || log.contains("Invalid initial heap size: "); + found.then_some(issue) +} + +fn intermediary_mappings(log: &str) -> Issue { + let issue = ( + "Wrong Intermediary Mappings version".to_string(), + "You are using Intermediary Mappings for the wrong Minecraft version. + Please select Change Version while it is selected in Edit > Version." + .to_string(), + ); + + let found = log.contains("Mapping source name conflicts detected:"); + found.then_some(issue) +} + +fn old_forge_new_java(log: &str) -> Issue { + let issue = ( + "Forge on old Minecraft versions".to_string(), + "This crash is caused by using an old Forge version with a modern Java version. + To fix it, add the flag `-Dfml.ignoreInvalidMinecraftCertificates=true` to Edit > Settings > Java arguments." + .to_string(), + ); + + let found = log.contains( + "add the flag -Dfml.ignoreInvalidMinecraftCertificates=true to the 'JVM settings'", + ); + found.then_some(issue) +} + +fn checksum_mismatch(log: &str) -> Issue { + let issue = ( + "Outdated cached files".to_string(), + "It looks like you need to delete cached files. + To do that, press Folders ⟶ View Launcher Root Folder, and **after closing the launcher** delete the folder named \"meta\"." + .to_string(), + ); + + let found = log.contains("Checksum mismatch, download is bad."); + found.then_some(issue) +} + +fn nvidia_linux(log: &str) -> Issue { + let issue = ( + "Nvidia drivers on Linux".to_string(), + "Nvidia drivers will often cause crashes on Linux. + To fix it, go to Settings ⟶ Enviroment variables and set `__GL_THREADED_OPTIMIZATIONS` to `0`." + .to_string(), + ); + + let found = log.contains("# C [libnvidia-glcore.so"); + found.then_some(issue) +} + +fn linux_openal(log: &str) -> Issue { + let issue = ( + "Missing .alsoftrc".to_string(), + "OpenAL is likely missing the configuration file. + To fix this, create a file named `.alsoftrc` in your home directory with the following content: + ``` +drivers=alsa +hrtf=true```" + .to_string(), + ); + + let found = log.contains("# C [libopenal.so"); + found.then_some(issue) +} + +fn flatpak_crash(log: &str) -> Issue { + let issue = ( + "Flatpak crash".to_string(), + "To fix this crash, disable \"Fallback to X11 Windowing System\" in Flatseal.".to_string(), + ); + + let found = log.contains( + "Can't connect to X11 window server using ':0.0' as the value of the DISPLAY variable", + ) || log.contains("Could not open X display connection"); + found.then_some(issue) +} + +fn spark_macos(log: &str) -> Issue { + let issue = ( + "Old Java on MacOS".to_string(), + "This crash is caused by an old Java version conflicting with mods, most often Spark, on MacOS. + To fix it, either remove Spark or update Java by going to Edit > Settings > Download Java > Adoptium, and selecting the new Java version via Auto-Detect." + .to_string(), + ); + + let found = log.contains("~StubRoutines::SafeFetch32"); + found.then_some(issue) +} diff --git a/src/handlers/event/analyze_logs/mod.rs b/src/handlers/event/analyze_logs/mod.rs new file mode 100644 index 0000000..df89913 --- /dev/null +++ b/src/handlers/event/analyze_logs/mod.rs @@ -0,0 +1,75 @@ +use crate::{consts::Colors, Data}; + +use eyre::Result; +use log::{debug, trace}; +use poise::serenity_prelude::{ + Context, CreateAllowedMentions, CreateEmbed, CreateMessage, Message, +}; + +mod issues; +mod providers; + +use providers::find_log; + +pub async fn handle(ctx: &Context, message: &Message, data: &Data) -> Result<()> { + trace!( + "Checking message {} from {} for logs", + message.id, + message.author.id + ); + let channel = message.channel_id; + + let log = find_log(&data.http_client, message).await; + + if log.is_err() { + let embed = CreateEmbed::new() + .title("Analysis failed!") + .description("Couldn't download log"); + let allowed_mentions = CreateAllowedMentions::new().replied_user(true); + let our_message = CreateMessage::new() + .reference_message(message) + .allowed_mentions(allowed_mentions) + .embed(embed); + + channel.send_message(ctx, our_message).await?; + + return Ok(()); + } + + let Some(log) = log? else { + debug!("No log found in message! Skipping analysis"); + return Ok(()); + }; + + let log = log.replace("\r\n", "\n"); + + let issues = issues::find(&log, data).await?; + + let embed = { + let mut e = CreateEmbed::new().title("Log analysis"); + + if issues.is_empty() { + e = e + .color(Colors::Green) + .description("The automatic check didn't reveal any issues, but it's possible that some issues went undetected. Please wait for a volunteer to assist you."); + } else { + e = e.color(Colors::Red); + + for (title, description) in issues { + e = e.field(title, description, false); + } + } + + e + }; + + let allowed_mentions = CreateAllowedMentions::new().replied_user(true); + let message = CreateMessage::new() + .reference_message(message) + .allowed_mentions(allowed_mentions) + .embed(embed); + + channel.send_message(ctx, message).await?; + + Ok(()) +} diff --git a/src/handlers/event/analyze_logs/providers/0x0.rs b/src/handlers/event/analyze_logs/providers/0x0.rs new file mode 100644 index 0000000..300ae0e --- /dev/null +++ b/src/handlers/event/analyze_logs/providers/0x0.rs @@ -0,0 +1,29 @@ +use crate::api::{HttpClient, HttpClientExt}; + +use std::sync::OnceLock; + +use eyre::Result; +use log::trace; +use poise::serenity_prelude::Message; +use regex::Regex; + +pub struct _0x0; + +impl super::LogProvider for _0x0 { + async fn find_match(&self, message: &Message) -> Option { + static REGEX: OnceLock = OnceLock::new(); + let regex = REGEX.get_or_init(|| Regex::new(r"https://0x0\.st/\w*.\w*").unwrap()); + + trace!("Checking if message {} is a 0x0 paste", message.id); + regex + .find_iter(&message.content) + .map(|m| m.as_str().to_string()) + .nth(0) + } + + async fn fetch(&self, http: &HttpClient, content: &str) -> Result { + let log = http.get_request(content).await?.text().await?; + + Ok(log) + } +} diff --git a/src/handlers/event/analyze_logs/providers/attachment.rs b/src/handlers/event/analyze_logs/providers/attachment.rs new file mode 100644 index 0000000..4e09c67 --- /dev/null +++ b/src/handlers/event/analyze_logs/providers/attachment.rs @@ -0,0 +1,30 @@ +use crate::api::{HttpClient, HttpClientExt}; + +use eyre::Result; +use log::trace; +use poise::serenity_prelude::Message; + +pub struct Attachment; + +impl super::LogProvider for Attachment { + async fn find_match(&self, message: &Message) -> Option { + trace!("Checking if message {} has text attachments", message.id); + + message + .attachments + .iter() + .filter_map(|a| { + a.content_type + .as_ref() + .and_then(|ct| ct.starts_with("text/").then_some(a.url.clone())) + }) + .nth(0) + } + + async fn fetch(&self, http: &HttpClient, content: &str) -> Result { + let attachment = http.get_request(content).await?.bytes().await?.to_vec(); + let log = String::from_utf8(attachment)?; + + Ok(log) + } +} diff --git a/src/handlers/event/analyze_logs/providers/haste.rs b/src/handlers/event/analyze_logs/providers/haste.rs new file mode 100644 index 0000000..3ad1c18 --- /dev/null +++ b/src/handlers/event/analyze_logs/providers/haste.rs @@ -0,0 +1,31 @@ +use crate::api::{HttpClient, HttpClientExt}; + +use std::sync::OnceLock; + +use eyre::Result; +use log::trace; +use poise::serenity_prelude::Message; +use regex::Regex; + +const HASTE: &str = "https://hst.sh"; +const RAW: &str = "/raw"; + +pub struct Haste; + +impl super::LogProvider for Haste { + async fn find_match(&self, message: &Message) -> Option { + static REGEX: OnceLock = OnceLock::new(); + let regex = + REGEX.get_or_init(|| Regex::new(r"https://hst\.sh(?:/raw)?/(\w+(?:\.\w*)?)").unwrap()); + + trace!("Checking if message {} is a hst.sh paste", message.id); + super::get_first_capture(regex, &message.content) + } + + async fn fetch(&self, http: &HttpClient, content: &str) -> Result { + let url = format!("{HASTE}{RAW}/{content}"); + let log = http.get_request(&url).await?.text().await?; + + Ok(log) + } +} diff --git a/src/handlers/event/analyze_logs/providers/mclogs.rs b/src/handlers/event/analyze_logs/providers/mclogs.rs new file mode 100644 index 0000000..e89009a --- /dev/null +++ b/src/handlers/event/analyze_logs/providers/mclogs.rs @@ -0,0 +1,30 @@ +use crate::api::{HttpClient, HttpClientExt}; + +use std::sync::OnceLock; + +use eyre::Result; +use log::trace; +use poise::serenity_prelude::Message; +use regex::Regex; + +const MCLOGS: &str = "https://api.mclo.gs/1"; +const RAW: &str = "/raw"; + +pub struct MCLogs; + +impl super::LogProvider for MCLogs { + async fn find_match(&self, message: &Message) -> Option { + static REGEX: OnceLock = OnceLock::new(); + let regex = REGEX.get_or_init(|| Regex::new(r"https://mclo\.gs/(\w+)").unwrap()); + + trace!("Checking if message {} is an mclo.gs paste", message.id); + super::get_first_capture(regex, &message.content) + } + + async fn fetch(&self, http: &HttpClient, content: &str) -> Result { + let url = format!("{MCLOGS}{RAW}/{content}"); + let log = http.get_request(&url).await?.text().await?; + + Ok(log) + } +} diff --git a/src/handlers/event/analyze_logs/providers/mod.rs b/src/handlers/event/analyze_logs/providers/mod.rs new file mode 100644 index 0000000..bb9aa4e --- /dev/null +++ b/src/handlers/event/analyze_logs/providers/mod.rs @@ -0,0 +1,70 @@ +use crate::api::HttpClient; + +use std::slice::Iter; + +use enum_dispatch::enum_dispatch; +use eyre::Result; +use poise::serenity_prelude::Message; +use regex::Regex; + +use self::{ + _0x0::_0x0 as _0x0st, attachment::Attachment, haste::Haste, mclogs::MCLogs, paste_gg::PasteGG, + pastebin::PasteBin, +}; + +#[path = "0x0.rs"] +mod _0x0; +mod attachment; +mod haste; +mod mclogs; +mod paste_gg; +mod pastebin; + +#[enum_dispatch] +pub trait LogProvider { + async fn find_match(&self, message: &Message) -> Option; + async fn fetch(&self, http: &HttpClient, content: &str) -> Result; +} + +fn get_first_capture(regex: &Regex, string: &str) -> Option { + regex + .captures_iter(string) + .find_map(|c| c.get(1).map(|c| c.as_str().to_string())) +} + +#[enum_dispatch(LogProvider)] +enum Provider { + _0x0st, + Attachment, + Haste, + MCLogs, + PasteGG, + PasteBin, +} + +impl Provider { + pub fn iterator() -> Iter<'static, Provider> { + static PROVIDERS: [Provider; 6] = [ + Provider::_0x0st(_0x0st), + Provider::Attachment(Attachment), + Provider::Haste(Haste), + Provider::MCLogs(MCLogs), + Provider::PasteBin(PasteBin), + Provider::PasteGG(PasteGG), + ]; + PROVIDERS.iter() + } +} + +pub async fn find_log(http: &HttpClient, message: &Message) -> Result> { + let providers = Provider::iterator(); + + for provider in providers { + if let Some(found) = provider.find_match(message).await { + let log = provider.fetch(http, &found).await?; + return Ok(Some(log)); + } + } + + Ok(None) +} diff --git a/src/handlers/event/analyze_logs/providers/paste_gg.rs b/src/handlers/event/analyze_logs/providers/paste_gg.rs new file mode 100644 index 0000000..8e69514 --- /dev/null +++ b/src/handlers/event/analyze_logs/providers/paste_gg.rs @@ -0,0 +1,37 @@ +use crate::api::{paste_gg, HttpClient}; + +use std::sync::OnceLock; + +use eyre::{OptionExt, Result}; +use log::trace; +use poise::serenity_prelude::Message; +use regex::Regex; + +pub struct PasteGG; + +impl super::LogProvider for PasteGG { + async fn find_match(&self, message: &Message) -> Option { + static REGEX: OnceLock = OnceLock::new(); + let regex = REGEX.get_or_init(|| Regex::new(r"https://paste.gg/p/\w+/(\w+)").unwrap()); + + trace!("Checking if message {} is a paste.gg paste", message.id); + super::get_first_capture(regex, &message.content) + } + + async fn fetch(&self, http: &HttpClient, content: &str) -> Result { + let files = paste_gg::files_from(http, content).await?; + let result = files + .result + .ok_or_eyre("Got an empty result from paste.gg!")?; + + let file_id = result + .iter() + .map(|f| f.id.as_str()) + .nth(0) + .ok_or_eyre("Couldn't get file id from empty paste.gg response!")?; + + let log = paste_gg::get_raw_file(http, content, file_id).await?; + + Ok(log) + } +} diff --git a/src/handlers/event/analyze_logs/providers/pastebin.rs b/src/handlers/event/analyze_logs/providers/pastebin.rs new file mode 100644 index 0000000..4207706 --- /dev/null +++ b/src/handlers/event/analyze_logs/providers/pastebin.rs @@ -0,0 +1,31 @@ +use crate::api::{HttpClient, HttpClientExt}; + +use std::sync::OnceLock; + +use eyre::Result; +use log::trace; +use poise::serenity_prelude::Message; +use regex::Regex; + +const PASTEBIN: &str = "https://pastebin.com"; +const RAW: &str = "/raw"; + +pub struct PasteBin; + +impl super::LogProvider for PasteBin { + async fn find_match(&self, message: &Message) -> Option { + static REGEX: OnceLock = OnceLock::new(); + let regex = + REGEX.get_or_init(|| Regex::new(r"https://pastebin\.com(?:/raw)?/(\w+)").unwrap()); + + trace!("Checking if message {} is a pastebin paste", message.id); + super::get_first_capture(regex, &message.content) + } + + async fn fetch(&self, http: &HttpClient, content: &str) -> Result { + let url = format!("{PASTEBIN}{RAW}/{content}"); + let log = http.get_request(&url).await?.text().await?; + + Ok(log) + } +} diff --git a/src/handlers/event/delete_on_reaction.rs b/src/handlers/event/delete_on_reaction.rs new file mode 100644 index 0000000..59a9eef --- /dev/null +++ b/src/handlers/event/delete_on_reaction.rs @@ -0,0 +1,26 @@ +use eyre::{Context as _, Result}; +use log::trace; +use poise::serenity_prelude::{Context, MessageInteractionMetadata, Reaction}; + +pub async fn handle(ctx: &Context, reaction: &Reaction) -> Result<()> { + let user = reaction + .user(ctx) + .await + .wrap_err("Couldn't fetch user from reaction!")?; + + let message = reaction + .message(ctx) + .await + .wrap_err("Couldn't fetch message from reaction!")?; + + if let Some(MessageInteractionMetadata::Command(metadata)) = + message.interaction_metadata.as_deref() + { + if metadata.user == user && reaction.emoji.unicode_eq("❌") { + trace!("Deleting our own message at the request of {}", user.tag()); + message.delete(ctx).await?; + } + } + + Ok(()) +} diff --git a/src/handlers/event/eta.rs b/src/handlers/event/eta.rs new file mode 100644 index 0000000..6db523e --- /dev/null +++ b/src/handlers/event/eta.rs @@ -0,0 +1,51 @@ +use std::{sync::OnceLock, time::SystemTime}; + +use eyre::Result; +use log::trace; +use poise::serenity_prelude::{Context, Message}; +use regex::Regex; + +fn regex() -> &'static Regex { + static REGEX: OnceLock = OnceLock::new(); + REGEX.get_or_init(|| Regex::new(r"(?i)\beta\b").unwrap()) +} + +const MESSAGES: [&str; 16] = [ + "Sometime", + "Some day", + "Not far", + "The future", + "Never", + "Perhaps tomorrow?", + "There are no ETAs", + "No", + "Nah", + "Yes", + "Yas", + "Next month", + "Next year", + "Next week", + "In Prism Launcher 2.0.0", + "At the appropriate juncture, in due course, in the fullness of time", +]; + +pub async fn handle(ctx: &Context, message: &Message) -> Result<()> { + if !regex().is_match(&message.content) { + trace!( + "The message '{}' (probably) doesn't say ETA", + message.content + ); + return Ok(()); + } + + // no, this isn't actually random. we don't need it to be, though -getchoo + let current_time = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH)? + .as_millis(); + let random_pos = (current_time % MESSAGES.len() as u128) as usize; + + let response = format!("{} <:pofat:1031701005559144458>", MESSAGES[random_pos]); + message.reply(ctx, response).await?; + + Ok(()) +} diff --git a/src/handlers/event/expand_link.rs b/src/handlers/event/expand_link.rs new file mode 100644 index 0000000..b336616 --- /dev/null +++ b/src/handlers/event/expand_link.rs @@ -0,0 +1,20 @@ +use crate::{api::HttpClient, utils}; + +use eyre::Result; +use poise::serenity_prelude::{Context, CreateAllowedMentions, CreateMessage, Message}; + +pub async fn handle(ctx: &Context, http: &HttpClient, message: &Message) -> Result<()> { + let embeds = utils::messages::from_message(ctx, http, message).await?; + + if !embeds.is_empty() { + let allowed_mentions = CreateAllowedMentions::new().replied_user(false); + let reply = CreateMessage::new() + .reference_message(message) + .embeds(embeds) + .allowed_mentions(allowed_mentions); + + message.channel_id.send_message(ctx, reply).await?; + } + + Ok(()) +} diff --git a/src/handlers/event/give_role.rs b/src/handlers/event/give_role.rs new file mode 100644 index 0000000..a063399 --- /dev/null +++ b/src/handlers/event/give_role.rs @@ -0,0 +1,45 @@ +use std::str::FromStr; + +use eyre::Result; +use log::debug; +use poise::serenity_prelude::{ + ComponentInteraction, Context, CreateEmbed, CreateInteractionResponseFollowup, RoleId, +}; + +pub async fn handle(ctx: &Context, component_interaction: &ComponentInteraction) -> Result<()> { + let Some(guild_id) = component_interaction.guild_id else { + debug!("Ignoring component interaction not from guild!"); + return Ok(()); + }; + + let Ok(role_id) = RoleId::from_str(&component_interaction.data.custom_id) else { + debug!("Ignoring component interaction that doesn't contain a role as it's ID"); + return Ok(()); + }; + + component_interaction.defer_ephemeral(ctx).await?; + + let mut followup = CreateInteractionResponseFollowup::new().ephemeral(true); + if let Some(role) = guild_id.roles(ctx).await?.get(&role_id) { + let guild_member = guild_id.member(ctx, component_interaction.user.id).await?; + + let mut embed = CreateEmbed::new(); + if guild_member.roles.contains(&role_id) { + guild_member.remove_role(ctx, role_id).await?; + embed = embed.description(format!("❌ Removed `{}`", role.name)); + } else { + guild_member.add_role(ctx, role_id).await?; + embed = embed.description(format!("✅ Added `{}`", role.name)); + } + + followup = followup.add_embed(embed); + } else { + followup = followup.content(format!( + "Role ID {role_id} doesn't seem to exist. Please let the moderators know!" + )); + } + + component_interaction.create_followup(ctx, followup).await?; + + Ok(()) +} diff --git a/src/handlers/event/mod.rs b/src/handlers/event/mod.rs new file mode 100644 index 0000000..efaca47 --- /dev/null +++ b/src/handlers/event/mod.rs @@ -0,0 +1,88 @@ +use crate::{api, Data, Error}; + +use log::{debug, info, trace}; +use poise::serenity_prelude::{ActivityData, Context, FullEvent, OnlineStatus}; +use poise::FrameworkContext; + +mod analyze_logs; +mod delete_on_reaction; +mod eta; +mod expand_link; +mod give_role; +mod pluralkit; +mod support_onboard; + +pub async fn handle( + ctx: &Context, + event: &FullEvent, + _: FrameworkContext<'_, Data, Error>, + data: &Data, +) -> Result<(), Error> { + match event { + FullEvent::Ready { data_about_bot } => { + info!("Logged in as {}!", data_about_bot.user.name); + + let latest_minecraft_version = + api::prism_meta::latest_minecraft_version(&data.http_client).await?; + let activity = ActivityData::playing(format!("Minecraft {latest_minecraft_version}")); + + info!("Setting presence to activity {activity:#?}"); + ctx.set_presence(Some(activity), OnlineStatus::Online); + } + + FullEvent::InteractionCreate { interaction } => { + if let Some(component_interaction) = interaction.as_message_component() { + give_role::handle(ctx, component_interaction).await?; + } + } + + FullEvent::Message { new_message } => { + trace!("Received message {}", new_message.content); + + // ignore new messages from bots + // note: the webhook_id check allows us to still respond to PK users + if (new_message.author.bot && new_message.webhook_id.is_none()) + || (new_message.author == **ctx.cache.current_user()) + { + trace!("Ignoring message {} from bot", new_message.id); + return Ok(()); + } + + if let Some(storage) = &data.storage { + let http = &data.http_client; + // detect PK users first to make sure we don't respond to unproxied messages + pluralkit::handle(ctx, http, storage, new_message).await?; + + if storage.is_user_plural(new_message.author.id).await? + && pluralkit::is_message_proxied(http, new_message).await? + { + debug!("Not replying to unproxied PluralKit message"); + return Ok(()); + } + } + + eta::handle(ctx, new_message).await?; + expand_link::handle(ctx, &data.http_client, new_message).await?; + analyze_logs::handle(ctx, new_message, data).await?; + } + + FullEvent::ReactionAdd { add_reaction } => { + trace!( + "Received reaction {} on message {} from {}", + add_reaction.emoji, + add_reaction.message_id.to_string(), + add_reaction.user_id.unwrap_or_default().to_string() + ); + delete_on_reaction::handle(ctx, add_reaction).await?; + } + + FullEvent::ThreadCreate { thread } => { + trace!("Received thread {}", thread.id); + support_onboard::handle(ctx, thread).await?; + } + + _ => {} + } + + Ok(()) +} diff --git a/src/handlers/event/pluralkit.rs b/src/handlers/event/pluralkit.rs new file mode 100644 index 0000000..a53434c --- /dev/null +++ b/src/handlers/event/pluralkit.rs @@ -0,0 +1,53 @@ +use crate::{ + api::{self, HttpClient}, + storage::Storage, +}; + +use std::time::Duration; + +use eyre::Result; +use log::{debug, trace}; +use poise::serenity_prelude::{Context, Message}; +use tokio::time::sleep; + +const PK_DELAY: Duration = Duration::from_secs(1); + +pub async fn is_message_proxied(http: &HttpClient, message: &Message) -> Result { + trace!( + "Waiting on PluralKit API for {} seconds", + PK_DELAY.as_secs() + ); + sleep(PK_DELAY).await; + + let proxied = api::pluralkit::sender_from(http, message.id).await.is_ok(); + + Ok(proxied) +} + +pub async fn handle( + _: &Context, + http: &HttpClient, + storage: &Storage, + msg: &Message, +) -> Result<()> { + if msg.webhook_id.is_none() { + return Ok(()); + } + + debug!( + "Message {} has a webhook ID. Checking if it was sent through PluralKit", + msg.id + ); + + trace!( + "Waiting on PluralKit API for {} seconds", + PK_DELAY.as_secs() + ); + sleep(PK_DELAY).await; + + if let Ok(sender) = api::pluralkit::sender_from(http, msg.id).await { + storage.store_user_plurality(sender).await?; + } + + Ok(()) +} diff --git a/src/handlers/event/support_onboard.rs b/src/handlers/event/support_onboard.rs new file mode 100644 index 0000000..958c4fe --- /dev/null +++ b/src/handlers/event/support_onboard.rs @@ -0,0 +1,52 @@ +use eyre::{eyre, OptionExt, Result}; +use log::{debug, trace}; +use poise::serenity_prelude::{ + ChannelType, Context, CreateAllowedMentions, CreateMessage, GuildChannel, +}; + +pub async fn handle(ctx: &Context, thread: &GuildChannel) -> Result<()> { + if thread.kind != ChannelType::PublicThread { + trace!("Not doing support onboard in non-public thread channel"); + return Ok(()); + } + + if thread.last_message_id.is_some() { + debug!("Ignoring duplicate thread creation event"); + return Ok(()); + } + + if thread + .parent_id + .ok_or_else(|| eyre!("Couldn't get parent ID from thread {}!", thread.name))? + .name(ctx) + .await + .unwrap_or_default() + != "community-support" + { + debug!("Not posting onboarding message to threads outside of support"); + return Ok(()); + } + + let owner = thread + .owner_id + .ok_or_eyre("Couldn't get owner of thread!")?; + + let msg = format!( + "<@{}> We've received your support ticket! {} {}", + owner, + "Please upload your logs and post the link here if possible (run `/tag log` to find out how).", + "Please don't ping people for support questions, unless you have their permission." + ); + + let allowed_mentions = CreateAllowedMentions::new() + .replied_user(true) + .users(Vec::from([owner])); + + let message = CreateMessage::new() + .content(msg) + .allowed_mentions(allowed_mentions); + + thread.send_message(ctx, message).await?; + + Ok(()) +} diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs new file mode 100644 index 0000000..2ae0539 --- /dev/null +++ b/src/handlers/mod.rs @@ -0,0 +1,5 @@ +mod error; +mod event; + +pub use error::handle as handle_error; +pub use event::handle as handle_event; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..0a4ec23 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,151 @@ +use std::{sync::Arc, time::Duration}; + +use eyre::Context as _; +use log::{info, trace, warn}; +use poise::{ + serenity_prelude::{self as serenity, CreateAllowedMentions}, + EditTracker, Framework, FrameworkOptions, PrefixFrameworkOptions, +}; +use tokio::signal::ctrl_c; +#[cfg(target_family = "unix")] +use tokio::signal::unix::{signal, SignalKind}; +#[cfg(target_family = "windows")] +use tokio::signal::windows::ctrl_close; + +mod api; +mod commands; +mod config; +mod consts; +mod handlers; +mod storage; +mod tags; +mod utils; + +use config::Config; +use storage::Storage; + +type Error = Box; +type Context<'a> = poise::Context<'a, Data, Error>; + +#[derive(Clone, Debug, Default)] +pub struct Data { + config: Config, + storage: Option, + http_client: api::HttpClient, + octocrab: Arc, +} + +async fn setup( + ctx: &serenity::Context, + _: &serenity::Ready, + framework: &Framework, +) -> Result { + let config = Config::new_from_env(); + + let storage = if let Some(url) = &config.bot.redis_url { + Some(Storage::from_url(url)?) + } else { + None + }; + + if let Some(storage) = storage.as_ref() { + if !storage.clone().has_connection() { + return Err( + "You specified a storage backend but there's no connection! Is it running?".into(), + ); + } + + trace!("Redis connection looks good!"); + } + + let http_client = ::default(); + let octocrab = octocrab::instance(); + + let data = Data { + config, + storage, + http_client, + octocrab, + }; + + poise::builtins::register_globally(ctx, &framework.options().commands).await?; + info!("Registered global commands!"); + + Ok(data) +} + +async fn handle_shutdown(shard_manager: Arc, reason: &str) { + warn!("{reason}! Shutting down bot..."); + shard_manager.shutdown_all().await; + println!("Everything is shutdown. Goodbye!"); +} + +#[tokio::main] +async fn main() -> eyre::Result<()> { + dotenvy::dotenv().ok(); + color_eyre::install()?; + env_logger::init(); + rustls::crypto::aws_lc_rs::default_provider() + .install_default() + .expect("Couldn't initialize crypto provider"); + + let token = + std::env::var("DISCORD_BOT_TOKEN").wrap_err("Couldn't find bot token in environment!")?; + + let intents = + serenity::GatewayIntents::non_privileged() | serenity::GatewayIntents::MESSAGE_CONTENT; + + let options = FrameworkOptions { + commands: commands::all(), + + on_error: |error| Box::pin(handlers::handle_error(error)), + + command_check: Some(|ctx| { + Box::pin(async move { Ok(ctx.author().id != ctx.framework().bot_id) }) + }), + + event_handler: |ctx, event, framework, data| { + Box::pin(handlers::handle_event(ctx, event, framework, data)) + }, + + prefix_options: PrefixFrameworkOptions { + prefix: Some(".".into()), + edit_tracker: Some(Arc::from(EditTracker::for_timespan(Duration::from_secs( + 3600, + )))), + ..Default::default() + }, + + allowed_mentions: Some(CreateAllowedMentions::new()), + + ..Default::default() + }; + + let framework = Framework::builder() + .options(options) + .setup(|ctx, ready, framework| Box::pin(setup(ctx, ready, framework))) + .build(); + + let mut client = serenity::ClientBuilder::new(token, intents) + .framework(framework) + .await?; + + let shard_manager = client.shard_manager.clone(); + + #[cfg(target_family = "unix")] + let mut sigterm = signal(SignalKind::terminate())?; + #[cfg(target_family = "windows")] + let mut sigterm = ctrl_close()?; + + tokio::select! { + result = client.start() => result.map_err(eyre::Report::from), + _ = sigterm.recv() => { + handle_shutdown(shard_manager, "Received SIGTERM").await; + std::process::exit(0); + } + _ = ctrl_c() => { + handle_shutdown(shard_manager, "Interrupted").await; + std::process::exit(130); + } + } +} diff --git a/src/storage/mod.rs b/src/storage/mod.rs new file mode 100644 index 0000000..1aad0be --- /dev/null +++ b/src/storage/mod.rs @@ -0,0 +1,92 @@ +use std::fmt::Debug; + +use eyre::Result; +use log::debug; +use poise::serenity_prelude::UserId; +use redis::{AsyncCommands, Client, ConnectionLike}; + +const PK_KEY: &str = "pluralkit-v1"; +const LAUNCHER_VERSION_KEY: &str = "launcher-version-v1"; +const LAUNCHER_STARGAZER_KEY: &str = "launcher-stargazer-v1"; + +#[derive(Clone, Debug)] +pub struct Storage { + client: Client, +} + +impl Storage { + pub fn new(client: Client) -> Self { + Self { client } + } + + pub fn from_url(redis_url: &str) -> Result { + let client = Client::open(redis_url)?; + + Ok(Self::new(client)) + } + + pub fn has_connection(&mut self) -> bool { + self.client.check_connection() + } + + pub async fn store_user_plurality(&self, sender: UserId) -> Result<()> { + debug!("Marking {sender} as a PluralKit user"); + let key = format!("{PK_KEY}:{sender}"); + + let mut con = self.client.get_multiplexed_async_connection().await?; + // Just store some value. We only care about the presence of this key + () = con.set_ex(key, 0, 7 * 24 * 60 * 60).await?; // 1 week + + Ok(()) + } + + pub async fn is_user_plural(&self, user_id: UserId) -> Result { + debug!("Checking if user {user_id} is plural"); + let key = format!("{PK_KEY}:{user_id}"); + + let mut con = self.client.get_multiplexed_async_connection().await?; + let exists = con.exists(key).await?; + + Ok(exists) + } + + pub async fn cache_launcher_version(&self, version: &str) -> Result<()> { + debug!("Caching launcher version as {version}"); + + let mut con = self.client.get_multiplexed_async_connection().await?; + () = con + .set_ex(LAUNCHER_VERSION_KEY, version, 24 * 60 * 60) + .await?; // 1 day + + Ok(()) + } + + pub async fn launcher_version(&self) -> Result { + debug!("Fetching launcher version"); + + let mut con = self.client.get_multiplexed_async_connection().await?; + let res = con.get(LAUNCHER_VERSION_KEY).await?; + + Ok(res) + } + + pub async fn cache_launcher_stargazer_count(&self, stargazers: u32) -> Result<()> { + debug!("Caching stargazer count as {stargazers}"); + + let mut con = self.client.get_multiplexed_async_connection().await?; + () = con + .set_ex(LAUNCHER_STARGAZER_KEY, stargazers, 60 * 60) + .await?; + + Ok(()) + } + + pub async fn launcher_stargazer_count(&self) -> Result { + debug!("Fetching launcher stargazer count"); + + let mut con = self.client.get_multiplexed_async_connection().await?; + let res: u32 = con.get(LAUNCHER_STARGAZER_KEY).await?; + + Ok(res) + } +} diff --git a/src/tags.rs b/src/tags.rs new file mode 100644 index 0000000..2d6336d --- /dev/null +++ b/src/tags.rs @@ -0,0 +1,20 @@ +use poise::serenity_prelude::EmbedField; +use serde::{Deserialize, Serialize}; + +#[allow(dead_code)] +pub const TAG_DIR: &str = "tags"; + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TagFrontmatter { + pub title: String, + pub color: Option, + pub image: Option, + pub fields: Option>, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Tag { + pub content: String, + pub id: String, + pub frontmatter: TagFrontmatter, +} diff --git a/src/utils/messages.rs b/src/utils/messages.rs new file mode 100644 index 0000000..830e49f --- /dev/null +++ b/src/utils/messages.rs @@ -0,0 +1,175 @@ +use crate::api::{pluralkit, HttpClient}; + +use std::{str::FromStr, sync::OnceLock}; + +use eyre::{eyre, Context as _, Result}; +use log::{debug, trace}; +use poise::serenity_prelude::{ + Cache, CacheHttp, ChannelId, ChannelType, Colour, Context, CreateEmbed, CreateEmbedAuthor, + CreateEmbedFooter, GuildChannel, Member, Message, MessageId, Permissions, UserId, +}; +use regex::Regex; + +fn find_first_image(message: &Message) -> Option { + message + .attachments + .iter() + .find(|a| { + a.content_type + .as_ref() + .unwrap_or(&String::new()) + .starts_with("image/") + }) + .map(|res| res.url.clone()) +} + +async fn find_real_author_id(http: &HttpClient, message: &Message) -> UserId { + if let Ok(sender) = pluralkit::sender_from(http, message.id).await { + sender + } else { + message.author.id + } +} + +async fn member_can_view_channel( + ctx: impl CacheHttp + AsRef, + member: &Member, + channel: &GuildChannel, +) -> Result { + static REQUIRED_PERMISSIONS: OnceLock = OnceLock::new(); + let required_permissions = REQUIRED_PERMISSIONS + .get_or_init(|| Permissions::VIEW_CHANNEL | Permissions::READ_MESSAGE_HISTORY); + + let guild = ctx.http().get_guild(channel.guild_id).await?; + + let channel_to_check = match &channel.kind { + ChannelType::PublicThread => { + let parent_id = channel + .parent_id + .ok_or_else(|| eyre!("Couldn't get parent of thread {}", channel.id))?; + parent_id + .to_channel(ctx) + .await? + .guild() + .ok_or_else(|| eyre!("Couldn't get GuildChannel from ChannelID {parent_id}!"))? + } + + ChannelType::Text | ChannelType::News => channel.to_owned(), + + _ => return Ok(false), + }; + + let can_view = guild + .user_permissions_in(&channel_to_check, member) + .contains(*required_permissions); + Ok(can_view) +} + +pub async fn to_embed( + ctx: impl CacheHttp + AsRef, + message: &Message, +) -> Result { + let author = CreateEmbedAuthor::new(message.author.tag()).icon_url( + message + .author + .avatar_url() + .unwrap_or_else(|| message.author.default_avatar_url()), + ); + + let footer = CreateEmbedFooter::new(format!( + "#{}", + message.channel(ctx).await?.guild().unwrap_or_default().name + )); + + let mut embed = CreateEmbed::new() + .author(author) + .color(Colour::BLITZ_BLUE) + .timestamp(message.timestamp) + .footer(footer) + .description(format!( + "{}\n\n[Jump to original message]({})", + message.content, + message.link() + )); + + if !message.attachments.is_empty() { + embed = embed.fields(message.attachments.iter().map(|a| { + ( + "Attachments".to_string(), + format!("[{}]({})", a.filename, a.url), + false, + ) + })); + + if let Some(image) = find_first_image(message) { + embed = embed.image(image); + } + } + + Ok(embed) +} + +pub async fn from_message( + ctx: &Context, + http: &HttpClient, + msg: &Message, +) -> Result> { + static MESSAGE_PATTERN: OnceLock = OnceLock::new(); + let message_pattern = MESSAGE_PATTERN.get_or_init(|| Regex::new(r"(?:https?:\/\/)?(?:canary\.|ptb\.)?discord(?:app)?\.com\/channels\/(?\d+)\/(?\d+)\/(?\d+)").unwrap()); + + let Some(guild_id) = msg.guild_id else { + debug!("Not resolving message in DM"); + return Ok(Vec::new()); + }; + + // if the message was sent through pluralkit, we'll want + // to reference the Member of the unproxied account + let author_id = if msg.webhook_id.is_some() { + find_real_author_id(http, msg).await + } else { + msg.author.id + }; + + let author = guild_id.member(ctx, author_id).await?; + + let matches = message_pattern + .captures_iter(&msg.content) + .map(|capture| capture.extract()); + + let mut embeds: Vec = vec![]; + + for (url, [target_guild_id, target_channel_id, target_message_id]) in matches { + if target_guild_id != guild_id.to_string() { + debug!("Not resolving message from other server"); + continue; + } + trace!("Attempting to resolve message {target_message_id} from URL {url}"); + + let target_channel = ChannelId::from_str(target_channel_id)? + .to_channel(ctx) + .await? + .guild() + .ok_or_else(|| { + eyre!("Couldn't find GuildChannel from ChannelId {target_channel_id}!") + })?; + + if !member_can_view_channel(ctx, &author, &target_channel).await? { + debug!("Not resolving message for author who can't see it"); + continue; + } + + let target_message_id = MessageId::from_str(target_message_id)?; + let target_message = target_channel + .message(ctx, target_message_id) + .await + .wrap_err_with(|| { + eyre!("Couldn't find channel message from ID {target_message_id}!") + })?; + + let embed = to_embed(ctx, &target_message).await?; + + embeds.push(embed); + } + + Ok(embeds) +} diff --git a/src/utils/mod.rs b/src/utils/mod.rs new file mode 100644 index 0000000..56385cb --- /dev/null +++ b/src/utils/mod.rs @@ -0,0 +1,17 @@ +use poise::serenity_prelude::{CreateEmbedAuthor, User}; + +pub mod messages; + +pub fn embed_author_from_user(user: &User) -> CreateEmbedAuthor { + CreateEmbedAuthor::new(user.tag()).icon_url( + user.avatar_url() + .unwrap_or_else(|| user.default_avatar_url()), + ) +} + +pub fn semver_split(version: &str) -> Vec { + version + .split('.') + .filter_map(|s| s.parse().ok()) + .collect::>() +} diff --git a/tags/binary_search.md b/tags/binary_search.md new file mode 100644 index 0000000..487a902 --- /dev/null +++ b/tags/binary_search.md @@ -0,0 +1,17 @@ +--- +title: Binary Search - A method of finding problems with mods +color: blue +--- + +The binary search is a way of finding a faulty thing amongst a lot of other things, without having to remove the things one-by-one. This is useful for finding a broken mod among hundreds of mods, without having to spend time testing the mods one-by-one. + +The procedure is simple: + +1. Remove half of the existing things, and put them aside. +2. Run the program / game. +3. Does the issue still exist? + If YES: Repeat from step 1 with the current things. + IF NO: Swap out the current things with the ones set aside, and repeat from step 1. +4. Repeat this process until the problematic thing/s have been found. + +_Credit to the Quilt Community discord and the Forge Discord for these instructions._ diff --git a/tags/build.md b/tags/build.md new file mode 100644 index 0000000..10eb711 --- /dev/null +++ b/tags/build.md @@ -0,0 +1,6 @@ +--- +title: Building Prism from scratch +color: blue +--- + +https://prismlauncher.org/wiki/development/build-instructions/ diff --git a/tags/curseforge.md b/tags/curseforge.md new file mode 100644 index 0000000..cd67b98 --- /dev/null +++ b/tags/curseforge.md @@ -0,0 +1,6 @@ +--- +title: What's wrong with CurseForge? +color: orange +--- + +CurseForge added a new option to block third party clients like Prism Launcher from accessing mod files, and they started to enforce this option lately. We can't allow you to download those mods directly from CurseForge because of this. However, Prism Launcher offers a workaround to enable the downloading of these mods, by allowing you to download these mods from your browser and automatically importing them into the instance. We highly encourage asking authors that opted out of client downloads to stop doing so. diff --git a/tags/fractureiser.md b/tags/fractureiser.md new file mode 100644 index 0000000..2a124d7 --- /dev/null +++ b/tags/fractureiser.md @@ -0,0 +1,10 @@ +--- +title: Information about Fractureiser +color: orange +--- + +Starting June 6th, 2023 UTC, there have been reports of malware being distributed through websites such as Curseforge, Bukkit, and possibly others in the form of mods, plugins, and modpacks. According to both [Modrinth](https://twitter.com/modrinth/status/1666853947804463115) and [Curseforge](https://twitter.com/CurseForge/status/1666741580022128641), all infected files have been removed. These services should be safe to use now, however users should still take caution in downloading files, especially from less trustworthy services. + +This is a complex situation, and for a full explanation you should go to [this](https://github.com/fractureiser-investigation/fractureiser) GitHub repository. We have also provided resources to help users find out if they have been affected [here](https://prismlauncher.org/news/cf-compromised-alert/#what-can-i-do). This includes scripts for both Windows and Linux (the operating systems known to be affected so far) to help you find files used by Fractureiser. + +In the case files are found, they should be deleted - however, we still recommend to **change all of your passwords**, especially for accounts with login information saved in your browser. There are also tools such as [NekoDetector](https://github.com/MCRcortex/nekodetector) that allow you to check for any Java files that could place these files on your computer again, and a [web app](https://douira.github.io/fractureiser-web-detector/) that allows you to scan individual mods. diff --git a/tags/ftb.md b/tags/ftb.md new file mode 100644 index 0000000..f78a016 --- /dev/null +++ b/tags/ftb.md @@ -0,0 +1,12 @@ +--- +title: Can I install/download FTB packs directly from Prism? +color: orange +--- + +You cannot download FTB packs directly from Prism Launcher. + +At the request of the FTB Team we had to remove the feature that allows you to download them from Prism Launcher due to the monetization of FTB packs. + +Existing instances of FTB packs are still functional, however to download them, you have to use the official FTB App and manually import the modpack to your Prism Launcher instances. + +For more information, please see [the blogpost](https://prismlauncher.org/news/ftb-removal/). diff --git a/tags/gayming.md b/tags/gayming.md new file mode 100644 index 0000000..fc64e93 --- /dev/null +++ b/tags/gayming.md @@ -0,0 +1,10 @@ +--- +title: Why is the channel called "gayming"? +color: pink +--- + +"gayming" is the correct spelling to describe the action of playing video gaymes. The common misconception that it should be spelled "gaming" stems from the erroneous yet widespread use of "game" instead of "gayme". + +This channel helps inform of proper lingustics in the face of rampant misspelling. ||This is a joke, though we do love our fellow gaymers out here :rainbow:|| + +(Taken almost entirely from Modrinth) diff --git a/tags/java.md b/tags/java.md new file mode 100644 index 0000000..b7232dc --- /dev/null +++ b/tags/java.md @@ -0,0 +1,6 @@ +--- +title: Java Instructions +color: orange +--- + +As of 9.0, Prism Launcher can automatically download and configure Java for the version of Minecraft you are using. The instructions can be found [here](https://prismlauncher.org/wiki/getting-started/installing-java/). diff --git a/tags/legacy_java_fixer.md b/tags/legacy_java_fixer.md new file mode 100644 index 0000000..0ccb6c4 --- /dev/null +++ b/tags/legacy_java_fixer.md @@ -0,0 +1,6 @@ +--- +title: LegacyJavaFixer +color: yellow +--- + +MinecraftForge provides a coremod to fix some issues with older Forge versions on recent Java versions. You can download it [here](https://dist.creeper.host/FTB2/maven/net/minecraftforge/lex/legacyjavafixer/1.0/legacyjavafixer-1.0.jar). diff --git a/tags/log.md b/tags/log.md new file mode 100644 index 0000000..94a3cf6 --- /dev/null +++ b/tags/log.md @@ -0,0 +1,7 @@ +--- +title: Upload Logs +color: orange +image: https://cdn.discordapp.com/attachments/1031694870756204566/1156971972232740874/image.png +--- + +Please send logs! The recommended site to upload your logs to is [mclo.gs](https://mclo.gs/). diff --git a/tags/login_fix.md b/tags/login_fix.md new file mode 100644 index 0000000..6931eb4 --- /dev/null +++ b/tags/login_fix.md @@ -0,0 +1,10 @@ +--- +title: Microsoft login +color: orange +--- + +If you have trouble with Microsoft login make sure: +* The age stated in your account is over 21. +* Microsoft auth servers are not experiencing downtime. + +For more possible solutions check this GitHub issue [#2302](https://github.com/PrismLauncher/PrismLauncher/issues/2302). diff --git a/tags/macos_arm_java.md b/tags/macos_arm_java.md new file mode 100644 index 0000000..abb40e8 --- /dev/null +++ b/tags/macos_arm_java.md @@ -0,0 +1,12 @@ +--- +title: Install arm64 Java on macOS +color: yellow +--- + +On macOS arm64, also known as Apple Silicon (M1, M2, etc.), you will need to install the arm64 version of Java. We recommend using builds from Azul, the links for which can be found below: + +- [Java 8](https://www.azul.com/downloads/?version=java-8-lts&os=macos&architecture=arm-64-bit&package=jdk#zulu) or versions ≤ 1.16 +- [Java 17](https://www.azul.com/downloads/?version=java-17-lts&os=macos&architecture=arm-64-bit&package=jdk#zulu) for versions ≥ 1.17 and ≤ 1.20.4 +- [Java 21](https://www.azul.com/downloads/?version=java-21-lts&os=macos&architecture=arm-64-bit&package=jdk#zulu) for versions ≥ 1.20.5 + +It is recommended to install Java 8, Java 17, and Java 21. diff --git a/tags/migrate.md b/tags/migrate.md new file mode 100644 index 0000000..16886f3 --- /dev/null +++ b/tags/migrate.md @@ -0,0 +1,6 @@ +--- +title: Migrating from MultiMC +color: orange +--- + +https://prismlauncher.org/wiki/getting-started/migrating-multimc/ diff --git a/tags/minecraft_launcher_comparison.md b/tags/minecraft_launcher_comparison.md new file mode 100644 index 0000000..08ee5d1 --- /dev/null +++ b/tags/minecraft_launcher_comparison.md @@ -0,0 +1,7 @@ +--- +title: Minecraft Launcher Comparison +color: green +--- + +Here is a comparison of the features of various launchers, including Prism Launcher: +https://mc-launcher.tayou.org/ diff --git a/tags/nightly.md b/tags/nightly.md new file mode 100644 index 0000000..2358157 --- /dev/null +++ b/tags/nightly.md @@ -0,0 +1,9 @@ +--- +title: Where can I download unstable builds of Prism Launcher? +color: green +--- + +You can download unstable builds [here](https://nightly.link/PrismLauncher/PrismLauncher/workflows/build/develop). + +> **:warning: Caution** +> Unstable builds have more bugs and are therefore more likely to break! By using the latest commit you are using software which has not been properly tested. For this reason we recommend using Portable or AppImage builds, or least making a backup. diff --git a/tags/not_support.md b/tags/not_support.md new file mode 100644 index 0000000..5f3ccf2 --- /dev/null +++ b/tags/not_support.md @@ -0,0 +1,7 @@ +--- +title: 🚨 This is not a support channel! 🚨 +color: orange +--- + +👉 <#1032130809055940690> 👈 +👉 <#1118165588200657006> 👈 diff --git a/tags/optifine.md b/tags/optifine.md new file mode 100644 index 0000000..403e099 --- /dev/null +++ b/tags/optifine.md @@ -0,0 +1,10 @@ +--- +title: OptiFine +color: green +--- + +OptiFine is known to cause problems when paired with other mods. + +Please see [Installing OptiFine Alternatives](https://prismlauncher.org/wiki/getting-started/install-of-alternatives/). + +If you really want to use OptiFine, see [Installing OptiFine](https://prismlauncher.org/wiki/getting-started/installing-optifine/). diff --git a/tags/paths.md b/tags/paths.md new file mode 100644 index 0000000..6ae5961 --- /dev/null +++ b/tags/paths.md @@ -0,0 +1,20 @@ +--- +title: Data directories +color: blue + +fields: + - name: Portable (Windows / Linux) + value: In the PrismLauncher folder + - name: Windows + value: '`%APPDATA%/PrismLauncher`' + - name: Scoop + value: '`%HOMEPATH%\scoop\persist\prismlauncher`' + - name: macOS + value: '`~/Library/Application Support/PrismLauncher`' + - name: Linux + value: '`~/.local/share/PrismLauncher`' + - name: Flatpak + value: '`~/.var/app/org.prismlauncher.PrismLauncher/data/PrismLauncher`' +--- + +Where Prism Launcher stores your data (e.g. instances). diff --git a/tags/piracy.md b/tags/piracy.md new file mode 100644 index 0000000..234f290 --- /dev/null +++ b/tags/piracy.md @@ -0,0 +1,6 @@ +--- +title: We don't tolerate piracy! +color: red +--- + +Prism Launcher has always been legal, legitimate & appropriate. We don't and never will have features such as offline login without an official account. diff --git a/tags/pluralkit.md b/tags/pluralkit.md new file mode 100644 index 0000000..a8278ad --- /dev/null +++ b/tags/pluralkit.md @@ -0,0 +1,14 @@ +--- +title: Why PluralKit? +color: blue +--- + +Plurality is the existence of multiple self-aware entities inside the same brain. + +Each member of a system/collective (group residing inside the same physical brain) is an individual person, so please treat them as such. + +On Discord, some systems may use [PluralKit](https://pluralkit.me/) to make their message appear with the correct profile, resulting in a `[APP]` tag. + +For more information about plurality, we recommend [More Than One](https://morethanone.info/) for a useful overview. + +**Note: We do NOT tolerate the use of PluralKit for role playing.** diff --git a/tags/prism_logs.md b/tags/prism_logs.md new file mode 100644 index 0000000..c04eb8c --- /dev/null +++ b/tags/prism_logs.md @@ -0,0 +1,20 @@ +--- +title: Upload Logs +color: orange + +fields: + - name: Portable (Windows / Linux) + value: '`./logs/PrismLauncher-0.log` In the PrismLauncher folder' + - name: Windows + value: '`%APPDATA%/PrismLauncher/logs/PrismLauncher-0.log`' + - name: Scoop + value: '`%HOMEPATH%\scoop\persist\prismlauncher\logs\PrismLauncher-0.log`' + - name: macOS + value: '`~/Library/Application Support/PrismLauncher/logs/PrismLauncher-0.log`' + - name: Linux + value: '`~/.local/share/PrismLauncher/logs/PrismLauncher-0.log`' + - name: Flatpak + value: '`~/.var/app/org.prismlauncher.PrismLauncher/data/PrismLauncher/logs/PrismLauncher-0.log`' +--- + +Please send logs! The recommended site to upload your logs to is [mclo.gs](https://mclo.gs/). diff --git a/tags/update.md b/tags/update.md new file mode 100644 index 0000000..ec17f2a --- /dev/null +++ b/tags/update.md @@ -0,0 +1,10 @@ +--- +title: Does Prism Launcher auto-update? +color: blue +--- + +Windows auto-updating is only supported on 8.0+. For Prism 7.2 or below, you will need to download the installer and run it again in order to update. On 8.0 or newer, click the 'Update' button. You will not lose your instances. + +Prism Launcher auto-updates for macOS using the [Sparkle Framework](https://sparkle-project.org/). + +For Linux, just use your package manager! Otherwise, AppImage and portable auto-updating was added in 8.0. diff --git a/tags/vcredist.md b/tags/vcredist.md new file mode 100644 index 0000000..017bd3b --- /dev/null +++ b/tags/vcredist.md @@ -0,0 +1,13 @@ +--- +title: vcredist is required to run Prism on Windows +color: pink +--- + +Like most apps on Windows, you have to install vcredist for Prism to run. Depending on what version of Prism you are using, you may need a different version. + +You need: + +- [vcredist 2022 x64](https://aka.ms/vs/17/release/vc_redist.x64.exe) if you're using PrismLauncher-Windows-MSVC (the recommended version for Windows 10 64 bit/Windows 11). +- [vcredist 2022 arm64](https://aka.ms/vs/17/release/vc_redist.arm64.exe) if you're using PrismLauncher-Windows-MSVC-arm64 (the recommended version for Windows 10/11 on ARM). + +See the [wiki page](https://prismlauncher.org/wiki/overview/frequent-issues/#%22msvcp140_2.dll-was-not-found%22) on Prism's website for more information. diff --git a/tags/why.md b/tags/why.md new file mode 100644 index 0000000..77d5cf0 --- /dev/null +++ b/tags/why.md @@ -0,0 +1,7 @@ +--- +title: But why? +color: purple +--- + +https://prismlauncher.org/wiki/overview/faq/#why-did-our-community-choose-to-fork +https://prismlauncher.org/news/moving-on/ diff --git a/tags/why_java_8.md b/tags/why_java_8.md new file mode 100644 index 0000000..d9aa824 --- /dev/null +++ b/tags/why_java_8.md @@ -0,0 +1,8 @@ +--- +title: Why does Prism Launcher ask me to change Java version? +color: orange +--- + +Minecraft versions before 1.17 required Java 8 and have issues with newer Java, while newer versions require Java 17 or Java 21, so you need to change Java version. Some people think Java 8 is very outdated, however, it's actually an LTS, meaning it's still getting updates. + +If one of your mods is weird and requires newer Java, you can bypass this, by going to instance settings-Java and ticking 'Skip java compatibility checks', but be aware of potential issues, such as [random CMEs](https://bugs.mojang.com/browse/MC-149777).