├── .github └── workflows │ ├── ci.yml │ └── docs.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── README.md ├── auth.rs ├── details.rs ├── download.rs ├── events.rs └── mymods.rs ├── header.png ├── src ├── auth.rs ├── client │ ├── builder.rs │ └── mod.rs ├── comments.rs ├── download.rs ├── error.rs ├── file_source.rs ├── files.rs ├── filter.rs ├── games.rs ├── lib.rs ├── loader.rs ├── macros.rs ├── metadata.rs ├── mods.rs ├── reports.rs ├── request.rs ├── routing.rs ├── teams.rs ├── types │ ├── auth.rs │ ├── files.rs │ ├── games.rs │ ├── id.rs │ ├── macros.rs │ ├── mod.rs │ ├── mods.rs │ └── utils.rs └── user.rs └── tests ├── fixtures ├── games-page1.json ├── games-page2.json ├── games-page3.json ├── games-page4.json └── games-page5.json └── query.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | lints: 7 | name: Rustfmt and clippy 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v4 13 | with: 14 | persist-credentials: false 15 | 16 | - name: Install rust (stable) 17 | uses: dtolnay/rust-toolchain@stable 18 | with: 19 | components: clippy, rustfmt 20 | 21 | - name: Run rustfmt 22 | run: cargo fmt --check 23 | 24 | - name: Run clippy 25 | run: cargo clippy --all-features -- -D warnings 26 | 27 | docs: 28 | name: Build docs 29 | runs-on: ubuntu-latest 30 | 31 | steps: 32 | - name: Checkout 33 | uses: actions/checkout@v4 34 | with: 35 | persist-credentials: false 36 | 37 | - name: Install rust (nightly) 38 | uses: dtolnay/rust-toolchain@nightly 39 | 40 | - name: Generate docs 41 | run: cargo doc --no-deps --all-features 42 | 43 | build_and_test: 44 | name: Build and test 45 | runs-on: ubuntu-latest 46 | 47 | strategy: 48 | matrix: 49 | rust: [stable, beta, nightly] 50 | 51 | steps: 52 | - name: Checkout 53 | uses: actions/checkout@v4 54 | with: 55 | persist-credentials: false 56 | 57 | - name: Install rust (${{ matrix.rust }}) 58 | uses: dtolnay/rust-toolchain@master 59 | with: 60 | toolchain: ${{ matrix.rust }} 61 | 62 | - name: Check default features 63 | run: cargo check --examples --tests 64 | 65 | - name: Check no default features 66 | run: cargo check --examples --tests --no-default-features 67 | 68 | - name: Check `rustls-tls` feature 69 | run: cargo check --examples --tests --no-default-features --features rustls-tls 70 | 71 | - name: Check `default-tls` and `rustls-tls` feature 72 | run: cargo check --examples --tests --features rustls-tls 73 | 74 | - name: Tests 75 | run: cargo test --all-features 76 | 77 | minimal_versions: 78 | name: Minimal crate versions 79 | runs-on: ubuntu-latest 80 | 81 | steps: 82 | - name: Checkout 83 | uses: actions/checkout@v4 84 | with: 85 | persist-credentials: false 86 | 87 | - name: Install nightly toolchain 88 | uses: dtolnay/rust-toolchain@nightly 89 | 90 | - name: Install stable toolchain 91 | uses: dtolnay/rust-toolchain@stable 92 | 93 | - name: Install cargo-hack 94 | uses: taiki-e/install-action@cargo-hack 95 | 96 | - name: Install cargo-minimal-versions 97 | uses: taiki-e/install-action@cargo-minimal-versions 98 | 99 | - name: Check minimal versions 100 | run: cargo minimal-versions check --no-default-features --features rustls-tls 101 | 102 | MSRV: 103 | runs-on: ubuntu-latest 104 | 105 | steps: 106 | - name: Checkout 107 | uses: actions/checkout@v4 108 | with: 109 | persist-credentials: false 110 | 111 | - name: Get MSRV from package metadata 112 | id: msrv 113 | run: cargo metadata --no-deps --format-version 1 | jq -r '"version=" + (.packages[] | select(.name == "modio")).rust_version' >> $GITHUB_OUTPUT 114 | 115 | - name: Install rust (${{ steps.msrv.outputs.version }}) 116 | uses: dtolnay/rust-toolchain@master 117 | with: 118 | toolchain: ${{ steps.msrv.outputs.version }} 119 | 120 | - run: cargo check --all-features 121 | -------------------------------------------------------------------------------- /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | name: docs 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | 7 | permissions: 8 | contents: read 9 | pages: write 10 | id-token: write 11 | 12 | jobs: 13 | build: 14 | name: Build docs 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v4 19 | with: 20 | persist-credentials: false 21 | - uses: dtolnay/rust-toolchain@nightly 22 | 23 | - name: Build docs 24 | run: cargo doc --no-deps --all-features 25 | 26 | - name: Prepare docs 27 | run: | 28 | mkdir -p _site/master 29 | echo '' > _site/index.html 30 | echo '' > _site/master/index.html 31 | mv target/doc/* _site/master 32 | 33 | - uses: actions/upload-pages-artifact@v3 34 | 35 | deploy: 36 | name: Deploy to GitHub Pages 37 | needs: build 38 | 39 | environment: 40 | name: github-pages 41 | url: ${{ steps.deployment.outputs.page_url }} 42 | 43 | runs-on: ubuntu-latest 44 | steps: 45 | - name: Deploy to GitHub Pages 46 | id: deployment 47 | uses: actions/deploy-pages@v4 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | .env 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "modio" 3 | version = "0.13.0" # don't forget to update html_root_url 4 | description = "Rust interface for integrating https://mod.io - a modding API for game developers" 5 | repository = "https://github.com/nickelc/modio-rs" 6 | license = "MIT OR Apache-2.0" 7 | authors = ["Constantin Nickel "] 8 | keywords = ["modio", "client"] 9 | categories = ["api-bindings", "web-programming::http-client"] 10 | edition = "2021" 11 | rust-version = "1.82" 12 | include = ["src/**/*", "LICENSE-*", "README.md", "CHANGELOG.md"] 13 | 14 | [dependencies] 15 | bitflags = "2.8.0" 16 | bytes = "1.9.0" 17 | futures-util = { version = "0.3.31", features = ["sink"] } 18 | http = "1.2.0" 19 | mime = "0.3.17" 20 | pin-project-lite = "0.2.16" 21 | reqwest = { version = "0.12.12", default-features = false, features = ["multipart", "stream"] } 22 | serde = "1.0.217" 23 | serde_derive = "1.0.217" 24 | serde_json = "1.0.135" 25 | tokio = { version = "1.43.0", default-features = false, features = ["fs"] } 26 | tokio-util = { version = "0.7.13", features = ["codec", "io"] } 27 | tracing = "0.1.40" 28 | url = "2.5.4" 29 | 30 | [dev-dependencies] 31 | dotenv = "0.15.0" 32 | httptest = "0.16.1" 33 | md5 = "0.7.0" 34 | serde_test = "1.0.177" 35 | tokio = { version = "1.43.0", features = ["full"] } 36 | tracing-subscriber = { version = "0.3.19", features = ["env-filter"] } 37 | 38 | [features] 39 | default = ["default-tls"] 40 | default-tls = ["reqwest/native-tls", "__tls"] 41 | rustls-tls = ["reqwest/rustls-tls", "__tls"] 42 | 43 | # Internal features 44 | __tls = [] 45 | 46 | [package.metadata.docs.rs] 47 | all-features = true 48 | rustdoc-args = ["--cfg", "docsrs"] 49 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 nickelc 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | mod.io 2 | 3 | [![Crates.io][crates-badge]][crates-url] 4 | [![Released API docs][docs-badge]][docs-url] 5 | [![Master API docs][master-docs-badge]][master-docs-url] 6 | ![Rust version][rust-version] 7 | ![License][license-badge] 8 | [![Workflow Status][workflow-badge]][actions-url] 9 | 10 | [crates-badge]: https://img.shields.io/crates/v/modio.svg 11 | [crates-url]: https://crates.io/crates/modio 12 | [docs-badge]: https://docs.rs/modio/badge.svg 13 | [docs-url]: https://docs.rs/modio 14 | [license-badge]: https://img.shields.io/crates/l/modio.svg 15 | [master-docs-badge]: https://img.shields.io/badge/docs-master-green.svg 16 | [master-docs-url]: https://nickelc.github.io/modio-rs/master/ 17 | [workflow-badge]: https://github.com/nickelc/modio-rs/workflows/ci/badge.svg 18 | [actions-url]: https://github.com/nickelc/modio-rs/actions 19 | [rust-version]: https://img.shields.io/badge/rust-1.82.0%2B-lightgrey.svg?logo=rust 20 | 21 | `modio` provides a set of building blocks for interacting with the [mod.io](https://mod.io) API. 22 | 23 | The client uses asynchronous I/O, backed by the `futures` and `tokio` crates, and requires both to be used alongside. 24 | 25 | ## mod.io 26 | [mod.io](https://mod.io) is a drop-in modding solution from the founders of [ModDB.com](https://www.moddb.com), 27 | that facilitates the upload, search, browsing, downloading and trading of mods in-game. 28 | 29 | ## Usage 30 | 31 | To use `modio`, execute `cargo add modio`. 32 | 33 | ### Basic Setup 34 | ```rust 35 | use modio::{Credentials, Modio, Result}; 36 | 37 | #[tokio::main] 38 | async fn main() -> Result<()> { 39 | let modio = Modio::new( 40 | Credentials::new("user-or-game-apikey"), 41 | )?; 42 | 43 | // create some tasks and execute them 44 | // let result = task.await?; 45 | Ok(()) 46 | } 47 | ``` 48 | 49 | ### Authentication 50 | ```rust 51 | // Request a security code be sent to the email address. 52 | modio.auth().request_code("john@example.com").await?; 53 | 54 | // Wait for the 5-digit security code 55 | let token = modio.auth().security_code("QWERT").await?; 56 | 57 | // Create an endpoint with the new credentials 58 | let modio = modio.with_credentials(token); 59 | ``` 60 | See [full example](examples/auth.rs). 61 | 62 | ### Games 63 | ```rust 64 | use modio::filter::prelude::*; 65 | 66 | // List games with filter `name_id = "0ad"` 67 | let games = modio.games().search(NameId::eq("0ad")).collect().await?; 68 | ``` 69 | 70 | ### Mods 71 | ```rust 72 | use modio::filter::prelude::*; 73 | 74 | // List all mods for 0 A.D. 75 | let mods = modio.game(5).mods().search(Filter::default()).collect().await?; 76 | 77 | // Get the details of the `balancing-mod` mod 78 | let balancing_mod = modio.mod_(5, 110).get().await?; 79 | ``` 80 | 81 | ### Streaming search result 82 | ```rust 83 | use futures::TryStreamExt; 84 | 85 | let filter = Fulltext::eq("tftd").limit(10); 86 | let mut st = modio.game(51).mods().search(filter).paged().await?; 87 | let (_page_count, _) = st.size_hint(); 88 | 89 | // Stream of paged results `Page` with page size = 10 90 | while let Some(page) = st.try_next().await? { 91 | println!("Page {}/{} - Items #{}", page.current(), page.page_count(), page.len()); 92 | for item in page { 93 | println!(" {}. {}", item.id, item.name); 94 | } 95 | } 96 | 97 | let filter = Fulltext::eq("soldier"); 98 | let mut st = modio.game(51).mods().search(filter).iter().await?; 99 | let (_total, _) = st.size_hint(); 100 | 101 | // Stream of `Mod` 102 | while let Some(mod_) = st.try_next().await? { 103 | println!("{}. {}", mod_.id, mod_.name); 104 | } 105 | ``` 106 | 107 | ### Download 108 | ```rust 109 | use future_util::{future, TryStreamExt}; 110 | use modio::download::{ResolvePolicy, DownloadAction}; 111 | 112 | // Download the primary file of a mod. 113 | let action = DownloadAction::Primary { 114 | game_id: 5, 115 | mod_id: 19, 116 | }; 117 | modio 118 | .download(action) 119 | .await? 120 | .save_to_file("mod.zip") 121 | .await?; 122 | 123 | // Download the specific file of a mod. 124 | let action = DownloadAction::File { 125 | game_id: 5, 126 | mod_id: 19, 127 | file_id: 101, 128 | }; 129 | modio 130 | .download(action) 131 | .await?.save_to_file("mod.zip") 132 | .await?; 133 | 134 | // Download the specific version of a mod. 135 | // if multiple files are found then the latest file is downloaded. 136 | // Set policy to `ResolvePolicy::Fail` to return with `modio::download::Error::MultipleFilesFound` 137 | // as source error. 138 | let action = DownloadAction::Version { 139 | game_id: 5, 140 | mod_id: 19, 141 | version: "0.1".to_string(), 142 | policy: ResolvePolicy::Latest, 143 | }; 144 | modio 145 | .download(action) 146 | .await? 147 | .stream() 148 | .try_for_each(|bytes| { 149 | println!("bytes: {:?}") 150 | future::ok(()) 151 | }) 152 | .await?; 153 | ``` 154 | 155 | ### Examples 156 | 157 | See [examples directory](examples/) for some getting started examples. 158 | 159 | ## License 160 | 161 | Licensed under either of 162 | 163 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://apache.org/licenses/LICENSE-2.0) 164 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 165 | 166 | ### Contribution 167 | 168 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, 169 | as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 170 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | ## Examples of using modio 2 | 3 | Run examples with `cargo run --example example_name` 4 | 5 | ### Available examples 6 | 7 | * [`auth`](auth.rs) - Request an access token and print the authenticated user. See [Email Authentication Flow](https://docs.mod.io/restapiref/#authenticate-via-email). 8 | 9 | * [`details`](details.rs) - Print some mod details (profile, dependencies, stats, files). 10 | 11 | * [`download`](download.rs) - Download the latest modfile for a given mod of a game. 12 | 13 | * [`events`](events.rs) - Poll the user events from [`/me/events`](https://docs.mod.io/restapiref/#get-user-events) every 10 seconds. 14 | 15 | * [`mymods`](mymods.rs) - List all mods the *authenticated user* added or is team member of. See [`/me/mods`](https://docs.mod.io/restapiref/#get-user-mods). 16 | -------------------------------------------------------------------------------- /examples/auth.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::io::{self, Write}; 3 | 4 | use modio::{auth::Credentials, Modio}; 5 | 6 | fn prompt(prompt: &str) -> io::Result { 7 | print!("{}", prompt); 8 | io::stdout().flush()?; 9 | let mut buffer = String::new(); 10 | io::stdin().read_line(&mut buffer)?; 11 | Ok(buffer.trim().to_string()) 12 | } 13 | 14 | #[tokio::main] 15 | async fn main() -> Result<(), Box> { 16 | dotenv::dotenv().ok(); 17 | tracing_subscriber::fmt::init(); 18 | 19 | let host = env::var("MODIO_HOST").unwrap_or_else(|_| "https://api.test.mod.io/v1".to_string()); 20 | 21 | let api_key = prompt("Enter api key: ")?; 22 | let email = prompt("Enter email: ")?; 23 | 24 | let modio = Modio::host(host, Credentials::new(api_key))?; 25 | 26 | let terms = modio.auth().terms().await?; 27 | println!("Terms:\n{}\n", terms.plaintext); 28 | 29 | match &*prompt("Accept? [Y/n]: ")? { 30 | "" | "y" | "Y" => {} 31 | _ => return Ok(()), 32 | } 33 | 34 | modio.auth().request_code(&email).await?; 35 | 36 | let code = prompt("Enter security code: ").expect("read code"); 37 | let new_creds = modio.auth().security_code(&code).await?; 38 | if let Some(token) = &new_creds.token { 39 | println!("Access token:\n{}", token.value); 40 | } 41 | 42 | // Consume the endpoint and create an endpoint with new credentials. 43 | let modio = modio.with_credentials(new_creds); 44 | let user = modio.user().current().await?; 45 | println!("Authenticated user:\n{:#?}", user); 46 | 47 | Ok(()) 48 | } 49 | -------------------------------------------------------------------------------- /examples/details.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::process; 3 | 4 | use modio::filter::Filter; 5 | use modio::types::id::Id; 6 | use modio::{auth::Credentials, Modio}; 7 | 8 | #[tokio::main] 9 | async fn main() -> Result<(), Box> { 10 | dotenv::dotenv().ok(); 11 | tracing_subscriber::fmt::init(); 12 | 13 | // Fetch the access token / api key from the environment of the current process. 14 | let creds = match (env::var("MODIO_TOKEN"), env::var("MODIO_API_KEY")) { 15 | (Ok(token), Ok(apikey)) => Credentials::with_token(apikey, token), 16 | (_, Ok(apikey)) => Credentials::new(apikey), 17 | _ => { 18 | eprintln!("missing MODIO_TOKEN or MODIO_API_KEY environment variable"); 19 | process::exit(1); 20 | } 21 | }; 22 | let host = env::var("MODIO_HOST").unwrap_or_else(|_| "https://api.test.mod.io/v1".to_string()); 23 | 24 | // Creates a `Modio` endpoint for the test environment. 25 | let modio = Modio::host(host, creds)?; 26 | 27 | // OpenXcom: The X-Com Files 28 | let modref = modio.mod_(Id::new(51), Id::new(158)); 29 | 30 | // Get mod with its dependencies and all files 31 | let deps = modref.dependencies().list().await?; 32 | let files = modref.files().search(Filter::default()).collect().await?; 33 | let m = modref.get().await?; 34 | 35 | println!("{}, {}\n", m.name, m.profile_url); 36 | println!( 37 | "deps: {:?}", 38 | deps.into_iter().map(|d| d.mod_id).collect::>() 39 | ); 40 | println!( 41 | "stats: downloads={} subscribers={}\n", 42 | m.stats.downloads_total, m.stats.subscribers_total, 43 | ); 44 | let primary = m.modfile.as_ref().map(|f| f.id); 45 | println!("files:"); 46 | for file in files { 47 | let primary = if primary == Some(file.id) { "*" } else { " " }; 48 | println!("{} id: {} version: {:?}", primary, file.id, file.version); 49 | } 50 | Ok(()) 51 | } 52 | -------------------------------------------------------------------------------- /examples/download.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::io::{self, Write}; 3 | use std::process; 4 | 5 | use futures_util::TryStreamExt; 6 | 7 | use modio::types::id::Id; 8 | use modio::{auth::Credentials, Modio}; 9 | 10 | fn prompt(prompt: &str) -> io::Result { 11 | print!("{}", prompt); 12 | io::stdout().flush()?; 13 | let mut buffer = String::new(); 14 | io::stdin().read_line(&mut buffer)?; 15 | Ok(buffer.trim().parse().expect("Invalid value")) 16 | } 17 | 18 | #[tokio::main] 19 | async fn main() -> Result<(), Box> { 20 | dotenv::dotenv().ok(); 21 | tracing_subscriber::fmt::init(); 22 | 23 | // Fetch the access token / api key from the environment of the current process. 24 | let creds = match (env::var("MODIO_TOKEN"), env::var("MODIO_API_KEY")) { 25 | (Ok(token), Ok(apikey)) => Credentials::with_token(apikey, token), 26 | (_, Ok(apikey)) => Credentials::new(apikey), 27 | _ => { 28 | eprintln!("missing MODIO_TOKEN or MODIO_API_KEY environment variable"); 29 | process::exit(1); 30 | } 31 | }; 32 | let host = env::var("MODIO_HOST").unwrap_or_else(|_| "https://api.test.mod.io/v1".to_string()); 33 | 34 | // Creates a `Modio` endpoint for the test environment. 35 | let modio = Modio::host(host, creds)?; 36 | 37 | let game_id = Id::new(prompt("Enter game id: ")?); 38 | let mod_id = Id::new(prompt("Enter mod id: ")?); 39 | 40 | // Create the call for `/games/{game_id}/mods/{mod_id}` and wait for the result. 41 | let m = modio.mod_(game_id, mod_id).get().await?; 42 | if let Some(file) = m.modfile { 43 | // Download the file and calculate its md5 digest. 44 | let mut ctx = md5::Context::new(); 45 | let mut size = 0; 46 | 47 | println!("mod: {}", m.name); 48 | println!("url: {}", file.download.binary_url); 49 | println!("filename: {}", file.filename); 50 | println!("filesize: {}", file.filesize); 51 | println!("reported md5: {}", file.filehash.md5); 52 | 53 | let mut st = Box::pin(modio.download(file).await?.stream()); 54 | while let Some(bytes) = st.try_next().await? { 55 | size += bytes.len(); 56 | ctx.write_all(&bytes)?; 57 | } 58 | 59 | println!("computed md5: {:x}", ctx.compute()); 60 | println!("downloaded size: {}", size); 61 | } else { 62 | println!("The mod has no files."); 63 | } 64 | Ok(()) 65 | } 66 | -------------------------------------------------------------------------------- /examples/events.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::process; 3 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; 4 | 5 | use tokio::time::{self, Instant}; 6 | 7 | use modio::filter::prelude::*; 8 | use modio::{auth::Credentials, Modio}; 9 | 10 | const TEN_SECS: Duration = Duration::from_secs(10); 11 | 12 | fn current_timestamp() -> u64 { 13 | SystemTime::now() 14 | .duration_since(UNIX_EPOCH) 15 | .unwrap() 16 | .as_secs() 17 | } 18 | 19 | #[tokio::main] 20 | async fn main() -> Result<(), Box> { 21 | dotenv::dotenv().ok(); 22 | tracing_subscriber::fmt::init(); 23 | 24 | // Fetch the access token & api key from the environment of the current process. 25 | let creds = match (env::var("MODIO_TOKEN"), env::var("MODIO_API_KEY")) { 26 | (Ok(token), Ok(apikey)) => Credentials::with_token(apikey, token), 27 | _ => { 28 | eprintln!("missing MODIO_TOKEN and MODIO_API_KEY environment variable"); 29 | process::exit(1); 30 | } 31 | }; 32 | let host = env::var("MODIO_HOST").unwrap_or_else(|_| "https://api.test.mod.io/v1".to_string()); 33 | 34 | // Creates a `Modio` endpoint for the test environment. 35 | let modio = Modio::host(host, creds)?; 36 | 37 | // Creates an `Interval` that yields every 10 seconds starting in 10 seconds. 38 | let mut interval = time::interval_at(Instant::now() + TEN_SECS, TEN_SECS); 39 | 40 | loop { 41 | let tstamp = current_timestamp(); 42 | interval.tick().await; 43 | 44 | // Create an event filter for `date_added` > time. 45 | let filter = DateAdded::gt(tstamp); 46 | println!("event filter: {}", filter); 47 | 48 | let list: Vec<_> = modio.user().events(filter).collect().await?; 49 | 50 | println!("event count: {}", list.len()); 51 | println!("{:#?}", list); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /examples/mymods.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::process; 3 | 4 | use modio::filter::prelude::*; 5 | use modio::{auth::Credentials, Modio}; 6 | 7 | #[tokio::main] 8 | async fn main() -> Result<(), Box> { 9 | dotenv::dotenv().ok(); 10 | tracing_subscriber::fmt::init(); 11 | 12 | // Fetch the access token / api key from the environment of the current process. 13 | let creds = match (env::var("MODIO_TOKEN"), env::var("MODIO_API_KEY")) { 14 | (Ok(token), Ok(apikey)) => Credentials::with_token(apikey, token), 15 | _ => { 16 | eprintln!("missing MODIO_TOKEN and MODIO_API_KEY environment variable"); 17 | process::exit(1); 18 | } 19 | }; 20 | let host = env::var("MODIO_HOST").unwrap_or_else(|_| "https://api.test.mod.io/v1".to_string()); 21 | 22 | // Creates a `Modio` endpoint for the test environment. 23 | let modio = Modio::host(host, creds)?; 24 | 25 | // Create a mod filter for `id` in (1043, 1041), limited to 30 results 26 | // and ordered by `id` desc. 27 | let filter = Id::_in(vec![1043, 1041]) 28 | .limit(30) 29 | .offset(0) 30 | .order_by(Id::desc()); 31 | 32 | // Create the call for `/me/mods` and wait for the result. 33 | for mod_ in modio.user().mods(filter).collect().await? { 34 | println!("{:#?}", mod_); 35 | } 36 | Ok(()) 37 | } 38 | -------------------------------------------------------------------------------- /header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickelc/modio-rs/ed25ecaf3d2a5d1bb644ccb83fb0f850876e852c/header.png -------------------------------------------------------------------------------- /src/auth.rs: -------------------------------------------------------------------------------- 1 | //! Authentication Flow interface 2 | use std::collections::BTreeMap; 3 | use std::fmt; 4 | 5 | use crate::routing::Route; 6 | use crate::types::auth::AccessToken; 7 | use crate::types::{Message, Timestamp}; 8 | use crate::Modio; 9 | use crate::Result; 10 | 11 | pub use crate::types::auth::{Link, Links, Terms}; 12 | 13 | /// [mod.io](https://mod.io) credentials. API key with optional OAuth2 access token. 14 | #[derive(Clone, Eq, PartialEq)] 15 | pub struct Credentials { 16 | pub api_key: String, 17 | pub token: Option, 18 | } 19 | 20 | /// Access token and optional Unix timestamp of the date this token will expire. 21 | #[derive(Clone, Eq, PartialEq)] 22 | pub struct Token { 23 | pub value: String, 24 | pub expired_at: Option, 25 | } 26 | 27 | impl fmt::Debug for Credentials { 28 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 29 | if self.token.is_some() { 30 | f.write_str("Credentials(apikey+token)") 31 | } else { 32 | f.write_str("Credentials(apikey)") 33 | } 34 | } 35 | } 36 | 37 | impl Credentials { 38 | pub fn new>(api_key: S) -> Credentials { 39 | Credentials { 40 | api_key: api_key.into(), 41 | token: None, 42 | } 43 | } 44 | 45 | pub fn with_token, T: Into>(api_key: S, token: T) -> Credentials { 46 | Credentials { 47 | api_key: api_key.into(), 48 | token: Some(Token { 49 | value: token.into(), 50 | expired_at: None, 51 | }), 52 | } 53 | } 54 | } 55 | 56 | impl From<&str> for Credentials { 57 | fn from(api_key: &str) -> Credentials { 58 | Credentials::new(api_key) 59 | } 60 | } 61 | 62 | impl From<(&str, &str)> for Credentials { 63 | fn from((api_key, token): (&str, &str)) -> Credentials { 64 | Credentials::with_token(api_key, token) 65 | } 66 | } 67 | 68 | impl From for Credentials { 69 | fn from(api_key: String) -> Credentials { 70 | Credentials::new(api_key) 71 | } 72 | } 73 | 74 | impl From<(String, String)> for Credentials { 75 | fn from((api_key, token): (String, String)) -> Credentials { 76 | Credentials::with_token(api_key, token) 77 | } 78 | } 79 | 80 | /// Authentication Flow interface to retrieve access tokens. See the [mod.io Authentication 81 | /// docs](https://docs.mod.io/restapiref/#email-exchange) for more information. 82 | /// 83 | /// # Example 84 | /// ```no_run 85 | /// use std::io::{self, Write}; 86 | /// 87 | /// use modio::{Credentials, Modio, Result}; 88 | /// 89 | /// fn prompt(prompt: &str) -> io::Result { 90 | /// print!("{}", prompt); 91 | /// io::stdout().flush()?; 92 | /// let mut buffer = String::new(); 93 | /// io::stdin().read_line(&mut buffer)?; 94 | /// Ok(buffer.trim().to_string()) 95 | /// } 96 | /// 97 | /// #[tokio::main] 98 | /// async fn main() -> Result<()> { 99 | /// let modio = Modio::new(Credentials::new("api-key"))?; 100 | /// 101 | /// let email = prompt("Enter email: ").expect("read email"); 102 | /// modio.auth().request_code(&email).await?; 103 | /// 104 | /// let code = prompt("Enter security code: ").expect("read code"); 105 | /// let token = modio.auth().security_code(&code).await?; 106 | /// 107 | /// // Consume the endpoint and create an endpoint with new credentials. 108 | /// let _modio = modio.with_credentials(token); 109 | /// 110 | /// Ok(()) 111 | /// } 112 | /// ``` 113 | #[derive(Clone)] 114 | pub struct Auth { 115 | modio: Modio, 116 | } 117 | 118 | impl Auth { 119 | pub(crate) fn new(modio: Modio) -> Self { 120 | Self { modio } 121 | } 122 | 123 | /// Get text and links for user agreement and consent prior to authentication. [required: apikey] 124 | /// 125 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#terms) for more information. 126 | pub async fn terms(self) -> Result { 127 | self.modio.request(Route::Terms).send().await 128 | } 129 | 130 | /// Request a security code be sent to the email of the user. [required: apikey] 131 | pub async fn request_code(self, email: &str) -> Result<()> { 132 | self.modio 133 | .request(Route::OAuthEmailRequest) 134 | .form(&[("email", email)]) 135 | .send::() 136 | .await?; 137 | 138 | Ok(()) 139 | } 140 | 141 | /// Get the access token for a security code. [required: apikey] 142 | pub async fn security_code(self, code: &str) -> Result { 143 | let t = self 144 | .modio 145 | .request(Route::OAuthEmailExchange) 146 | .form(&[("security_code", code)]) 147 | .send::() 148 | .await?; 149 | 150 | let token = Token { 151 | value: t.value, 152 | expired_at: t.expired_at, 153 | }; 154 | Ok(Credentials { 155 | api_key: self.modio.inner.credentials.api_key.clone(), 156 | token: Some(token), 157 | }) 158 | } 159 | 160 | /// Authenticate via external services ([Steam], [Switch], [Xbox], [Discord], [Oculus], [Google]). 161 | /// 162 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#authentication-2) for more information. 163 | /// 164 | /// [Steam]: SteamOptions 165 | /// [Oculus]: OculusOptions 166 | /// [Switch]: SwitchOptions 167 | /// [Xbox]: XboxOptions 168 | /// [Discord]: DiscordOptions 169 | /// [Google]: GoogleOptions 170 | /// 171 | /// # Examples 172 | /// 173 | /// ```no_run 174 | /// # use modio::{Credentials, Modio, Result}; 175 | /// # #[tokio::main] 176 | /// # async fn run() -> Result<()> { 177 | /// # let modio = modio::Modio::new("apikey")?; 178 | /// use modio::auth::SteamOptions; 179 | /// let opts = SteamOptions::new("ticket"); 180 | /// modio.auth().external(opts).await?; 181 | /// # Ok(()) 182 | /// # } 183 | /// ``` 184 | pub async fn external(self, auth_options: T) -> Result 185 | where 186 | T: Into, 187 | { 188 | let AuthOptions { route, params } = auth_options.into(); 189 | 190 | let t = self 191 | .modio 192 | .request(route) 193 | .form(¶ms) 194 | .send::() 195 | .await?; 196 | 197 | let token = Token { 198 | value: t.value, 199 | expired_at: t.expired_at, 200 | }; 201 | Ok(Credentials { 202 | api_key: self.modio.inner.credentials.api_key.clone(), 203 | token: Some(token), 204 | }) 205 | } 206 | 207 | /// Logout by revoking the current access token. 208 | pub async fn logout(self) -> Result<()> { 209 | self.modio 210 | .request(Route::OAuthLogout) 211 | .send::() 212 | .await?; 213 | 214 | Ok(()) 215 | } 216 | } 217 | 218 | /// Options for external authentication. 219 | pub struct AuthOptions { 220 | route: Route, 221 | params: BTreeMap<&'static str, String>, 222 | } 223 | 224 | // impl From<*Options> for AuthOptions {{{ 225 | impl From for AuthOptions { 226 | fn from(options: OculusOptions) -> AuthOptions { 227 | AuthOptions { 228 | route: Route::ExternalAuthMeta, 229 | params: options.params, 230 | } 231 | } 232 | } 233 | 234 | impl From for AuthOptions { 235 | fn from(options: SteamOptions) -> AuthOptions { 236 | AuthOptions { 237 | route: Route::ExternalAuthSteam, 238 | params: options.params, 239 | } 240 | } 241 | } 242 | 243 | impl From for AuthOptions { 244 | fn from(options: SwitchOptions) -> AuthOptions { 245 | AuthOptions { 246 | route: Route::ExternalAuthSwitch, 247 | params: options.params, 248 | } 249 | } 250 | } 251 | 252 | impl From for AuthOptions { 253 | fn from(options: XboxOptions) -> AuthOptions { 254 | AuthOptions { 255 | route: Route::ExternalAuthXbox, 256 | params: options.params, 257 | } 258 | } 259 | } 260 | 261 | impl From for AuthOptions { 262 | fn from(options: DiscordOptions) -> AuthOptions { 263 | AuthOptions { 264 | route: Route::ExternalAuthDiscord, 265 | params: options.params, 266 | } 267 | } 268 | } 269 | 270 | impl From for AuthOptions { 271 | fn from(options: GoogleOptions) -> AuthOptions { 272 | AuthOptions { 273 | route: Route::ExternalAuthGoogle, 274 | params: options.params, 275 | } 276 | } 277 | } 278 | // }}} 279 | 280 | /// Authentication options for an encrypted gog app ticket. 281 | /// 282 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#gog-galaxy) for more information. 283 | pub struct GalaxyOptions { 284 | params: BTreeMap<&'static str, String>, 285 | } 286 | 287 | impl GalaxyOptions { 288 | pub fn new(ticket: T) -> Self 289 | where 290 | T: Into, 291 | { 292 | let mut params = BTreeMap::new(); 293 | params.insert("appdata", ticket.into()); 294 | Self { params } 295 | } 296 | 297 | option!(email >> "email"); 298 | option!( 299 | /// Unix timestamp of date in which the returned token will expire. Value cannot be higher 300 | /// than the default value which is a common year. 301 | expired_at u64 >> "date_expires" 302 | ); 303 | option!(terms_agreed bool >> "terms_agreed"); 304 | } 305 | 306 | /// Authentication options for an itch.io JWT token. 307 | /// 308 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#itch-io) for more information. 309 | pub struct ItchioOptions { 310 | params: BTreeMap<&'static str, String>, 311 | } 312 | 313 | impl ItchioOptions { 314 | pub fn new(token: T) -> Self 315 | where 316 | T: Into, 317 | { 318 | let mut params = BTreeMap::new(); 319 | params.insert("itchio_token", token.into()); 320 | Self { params } 321 | } 322 | 323 | option!(email >> "email"); 324 | option!( 325 | /// Unix timestamp of date in which the returned token will expire. Value cannot be higher 326 | /// than the default value which is a week. 327 | expired_at u64 >> "date_expires" 328 | ); 329 | option!(terms_agreed bool >> "terms_agreed"); 330 | } 331 | 332 | /// Authentication options for an Oculus user. 333 | /// 334 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#meta-quest) for more information. 335 | pub struct OculusOptions { 336 | params: BTreeMap<&'static str, String>, 337 | } 338 | 339 | impl OculusOptions { 340 | pub fn new_for_quest(nonce: T, user_id: u64, auth_token: T) -> Self 341 | where 342 | T: Into, 343 | { 344 | OculusOptions::new("quest".to_owned(), nonce.into(), user_id, auth_token.into()) 345 | } 346 | 347 | pub fn new_for_rift(nonce: T, user_id: u64, auth_token: T) -> Self 348 | where 349 | T: Into, 350 | { 351 | OculusOptions::new("rift".to_owned(), nonce.into(), user_id, auth_token.into()) 352 | } 353 | 354 | fn new(device: String, nonce: String, user_id: u64, auth_token: String) -> Self { 355 | let mut params = BTreeMap::new(); 356 | params.insert("device", device); 357 | params.insert("nonce", nonce); 358 | params.insert("user_id", user_id.to_string()); 359 | params.insert("auth_token", auth_token); 360 | Self { params } 361 | } 362 | 363 | option!(email >> "email"); 364 | option!( 365 | /// Unix timestamp of date in which the returned token will expire. Value cannot be higher 366 | /// than the default value which is a common year. 367 | expired_at u64 >> "date_expires" 368 | ); 369 | option!(terms_agreed bool >> "terms_agreed"); 370 | } 371 | 372 | /// Authentication options for an encrypted steam app ticket. 373 | /// 374 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#steam) for more information. 375 | pub struct SteamOptions { 376 | params: BTreeMap<&'static str, String>, 377 | } 378 | 379 | impl SteamOptions { 380 | pub fn new(ticket: T) -> Self 381 | where 382 | T: Into, 383 | { 384 | let mut params = BTreeMap::new(); 385 | params.insert("appdata", ticket.into()); 386 | Self { params } 387 | } 388 | 389 | option!(email >> "email"); 390 | option!( 391 | /// Unix timestamp of date in which the returned token will expire. Value cannot be higher 392 | /// than the default value which is a common year. 393 | expired_at u64 >> "date_expires" 394 | ); 395 | option!(terms_agreed bool >> "terms_agreed"); 396 | } 397 | 398 | /// Authentication options for the NSA ID token. 399 | /// 400 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#nintendo-switch) for more information. 401 | pub struct SwitchOptions { 402 | params: BTreeMap<&'static str, String>, 403 | } 404 | 405 | impl SwitchOptions { 406 | pub fn new(id_token: T) -> Self 407 | where 408 | T: Into, 409 | { 410 | let mut params = BTreeMap::new(); 411 | params.insert("id_token", id_token.into()); 412 | Self { params } 413 | } 414 | 415 | option!(email >> "email"); 416 | option!( 417 | /// Unix timestamp of date in which the returned token will expire. Value cannot be higher 418 | /// than the default value which is a common year. 419 | expired_at u64 >> "date_expires" 420 | ); 421 | option!(terms_agreed bool >> "terms_agreed"); 422 | } 423 | 424 | /// Authentication options for an Xbox Live token. 425 | /// 426 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#xbox-live) for more information. 427 | pub struct XboxOptions { 428 | params: BTreeMap<&'static str, String>, 429 | } 430 | 431 | impl XboxOptions { 432 | pub fn new(token: T) -> Self 433 | where 434 | T: Into, 435 | { 436 | let mut params = BTreeMap::new(); 437 | params.insert("xbox_token", token.into()); 438 | Self { params } 439 | } 440 | 441 | option!(email >> "email"); 442 | option!( 443 | /// Unix timestamp of date in which the returned token will expire. Value cannot be higher 444 | /// than the default value which is a common year. 445 | expired_at u64 >> "date_expires" 446 | ); 447 | option!(terms_agreed bool >> "terms_agreed"); 448 | } 449 | 450 | /// Authentication options for an Discord token. 451 | /// 452 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#discord) for more information. 453 | pub struct DiscordOptions { 454 | params: BTreeMap<&'static str, String>, 455 | } 456 | 457 | impl DiscordOptions { 458 | pub fn new(token: T) -> Self 459 | where 460 | T: Into, 461 | { 462 | let mut params = BTreeMap::new(); 463 | params.insert("discord_token", token.into()); 464 | Self { params } 465 | } 466 | 467 | option!(email >> "email"); 468 | option!( 469 | /// Unix timestamp of date in which the returned token will expire. Value cannot be higher 470 | /// than the default value which is a week. 471 | expired_at u64 >> "date_expires" 472 | ); 473 | option!(terms_agreed bool >> "terms_agreed"); 474 | } 475 | 476 | /// Authentication options for an Google token. 477 | /// 478 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#google) for more information. 479 | pub struct GoogleOptions { 480 | params: BTreeMap<&'static str, String>, 481 | } 482 | 483 | impl GoogleOptions { 484 | pub fn new(token: T) -> Self 485 | where 486 | T: Into, 487 | { 488 | let mut params = BTreeMap::new(); 489 | params.insert("id_token", token.into()); 490 | Self { params } 491 | } 492 | 493 | option!(email >> "email"); 494 | option!( 495 | /// Unix timestamp of date in which the returned token will expire. Value cannot be higher 496 | /// than the default value which is a week. 497 | expired_at u64 >> "date_expires" 498 | ); 499 | option!(terms_agreed bool >> "terms_agreed"); 500 | } 501 | 502 | // vim: fdm=marker 503 | -------------------------------------------------------------------------------- /src/client/builder.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use http::header::USER_AGENT; 4 | use http::header::{HeaderMap, HeaderValue}; 5 | use reqwest::{Client, ClientBuilder, Proxy}; 6 | 7 | use crate::auth::Credentials; 8 | use crate::error::{self, Error, Result}; 9 | use crate::{TargetPlatform, TargetPortal}; 10 | 11 | use super::{ClientRef, Modio}; 12 | use super::{DEFAULT_AGENT, DEFAULT_HOST, TEST_HOST}; 13 | 14 | /// A `Builder` can be used to create a `Modio` client with custom configuration. 15 | #[must_use] 16 | pub struct Builder { 17 | config: Config, 18 | } 19 | 20 | struct Config { 21 | host: Option, 22 | credentials: Credentials, 23 | builder: Option, 24 | headers: HeaderMap, 25 | proxies: Vec, 26 | #[cfg(feature = "__tls")] 27 | tls: TlsBackend, 28 | error: Option, 29 | } 30 | 31 | #[cfg(feature = "__tls")] 32 | enum TlsBackend { 33 | #[cfg(feature = "default-tls")] 34 | Default, 35 | #[cfg(feature = "rustls-tls")] 36 | Rustls, 37 | } 38 | 39 | #[cfg(feature = "__tls")] 40 | #[allow(clippy::derivable_impls)] 41 | impl Default for TlsBackend { 42 | fn default() -> TlsBackend { 43 | #[cfg(feature = "default-tls")] 44 | { 45 | TlsBackend::Default 46 | } 47 | #[cfg(all(feature = "rustls-tls", not(feature = "default-tls")))] 48 | { 49 | TlsBackend::Rustls 50 | } 51 | } 52 | } 53 | 54 | impl Builder { 55 | /// Constructs a new `Builder`. 56 | /// 57 | /// This is the same as `Modio::builder(credentials)`. 58 | pub fn new>(credentials: C) -> Builder { 59 | Builder { 60 | config: Config { 61 | host: None, 62 | credentials: credentials.into(), 63 | builder: None, 64 | headers: HeaderMap::new(), 65 | proxies: Vec::new(), 66 | #[cfg(feature = "__tls")] 67 | tls: TlsBackend::default(), 68 | error: None, 69 | }, 70 | } 71 | } 72 | 73 | /// Returns a `Modio` client that uses this `Builder` configuration. 74 | pub fn build(self) -> Result { 75 | let config = self.config; 76 | 77 | if let Some(e) = config.error { 78 | return Err(e); 79 | } 80 | 81 | let host = config.host.unwrap_or_else(|| DEFAULT_HOST.to_string()); 82 | let credentials = config.credentials; 83 | 84 | let client = { 85 | let mut builder = { 86 | let builder = config.builder.unwrap_or_else(Client::builder); 87 | #[cfg(feature = "__tls")] 88 | match config.tls { 89 | #[cfg(feature = "default-tls")] 90 | TlsBackend::Default => builder.use_native_tls(), 91 | #[cfg(feature = "rustls-tls")] 92 | TlsBackend::Rustls => builder.use_rustls_tls(), 93 | } 94 | 95 | #[cfg(not(feature = "__tls"))] 96 | builder 97 | }; 98 | 99 | let mut headers = config.headers; 100 | if !headers.contains_key(USER_AGENT) { 101 | headers.insert(USER_AGENT, HeaderValue::from_static(DEFAULT_AGENT)); 102 | } 103 | 104 | for proxy in config.proxies { 105 | builder = builder.proxy(proxy); 106 | } 107 | 108 | builder 109 | .default_headers(headers) 110 | .build() 111 | .map_err(error::builder)? 112 | }; 113 | 114 | Ok(Modio { 115 | inner: Arc::new(ClientRef { 116 | host, 117 | client, 118 | credentials, 119 | }), 120 | }) 121 | } 122 | 123 | /// Configure the underlying `reqwest` client using `reqwest::ClientBuilder`. 124 | pub fn client(mut self, f: F) -> Builder 125 | where 126 | F: FnOnce(ClientBuilder) -> ClientBuilder, 127 | { 128 | self.config.builder = Some(f(Client::builder())); 129 | self 130 | } 131 | 132 | /// Set the mod.io api host. 133 | /// 134 | /// Defaults to `"https://api.mod.io/v1"` 135 | pub fn host>(mut self, host: S) -> Builder { 136 | self.config.host = Some(host.into()); 137 | self 138 | } 139 | 140 | /// Use the mod.io api test host. 141 | pub fn use_test(mut self) -> Builder { 142 | self.config.host = Some(TEST_HOST.into()); 143 | self 144 | } 145 | 146 | /// Set the user agent used for every request. 147 | /// 148 | /// Defaults to `"modio/{version}"` 149 | pub fn user_agent(mut self, value: V) -> Builder 150 | where 151 | V: TryInto, 152 | V::Error: Into, 153 | { 154 | match value.try_into() { 155 | Ok(value) => { 156 | self.config.headers.insert(USER_AGENT, value); 157 | } 158 | Err(e) => { 159 | self.config.error = Some(error::builder(e.into())); 160 | } 161 | } 162 | self 163 | } 164 | 165 | /// Add a `Proxy` to the list of proxies the client will use. 166 | pub fn proxy(mut self, proxy: Proxy) -> Builder { 167 | self.config.proxies.push(proxy); 168 | self 169 | } 170 | 171 | /// Set the target platform. 172 | /// 173 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#targeting-a-platform) for more information. 174 | pub fn target_platform(mut self, platform: TargetPlatform) -> Builder { 175 | match HeaderValue::from_str(platform.as_str()) { 176 | Ok(value) => { 177 | self.config.headers.insert("X-Modio-Platform", value); 178 | } 179 | Err(e) => { 180 | self.config.error = Some(error::builder(e)); 181 | } 182 | } 183 | self 184 | } 185 | 186 | /// Set the target portal. 187 | /// 188 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#targeting-a-portal) for more information. 189 | pub fn target_portal(mut self, portal: TargetPortal) -> Builder { 190 | match HeaderValue::from_str(portal.as_str()) { 191 | Ok(value) => { 192 | self.config.headers.insert("X-Modio-Portal", value); 193 | } 194 | Err(e) => { 195 | self.config.error = Some(error::builder(e)); 196 | } 197 | } 198 | self 199 | } 200 | 201 | /// Use native TLS backend. 202 | #[cfg(feature = "default-tls")] 203 | pub fn use_default_tls(mut self) -> Builder { 204 | self.config.tls = TlsBackend::Default; 205 | self 206 | } 207 | 208 | /// Use rustls TLS backend. 209 | #[cfg(feature = "rustls-tls")] 210 | pub fn use_rustls_tls(mut self) -> Builder { 211 | self.config.tls = TlsBackend::Rustls; 212 | self 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /src/client/mod.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use reqwest::Client; 4 | 5 | use crate::auth::{Auth, Credentials, Token}; 6 | use crate::download::{DownloadAction, Downloader}; 7 | use crate::error::Result; 8 | use crate::games::{GameRef, Games}; 9 | use crate::mods::ModRef; 10 | use crate::reports::Reports; 11 | use crate::request::RequestBuilder; 12 | use crate::routing::Route; 13 | use crate::types::id::{GameId, ModId}; 14 | use crate::user::Me; 15 | 16 | mod builder; 17 | 18 | pub use builder::Builder; 19 | 20 | const DEFAULT_HOST: &str = "https://api.mod.io/v1"; 21 | const TEST_HOST: &str = "https://api.test.mod.io/v1"; 22 | const DEFAULT_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), '/', env!("CARGO_PKG_VERSION")); 23 | 24 | /// Endpoint interface to interacting with the [mod.io](https://mod.io) API. 25 | #[derive(Clone, Debug)] 26 | pub struct Modio { 27 | pub(crate) inner: Arc, 28 | } 29 | 30 | #[derive(Debug)] 31 | pub(crate) struct ClientRef { 32 | pub(crate) host: String, 33 | pub(crate) client: Client, 34 | pub(crate) credentials: Credentials, 35 | } 36 | 37 | impl Modio { 38 | /// Constructs a new `Builder` to configure a `Modio` client. 39 | /// 40 | /// This is the same as `Builder::new(credentials)`. 41 | pub fn builder>(credentials: C) -> Builder { 42 | Builder::new(credentials) 43 | } 44 | 45 | /// Create an endpoint to [https://api.mod.io/v1](https://docs.mod.io/restapiref/#mod-io-api-v1). 46 | pub fn new(credentials: C) -> Result 47 | where 48 | C: Into, 49 | { 50 | Builder::new(credentials).build() 51 | } 52 | 53 | /// Create an endpoint to a different host. 54 | pub fn host(host: H, credentials: C) -> Result 55 | where 56 | H: Into, 57 | C: Into, 58 | { 59 | Builder::new(credentials).host(host).build() 60 | } 61 | 62 | /// Return an endpoint with new credentials. 63 | #[must_use] 64 | pub fn with_credentials(&self, credentials: CR) -> Self 65 | where 66 | CR: Into, 67 | { 68 | Self { 69 | inner: Arc::new(ClientRef { 70 | host: self.inner.host.clone(), 71 | client: self.inner.client.clone(), 72 | credentials: credentials.into(), 73 | }), 74 | } 75 | } 76 | 77 | /// Return an endpoint with a new token. 78 | #[must_use] 79 | pub fn with_token(&self, token: T) -> Self 80 | where 81 | T: Into, 82 | { 83 | Self { 84 | inner: Arc::new(ClientRef { 85 | host: self.inner.host.clone(), 86 | client: self.inner.client.clone(), 87 | credentials: Credentials { 88 | api_key: self.inner.credentials.api_key.clone(), 89 | token: Some(token.into()), 90 | }, 91 | }), 92 | } 93 | } 94 | 95 | /// Return a reference to an interface for requesting access tokens. 96 | pub fn auth(&self) -> Auth { 97 | Auth::new(self.clone()) 98 | } 99 | 100 | /// Return a reference to an interface that provides access to game information. 101 | pub fn games(&self) -> Games { 102 | Games::new(self.clone()) 103 | } 104 | 105 | /// Return a reference to a game. 106 | pub fn game(&self, game_id: GameId) -> GameRef { 107 | GameRef::new(self.clone(), game_id) 108 | } 109 | 110 | /// Return a reference to a mod. 111 | pub fn mod_(&self, game_id: GameId, mod_id: ModId) -> ModRef { 112 | ModRef::new(self.clone(), game_id, mod_id) 113 | } 114 | 115 | /// Returns [`Downloader`] for saving to file or retrieving 116 | /// the data via [`Stream`]. 117 | /// 118 | /// The download fails with [`modio::download::Error`] as source 119 | /// if a primary file, a specific file or a specific version is not found. 120 | /// 121 | /// [`Downloader`]: crate::download::Downloader 122 | /// [`modio::download::Error`]: crate::download::Error 123 | /// [`Stream`]: futures_util::Stream 124 | /// 125 | /// # Example 126 | /// ```no_run 127 | /// use futures_util::{future, TryStreamExt}; 128 | /// use modio::download::{DownloadAction, ResolvePolicy}; 129 | /// use modio::types::id::Id; 130 | /// # async fn run() -> Result<(), Box> { 131 | /// # let modio = modio::Modio::new("user-or-game-api-key")?; 132 | /// 133 | /// // Download the primary file of a mod. 134 | /// let action = DownloadAction::Primary { 135 | /// game_id: Id::new(5), 136 | /// mod_id: Id::new(19), 137 | /// }; 138 | /// modio 139 | /// .download(action) 140 | /// .await? 141 | /// .save_to_file("mod.zip") 142 | /// .await?; 143 | /// 144 | /// // Download the specific file of a mod. 145 | /// let action = DownloadAction::File { 146 | /// game_id: Id::new(5), 147 | /// mod_id: Id::new(19), 148 | /// file_id: Id::new(101), 149 | /// }; 150 | /// modio 151 | /// .download(action) 152 | /// .await? 153 | /// .save_to_file("mod.zip") 154 | /// .await?; 155 | /// 156 | /// // Download the specific version of a mod. 157 | /// // if multiple files are found then the latest file is downloaded. 158 | /// // Set policy to `ResolvePolicy::Fail` to return with 159 | /// // `modio::download::Error::MultipleFilesFound` as source error. 160 | /// let action = DownloadAction::Version { 161 | /// game_id: Id::new(5), 162 | /// mod_id: Id::new(19), 163 | /// version: "0.1".to_string(), 164 | /// policy: ResolvePolicy::Latest, 165 | /// }; 166 | /// modio 167 | /// .download(action) 168 | /// .await? 169 | /// .stream() 170 | /// .try_for_each(|bytes| { 171 | /// println!("Bytes: {:?}", bytes); 172 | /// future::ok(()) 173 | /// }) 174 | /// .await?; 175 | /// # Ok(()) 176 | /// # } 177 | /// ``` 178 | pub async fn download(&self, action: A) -> Result 179 | where 180 | DownloadAction: From, 181 | { 182 | Downloader::new(self.clone(), action.into()).await 183 | } 184 | 185 | /// Return a reference to an interface that provides access to resources owned by the user 186 | /// associated with the current authentication credentials. 187 | pub fn user(&self) -> Me { 188 | Me::new(self.clone()) 189 | } 190 | 191 | /// Return a reference to an interface to report games, mods and users. 192 | pub fn reports(&self) -> Reports { 193 | Reports::new(self.clone()) 194 | } 195 | 196 | pub(crate) fn request(&self, route: Route) -> RequestBuilder { 197 | RequestBuilder::new(self.clone(), route) 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /src/comments.rs: -------------------------------------------------------------------------------- 1 | //! Mod comments interface 2 | 3 | use serde::ser::{Serialize, SerializeMap, Serializer}; 4 | use serde_derive::Serialize; 5 | 6 | use crate::prelude::*; 7 | use crate::types::id::{CommentId, GameId, ModId}; 8 | pub use crate::types::mods::Comment; 9 | 10 | /// Interface for comments of a mod. 11 | #[derive(Clone)] 12 | pub struct Comments { 13 | modio: Modio, 14 | game: GameId, 15 | mod_id: ModId, 16 | } 17 | 18 | impl Comments { 19 | pub(crate) fn new(modio: Modio, game: GameId, mod_id: ModId) -> Self { 20 | Self { 21 | modio, 22 | game, 23 | mod_id, 24 | } 25 | } 26 | 27 | /// Returns a `Query` interface to retrieve all comments. 28 | /// 29 | /// See [Filters and sorting](filters). 30 | pub fn search(&self, filter: Filter) -> Query { 31 | let route = Route::GetModComments { 32 | game_id: self.game, 33 | mod_id: self.mod_id, 34 | }; 35 | Query::new(self.modio.clone(), route, filter) 36 | } 37 | 38 | /// Return comment by id. 39 | pub async fn get(self, id: CommentId) -> Result { 40 | let route = Route::GetModComment { 41 | game_id: self.game, 42 | mod_id: self.mod_id, 43 | comment_id: id, 44 | }; 45 | self.modio.request(route).send().await 46 | } 47 | 48 | /// Add a new comment. [required: token] 49 | pub async fn add(self, content: S, reply_id: Option) -> Result 50 | where 51 | S: Into, 52 | { 53 | let route = Route::AddModComment { 54 | game_id: self.game, 55 | mod_id: self.mod_id, 56 | }; 57 | let content = content.into(); 58 | let data = CommentOptions { content, reply_id }; 59 | self.modio.request(route).form(&data).send().await 60 | } 61 | 62 | /// Edit a comment by id. [required: token] 63 | pub async fn edit(self, id: CommentId, content: S) -> Result 64 | where 65 | S: Into, 66 | { 67 | let route = Route::EditModComment { 68 | game_id: self.game, 69 | mod_id: self.mod_id, 70 | comment_id: id, 71 | }; 72 | let data = CommentOptions { 73 | content: content.into(), 74 | reply_id: None, 75 | }; 76 | self.modio.request(route).form(&data).send().await 77 | } 78 | 79 | /// Delete a comment by id. [required: token] 80 | pub async fn delete(self, id: CommentId) -> Result<()> { 81 | let route = Route::DeleteModComment { 82 | game_id: self.game, 83 | mod_id: self.mod_id, 84 | comment_id: id, 85 | }; 86 | self.modio.request(route).send().await 87 | } 88 | 89 | /// Update the karma for a comment. [required: token] 90 | pub async fn karma(self, id: CommentId, karma: Karma) -> Result> { 91 | let route = Route::AddModCommentKarma { 92 | game_id: self.game, 93 | mod_id: self.mod_id, 94 | comment_id: id, 95 | }; 96 | self.modio 97 | .request(route) 98 | .form(&karma) 99 | .send() 100 | .await 101 | .map(Editing::Entity) 102 | .or_else(|e| match (e.status(), e.error_ref()) { 103 | (Some(StatusCode::FORBIDDEN), Some(15059)) => Ok(Editing::NoChanges), 104 | _ => Err(e), 105 | }) 106 | } 107 | } 108 | 109 | /// Comment filters and sorting. 110 | /// 111 | /// # Filters 112 | /// - `Fulltext` 113 | /// - `Id` 114 | /// - `ModId` 115 | /// - `SubmittedBy` 116 | /// - `DateAdded` 117 | /// - `ReplyId` 118 | /// - `ThreadPosition` 119 | /// - `Karma` 120 | /// - `Content` 121 | /// 122 | /// # Sorting 123 | /// - `Id` 124 | /// - `ModId` 125 | /// - `SubmittedBy` 126 | /// - `DateAdded` 127 | /// 128 | /// See [modio docs](https://docs.mod.io/restapiref/#get-mod-comments) for more information. 129 | /// 130 | /// By default this returns up to `100` items. You can limit the result by using `limit` and 131 | /// `offset`. 132 | /// 133 | /// # Example 134 | /// ``` 135 | /// use modio::filter::prelude::*; 136 | /// use modio::comments::filters::Id; 137 | /// 138 | /// let filter = Id::_in(vec![1, 2]).order_by(Id::desc()); 139 | /// ``` 140 | #[rustfmt::skip] 141 | pub mod filters { 142 | #[doc(inline)] 143 | pub use crate::filter::prelude::Fulltext; 144 | #[doc(inline)] 145 | pub use crate::filter::prelude::Id; 146 | #[doc(inline)] 147 | pub use crate::filter::prelude::ModId; 148 | #[doc(inline)] 149 | pub use crate::filter::prelude::DateAdded; 150 | #[doc(inline)] 151 | pub use crate::filter::prelude::SubmittedBy; 152 | 153 | filter!(ReplyId, REPLY_ID, "reply_id", Eq, NotEq, In, Cmp); 154 | filter!(ThreadPosition, THREAD_POSITION, "thread_position", Eq, NotEq, In, Like); 155 | filter!(Karma, KARMA, "karma", Eq, NotEq, In, Cmp); 156 | filter!(Content, CONTENT, "content", Eq, NotEq, Like); 157 | } 158 | 159 | pub enum Karma { 160 | Positive, 161 | Negative, 162 | } 163 | 164 | impl Serialize for Karma { 165 | fn serialize(&self, serializer: S) -> Result { 166 | let mut s = serializer.serialize_map(Some(1))?; 167 | match self { 168 | Self::Positive => s.serialize_entry("karma", &1)?, 169 | Self::Negative => s.serialize_entry("karma", &-1)?, 170 | } 171 | s.end() 172 | } 173 | } 174 | 175 | #[derive(Serialize)] 176 | struct CommentOptions { 177 | content: String, 178 | #[serde(skip_serializing_if = "Option::is_none")] 179 | reply_id: Option, 180 | } 181 | -------------------------------------------------------------------------------- /src/download.rs: -------------------------------------------------------------------------------- 1 | //! Downloading mod files. 2 | use std::error::Error as StdError; 3 | use std::fmt; 4 | use std::path::Path; 5 | 6 | use bytes::Bytes; 7 | use futures_util::{SinkExt, Stream, StreamExt, TryFutureExt, TryStreamExt}; 8 | use reqwest::{Method, Response, StatusCode}; 9 | use tokio::fs::File as AsyncFile; 10 | use tokio::io::BufWriter; 11 | use tokio_util::codec::{BytesCodec, FramedWrite}; 12 | use tracing::debug; 13 | 14 | use crate::error::{self, Result}; 15 | use crate::types::files::File; 16 | use crate::types::id::{FileId, GameId, ModId}; 17 | use crate::types::mods::Mod; 18 | use crate::Modio; 19 | 20 | /// A `Downloader` can be used to stream a mod file or save the file to a local file. 21 | /// Constructed with [`Modio::download`]. 22 | pub struct Downloader(Response); 23 | 24 | impl Downloader { 25 | pub(crate) async fn new(modio: Modio, action: DownloadAction) -> Result { 26 | Ok(Self(request_file(modio, action).await?)) 27 | } 28 | 29 | /// Save the mod file to a local file. 30 | /// 31 | /// # Example 32 | /// ```no_run 33 | /// # use modio::types::id::Id; 34 | /// # async fn run() -> Result<(), Box> { 35 | /// # let modio = modio::Modio::new("api-key")?; 36 | /// let action = modio::DownloadAction::Primary { 37 | /// game_id: Id::new(5), 38 | /// mod_id: Id::new(19), 39 | /// }; 40 | /// 41 | /// modio 42 | /// .download(action) 43 | /// .await? 44 | /// .save_to_file("mod.zip") 45 | /// .await?; 46 | /// # Ok(()) 47 | /// # } 48 | /// ``` 49 | pub async fn save_to_file>(self, file: P) -> Result<()> { 50 | let out = AsyncFile::create(file).map_err(error::decode).await?; 51 | let out = BufWriter::with_capacity(512 * 512, out); 52 | let out = FramedWrite::new(out, BytesCodec::new()); 53 | let out = SinkExt::::sink_map_err(out, error::decode); 54 | self.stream().forward(out).await 55 | } 56 | 57 | /// Get the full mod file as `Bytes`. 58 | /// 59 | /// # Example 60 | /// ```no_run 61 | /// # use modio::types::id::Id; 62 | /// # async fn run() -> Result<(), Box> { 63 | /// # let modio = modio::Modio::new("api-key")?; 64 | /// let action = modio::DownloadAction::Primary { 65 | /// game_id: Id::new(5), 66 | /// mod_id: Id::new(19), 67 | /// }; 68 | /// 69 | /// let bytes = modio.download(action).await?.bytes().await?; 70 | /// # Ok(()) 71 | /// # } 72 | /// ``` 73 | pub async fn bytes(self) -> Result { 74 | self.0.bytes().map_err(error::request).await 75 | } 76 | 77 | /// `Stream` of bytes of the mod file. 78 | /// 79 | /// # Example 80 | /// ```no_run 81 | /// use futures_util::TryStreamExt; 82 | /// 83 | /// # use modio::types::id::Id; 84 | /// # async fn run() -> Result<(), Box> { 85 | /// # let modio = modio::Modio::new("api-key")?; 86 | /// let action = modio::DownloadAction::Primary { 87 | /// game_id: Id::new(5), 88 | /// mod_id: Id::new(19), 89 | /// }; 90 | /// 91 | /// let mut st = Box::pin(modio.download(action).await?.stream()); 92 | /// while let Some(bytes) = st.try_next().await? { 93 | /// println!("Bytes: {:?}", bytes); 94 | /// } 95 | /// # Ok(()) 96 | /// # } 97 | /// ``` 98 | pub fn stream(self) -> impl Stream> { 99 | self.0.bytes_stream().map_err(error::request) 100 | } 101 | 102 | /// Get the content length from the mod file response. 103 | /// 104 | /// # Example 105 | /// ```no_run 106 | /// # use modio::types::id::Id; 107 | /// # async fn run() -> Result<(), Box> { 108 | /// # let modio = modio::Modio::new("api-key")?; 109 | /// let action = modio::DownloadAction::Primary { 110 | /// game_id: Id::new(5), 111 | /// mod_id: Id::new(19), 112 | /// }; 113 | /// 114 | /// let content_length = modio 115 | /// .download(action) 116 | /// .await? 117 | /// .content_length() 118 | /// .expect("mod file response should have content length"); 119 | /// # Ok(()) 120 | /// # } 121 | /// ``` 122 | pub fn content_length(&self) -> Option { 123 | self.0.content_length() 124 | } 125 | } 126 | 127 | async fn request_file(modio: Modio, action: DownloadAction) -> Result { 128 | let url = match action { 129 | DownloadAction::Primary { game_id, mod_id } => { 130 | let modref = modio.mod_(game_id, mod_id); 131 | let m = modref 132 | .get() 133 | .map_err(|e| match e.status() { 134 | Some(StatusCode::NOT_FOUND) => { 135 | let source = Error::ModNotFound { game_id, mod_id }; 136 | error::download(source) 137 | } 138 | _ => e, 139 | }) 140 | .await?; 141 | if let Some(file) = m.modfile { 142 | file.download.binary_url 143 | } else { 144 | let source = Error::NoPrimaryFile { game_id, mod_id }; 145 | return Err(error::download(source)); 146 | } 147 | } 148 | DownloadAction::FileObj(file) => file.download.binary_url, 149 | DownloadAction::File { 150 | game_id, 151 | mod_id, 152 | file_id, 153 | } => { 154 | let fileref = modio.mod_(game_id, mod_id).file(file_id); 155 | let file = fileref 156 | .get() 157 | .map_err(|e| match e.status() { 158 | Some(StatusCode::NOT_FOUND) => { 159 | let source = Error::FileNotFound { 160 | game_id, 161 | mod_id, 162 | file_id, 163 | }; 164 | error::download(source) 165 | } 166 | _ => e, 167 | }) 168 | .await?; 169 | file.download.binary_url 170 | } 171 | DownloadAction::Version { 172 | game_id, 173 | mod_id, 174 | version, 175 | policy, 176 | } => { 177 | use crate::files::filters::Version; 178 | use crate::filter::prelude::*; 179 | use ResolvePolicy::*; 180 | 181 | let filter = Version::eq(version.clone()) 182 | .order_by(DateAdded::desc()) 183 | .limit(2); 184 | 185 | let files = modio.mod_(game_id, mod_id).files(); 186 | let mut list = files 187 | .search(filter) 188 | .first_page() 189 | .map_err(|e| match e.status() { 190 | Some(StatusCode::NOT_FOUND) => { 191 | let source = Error::ModNotFound { game_id, mod_id }; 192 | error::download(source) 193 | } 194 | _ => e, 195 | }) 196 | .await?; 197 | 198 | let (file, error) = match (list.len(), policy) { 199 | (0, _) => ( 200 | None, 201 | Some(Error::VersionNotFound { 202 | game_id, 203 | mod_id, 204 | version, 205 | }), 206 | ), 207 | (1, _) | (_, Latest) => (Some(list.remove(0)), None), 208 | (_, Fail) => ( 209 | None, 210 | Some(Error::MultipleFilesFound { 211 | game_id, 212 | mod_id, 213 | version, 214 | }), 215 | ), 216 | }; 217 | 218 | if let Some(file) = file { 219 | file.download.binary_url 220 | } else { 221 | let source = error.expect("bug in previous match!"); 222 | return Err(error::download(source)); 223 | } 224 | } 225 | }; 226 | 227 | debug!("downloading file: {}", url); 228 | modio 229 | .inner 230 | .client 231 | .request(Method::GET, url) 232 | .send() 233 | .map_err(error::builder_or_request) 234 | .await? 235 | .error_for_status() 236 | .map_err(error::request) 237 | } 238 | 239 | /// Defines the action that is performed for [`Modio::download`]. 240 | #[derive(Debug)] 241 | pub enum DownloadAction { 242 | /// Download the primary modfile of a mod. 243 | Primary { game_id: GameId, mod_id: ModId }, 244 | /// Download a specific modfile of a mod. 245 | File { 246 | game_id: GameId, 247 | mod_id: ModId, 248 | file_id: FileId, 249 | }, 250 | /// Download a specific modfile. 251 | FileObj(Box), 252 | /// Download a specific version of a mod. 253 | Version { 254 | game_id: GameId, 255 | mod_id: ModId, 256 | version: String, 257 | policy: ResolvePolicy, 258 | }, 259 | } 260 | 261 | /// Defines the policy for `DownloadAction::Version` when multiple files are found. 262 | #[derive(Debug)] 263 | pub enum ResolvePolicy { 264 | /// Download the latest file. 265 | Latest, 266 | /// Return with [`Error::MultipleFilesFound`] as source error. 267 | Fail, 268 | } 269 | 270 | /// The Errors that may occur when using [`Modio::download`]. 271 | #[derive(Debug)] 272 | pub enum Error { 273 | /// The mod has not found. 274 | ModNotFound { game_id: GameId, mod_id: ModId }, 275 | /// The mod has no primary file. 276 | NoPrimaryFile { game_id: GameId, mod_id: ModId }, 277 | /// The specific file of a mod was not found. 278 | FileNotFound { 279 | game_id: GameId, 280 | mod_id: ModId, 281 | file_id: FileId, 282 | }, 283 | /// Multiple files for a given version were found and the policy was set to 284 | /// [`ResolvePolicy::Fail`]. 285 | MultipleFilesFound { 286 | game_id: GameId, 287 | mod_id: ModId, 288 | version: String, 289 | }, 290 | /// No file for a given version was found. 291 | VersionNotFound { 292 | game_id: GameId, 293 | mod_id: ModId, 294 | version: String, 295 | }, 296 | } 297 | 298 | impl StdError for Error {} 299 | 300 | impl fmt::Display for Error { 301 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { 302 | match self { 303 | Error::ModNotFound { game_id, mod_id } => write!( 304 | fmt, 305 | "Mod {{id: {mod_id}, game_id: {game_id}}} not found.", 306 | ), 307 | Error::FileNotFound { 308 | game_id, 309 | mod_id, 310 | file_id, 311 | } => write!( 312 | fmt, 313 | "Mod {{id: {mod_id}, game_id: {game_id}}}: File {{ id: {file_id} }} not found.", 314 | ), 315 | Error::MultipleFilesFound { 316 | game_id, 317 | mod_id, 318 | version, 319 | } => write!( 320 | fmt, 321 | "Mod {{id: {mod_id}, game_id: {game_id}}}: Multiple files found for version '{version}'.", 322 | ), 323 | Error::NoPrimaryFile { game_id, mod_id } => write!( 324 | fmt, 325 | "Mod {{id: {mod_id}, game_id: {game_id}}} Mod has no primary file.", 326 | ), 327 | Error::VersionNotFound { 328 | game_id, 329 | mod_id, 330 | version, 331 | } => write!( 332 | fmt, 333 | "Mod {{id: {mod_id}, game_id: {game_id}}}: No file with version '{version}' found.", 334 | ), 335 | } 336 | } 337 | } 338 | 339 | /// Convert `Mod` to [`DownloadAction::File`] or [`DownloadAction::Primary`] if `Mod::modfile` is `None` 340 | impl From for DownloadAction { 341 | fn from(m: Mod) -> DownloadAction { 342 | if let Some(file) = m.modfile { 343 | DownloadAction::from(file) 344 | } else { 345 | DownloadAction::Primary { 346 | game_id: m.game_id, 347 | mod_id: m.id, 348 | } 349 | } 350 | } 351 | } 352 | 353 | /// Convert `File` to [`DownloadAction::FileObj`] 354 | impl From for DownloadAction { 355 | fn from(file: File) -> DownloadAction { 356 | DownloadAction::FileObj(Box::new(file)) 357 | } 358 | } 359 | 360 | /// Convert `(GameId, ModId)` to [`DownloadAction::Primary`] 361 | impl From<(GameId, ModId)> for DownloadAction { 362 | fn from((game_id, mod_id): (GameId, ModId)) -> DownloadAction { 363 | DownloadAction::Primary { game_id, mod_id } 364 | } 365 | } 366 | 367 | /// Convert `(GameId, ModId, FileId)` to [`DownloadAction::File`] 368 | impl From<(GameId, ModId, FileId)> for DownloadAction { 369 | fn from((game_id, mod_id, file_id): (GameId, ModId, FileId)) -> DownloadAction { 370 | DownloadAction::File { 371 | game_id, 372 | mod_id, 373 | file_id, 374 | } 375 | } 376 | } 377 | 378 | /// Convert `(GameId, ModId, String)` to [`DownloadAction::Version`] with resolve policy 379 | /// set to `ResolvePolicy::Latest` 380 | impl From<(GameId, ModId, String)> for DownloadAction { 381 | fn from((game_id, mod_id, version): (GameId, ModId, String)) -> DownloadAction { 382 | DownloadAction::Version { 383 | game_id, 384 | mod_id, 385 | version, 386 | policy: ResolvePolicy::Latest, 387 | } 388 | } 389 | } 390 | 391 | /// Convert `(GameId, ModId, &'a str)` to [`DownloadAction::Version`] with resolve policy 392 | /// set to `ResolvePolicy::Latest` 393 | impl<'a> From<(GameId, ModId, &'a str)> for DownloadAction { 394 | fn from((game_id, mod_id, version): (GameId, ModId, &'a str)) -> DownloadAction { 395 | DownloadAction::Version { 396 | game_id, 397 | mod_id, 398 | version: version.to_string(), 399 | policy: ResolvePolicy::Latest, 400 | } 401 | } 402 | } 403 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | //! Client errors 2 | use std::error::Error as StdError; 3 | use std::fmt; 4 | use std::time::Duration; 5 | 6 | use reqwest::StatusCode; 7 | 8 | use crate::types::Error as ApiError; 9 | 10 | /// A `Result` alias where the `Err` case is `modio::Error`. 11 | pub type Result = std::result::Result; 12 | 13 | /// The Errors that may occur when using `Modio`. 14 | pub struct Error { 15 | inner: Box, 16 | } 17 | 18 | type BoxError = Box; 19 | 20 | struct Inner { 21 | kind: Kind, 22 | error_ref: Option, 23 | source: Option, 24 | } 25 | 26 | impl Error { 27 | #[inline] 28 | pub(crate) fn new(kind: Kind) -> Self { 29 | Self { 30 | inner: Box::new(Inner { 31 | kind, 32 | error_ref: None, 33 | source: None, 34 | }), 35 | } 36 | } 37 | 38 | #[inline] 39 | pub(crate) fn with>(mut self, source: E) -> Self { 40 | self.inner.source = Some(source.into()); 41 | self 42 | } 43 | 44 | #[inline] 45 | pub(crate) fn with_error_ref(mut self, error_ref: u16) -> Self { 46 | self.inner.error_ref = Some(error_ref); 47 | self 48 | } 49 | 50 | /// Returns true if the API key/access token is incorrect, revoked, expired or the request 51 | /// needs a different authentication method. 52 | pub fn is_auth(&self) -> bool { 53 | matches!(self.inner.kind, Kind::Unauthorized | Kind::TokenRequired) 54 | } 55 | 56 | /// Returns true if the acceptance of the Terms of Use is required before continuing external 57 | /// authorization. 58 | pub fn is_terms_acceptance_required(&self) -> bool { 59 | matches!(self.inner.kind, Kind::TermsAcceptanceRequired) 60 | } 61 | 62 | /// Returns true if the error is from a type Builder. 63 | pub fn is_builder(&self) -> bool { 64 | matches!(self.inner.kind, Kind::Builder) 65 | } 66 | 67 | /// Returns true if the error is from a [`DownloadAction`](crate::download::DownloadAction). 68 | pub fn is_download(&self) -> bool { 69 | matches!(self.inner.kind, Kind::Download) 70 | } 71 | 72 | /// Returns true if the rate limit associated with credentials has been exhausted. 73 | pub fn is_ratelimited(&self) -> bool { 74 | matches!(self.inner.kind, Kind::RateLimit { .. }) 75 | } 76 | 77 | /// Returns true if the error was generated from a response. 78 | pub fn is_response(&self) -> bool { 79 | matches!(self.inner.kind, Kind::Response { .. }) 80 | } 81 | 82 | /// Returns true if the error contains validation errors. 83 | pub fn is_validation(&self) -> bool { 84 | matches!(self.inner.kind, Kind::Validation { .. }) 85 | } 86 | 87 | /// Returns true if the error is related to serialization. 88 | pub fn is_decode(&self) -> bool { 89 | matches!(self.inner.kind, Kind::Decode) 90 | } 91 | 92 | /// Returns the API error if the error was generated from a response. 93 | pub fn api_error(&self) -> Option<&ApiError> { 94 | match &self.inner.kind { 95 | Kind::Response { error, .. } => Some(error), 96 | _ => None, 97 | } 98 | } 99 | 100 | /// Returns modio's error reference code. 101 | /// 102 | /// See the [Error Codes](https://docs.mod.io/restapiref/#error-codes) docs for more information. 103 | pub fn error_ref(&self) -> Option { 104 | self.inner.error_ref 105 | } 106 | 107 | /// Returns status code if the error was generated from a response. 108 | pub fn status(&self) -> Option { 109 | match self.inner.kind { 110 | Kind::Response { status, .. } => Some(status), 111 | _ => None, 112 | } 113 | } 114 | 115 | /// Returns validation message & errors from the response. 116 | pub fn validation(&self) -> Option<(&String, &Vec<(String, String)>)> { 117 | match self.inner.kind { 118 | Kind::Validation { 119 | ref message, 120 | ref errors, 121 | } => Some((message, errors)), 122 | _ => None, 123 | } 124 | } 125 | } 126 | 127 | impl fmt::Debug for Error { 128 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 129 | let mut builder = f.debug_struct("modio::Error"); 130 | 131 | builder.field("kind", &self.inner.kind); 132 | if let Some(ref error_ref) = self.inner.error_ref { 133 | builder.field("error_ref", error_ref); 134 | } 135 | 136 | if let Some(ref source) = self.inner.source { 137 | builder.field("source", source); 138 | } 139 | builder.finish() 140 | } 141 | } 142 | 143 | impl fmt::Display for Error { 144 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 145 | match self.inner.kind { 146 | Kind::Unauthorized => f.write_str("unauthorized")?, 147 | Kind::TokenRequired => f.write_str("access token is required")?, 148 | Kind::TermsAcceptanceRequired => f.write_str("terms acceptance is required")?, 149 | Kind::Builder => f.write_str("builder error")?, 150 | Kind::Decode => f.write_str("error decoding response body")?, 151 | Kind::Download => f.write_str("download error")?, 152 | Kind::Request => f.write_str("http request error")?, 153 | Kind::Response { status, .. } => { 154 | let prefix = if status.is_client_error() { 155 | "HTTP status client error" 156 | } else { 157 | debug_assert!(status.is_server_error()); 158 | "HTTP status server error" 159 | }; 160 | write!(f, "{prefix} ({status})")?; 161 | } 162 | Kind::RateLimit { retry_after } => { 163 | write!(f, "API rate limit reached. Try again in {retry_after:?}.")?; 164 | } 165 | Kind::Validation { 166 | ref message, 167 | ref errors, 168 | } => { 169 | write!(f, "validation failed: '{message}' {errors:?}")?; 170 | } 171 | }; 172 | if let Some(ref e) = self.inner.source { 173 | write!(f, ": {e}")?; 174 | } 175 | Ok(()) 176 | } 177 | } 178 | 179 | impl StdError for Error { 180 | fn source(&self) -> Option<&(dyn StdError + 'static)> { 181 | self.inner.source.as_ref().map(|e| &**e as _) 182 | } 183 | } 184 | 185 | #[derive(Debug)] 186 | pub(crate) enum Kind { 187 | /// API key/access token is incorrect, revoked or expired. 188 | Unauthorized, 189 | /// Access token is required to perform the action. 190 | TokenRequired, 191 | /// The acceptance of the Terms of Use is required. 192 | TermsAcceptanceRequired, 193 | Download, 194 | Validation { 195 | message: String, 196 | errors: Vec<(String, String)>, 197 | }, 198 | RateLimit { 199 | retry_after: Duration, 200 | }, 201 | Builder, 202 | Request, 203 | Response { 204 | status: StatusCode, 205 | error: ApiError, 206 | }, 207 | Decode, 208 | } 209 | 210 | pub(crate) fn token_required() -> Error { 211 | Error::new(Kind::TokenRequired) 212 | } 213 | 214 | pub(crate) fn builder_or_request(e: reqwest::Error) -> Error { 215 | if e.is_builder() { 216 | builder(e) 217 | } else { 218 | request(e) 219 | } 220 | } 221 | 222 | pub(crate) fn builder>(source: E) -> Error { 223 | Error::new(Kind::Builder).with(source) 224 | } 225 | 226 | pub(crate) fn request>(source: E) -> Error { 227 | Error::new(Kind::Request).with(source) 228 | } 229 | 230 | pub(crate) fn decode>(source: E) -> Error { 231 | Error::new(Kind::Decode).with(source) 232 | } 233 | 234 | pub(crate) fn error_for_status(status: StatusCode, error: ApiError) -> Error { 235 | let error_ref = error.error_ref; 236 | let kind = match status { 237 | StatusCode::UNPROCESSABLE_ENTITY => Kind::Validation { 238 | message: error.message, 239 | errors: error.errors, 240 | }, 241 | StatusCode::UNAUTHORIZED => Kind::Unauthorized, 242 | StatusCode::FORBIDDEN if error_ref == 11051 => Kind::TermsAcceptanceRequired, 243 | _ => Kind::Response { status, error }, 244 | }; 245 | Error::new(kind).with_error_ref(error_ref) 246 | } 247 | 248 | pub(crate) fn ratelimit(retry_after: u64) -> Error { 249 | Error::new(Kind::RateLimit { 250 | retry_after: Duration::from_secs(retry_after), 251 | }) 252 | } 253 | 254 | pub(crate) fn download>(source: E) -> Error { 255 | Error::new(Kind::Download).with(source) 256 | } 257 | -------------------------------------------------------------------------------- /src/file_source.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | 3 | use futures_util::TryFutureExt; 4 | use mime::Mime; 5 | use reqwest::multipart::Part; 6 | use reqwest::Body; 7 | use tokio::fs::File; 8 | use tokio::io::AsyncRead; 9 | use tokio_util::io::ReaderStream; 10 | 11 | pub struct FileSource { 12 | pub body: Body, 13 | pub filename: String, 14 | pub mime: Mime, 15 | } 16 | 17 | impl FileSource { 18 | pub fn new_from_file>(file: P, filename: String, mime: Mime) -> Self { 19 | let file = file.as_ref().to_path_buf(); 20 | let st = File::open(file) 21 | .map_ok(ReaderStream::new) 22 | .try_flatten_stream(); 23 | 24 | FileSource { 25 | body: Body::wrap_stream(st), 26 | filename, 27 | mime, 28 | } 29 | } 30 | 31 | pub fn new_from_read(read: T, filename: String, mime: Mime) -> Self 32 | where 33 | T: AsyncRead + Send + Sync + Unpin + 'static, 34 | { 35 | FileSource { 36 | body: Body::wrap_stream(ReaderStream::new(read)), 37 | filename, 38 | mime, 39 | } 40 | } 41 | } 42 | 43 | impl From for Part { 44 | fn from(source: FileSource) -> Part { 45 | Part::stream(source.body) 46 | .file_name(source.filename) 47 | .mime_str(source.mime.as_ref()) 48 | .expect("FileSource::into::()") 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/files.rs: -------------------------------------------------------------------------------- 1 | //! Modfile interface 2 | use std::ffi::OsStr; 3 | use std::path::Path; 4 | 5 | use mime::APPLICATION_OCTET_STREAM; 6 | use serde::ser::{Serialize, SerializeMap, Serializer}; 7 | use tokio::io::AsyncRead; 8 | 9 | use crate::file_source::FileSource; 10 | use crate::prelude::*; 11 | use crate::types::id::{FileId, GameId, ModId}; 12 | use crate::TargetPlatform; 13 | 14 | pub use crate::types::files::{ 15 | Download, File, FileHash, Platform, PlatformStatus, VirusResult, VirusScan, VirusStatus, 16 | }; 17 | 18 | /// Interface for the modfiles of a mod. 19 | #[derive(Clone)] 20 | pub struct Files { 21 | modio: Modio, 22 | game: GameId, 23 | mod_id: ModId, 24 | } 25 | 26 | impl Files { 27 | pub(crate) fn new(modio: Modio, game: GameId, mod_id: ModId) -> Self { 28 | Self { 29 | modio, 30 | game, 31 | mod_id, 32 | } 33 | } 34 | 35 | /// Returns a `Query` interface to retrieve all files that are published 36 | /// for a mod this `Files` refers to. 37 | /// 38 | /// See [Filters and sorting](filters). 39 | pub fn search(&self, filter: Filter) -> Query { 40 | let route = Route::GetFiles { 41 | game_id: self.game, 42 | mod_id: self.mod_id, 43 | }; 44 | Query::new(self.modio.clone(), route, filter) 45 | } 46 | 47 | /// Return a reference to a file. 48 | pub fn get(&self, id: FileId) -> FileRef { 49 | FileRef::new(self.modio.clone(), self.game, self.mod_id, id) 50 | } 51 | 52 | /// Add a file for a mod that this `Files` refers to. [required: token] 53 | #[allow(clippy::should_implement_trait)] 54 | pub async fn add(self, options: AddFileOptions) -> Result { 55 | let route = Route::AddFile { 56 | game_id: self.game, 57 | mod_id: self.mod_id, 58 | }; 59 | self.modio 60 | .request(route) 61 | .multipart(Form::from(options)) 62 | .send() 63 | .await 64 | } 65 | } 66 | 67 | /// Reference interface of a modfile. 68 | #[derive(Clone)] 69 | pub struct FileRef { 70 | modio: Modio, 71 | game: GameId, 72 | mod_id: ModId, 73 | id: FileId, 74 | } 75 | 76 | impl FileRef { 77 | pub(crate) fn new(modio: Modio, game: GameId, mod_id: ModId, id: FileId) -> Self { 78 | Self { 79 | modio, 80 | game, 81 | mod_id, 82 | id, 83 | } 84 | } 85 | 86 | /// Get a reference to the Modio modfile object that this `FileRef` refers to. 87 | pub async fn get(self) -> Result { 88 | let route = Route::GetFile { 89 | game_id: self.game, 90 | mod_id: self.mod_id, 91 | file_id: self.id, 92 | }; 93 | self.modio.request(route).send().await 94 | } 95 | 96 | /// Edit details of a modfile. [required: token] 97 | pub async fn edit(self, options: EditFileOptions) -> Result> { 98 | let route = Route::EditFile { 99 | game_id: self.game, 100 | mod_id: self.mod_id, 101 | file_id: self.id, 102 | }; 103 | self.modio.request(route).form(&options).send().await 104 | } 105 | 106 | /// Delete a modfile. [required: token] 107 | pub async fn delete(self) -> Result<()> { 108 | let route = Route::DeleteFile { 109 | game_id: self.game, 110 | mod_id: self.mod_id, 111 | file_id: self.id, 112 | }; 113 | self.modio.request(route).send().await 114 | } 115 | 116 | /// Edit the platform status of a modfile. [required: token] 117 | pub async fn edit_platform_status(self, options: EditPlatformStatusOptions) -> Result { 118 | let route = Route::ManagePlatformStatus { 119 | game_id: self.game, 120 | mod_id: self.mod_id, 121 | file_id: self.id, 122 | }; 123 | self.modio.request(route).form(&options).send().await 124 | } 125 | } 126 | 127 | /// Modfile filters and sorting. 128 | /// 129 | /// # Filters 130 | /// - `Fulltext` 131 | /// - `Id` 132 | /// - `ModId` 133 | /// - `DateAdded` 134 | /// - `DateScanned` 135 | /// - `VirusStatus` 136 | /// - `VirusPositive` 137 | /// - `Filesize` 138 | /// - `Filehash` 139 | /// - `Filename` 140 | /// - `Version` 141 | /// - `Changelog` 142 | /// 143 | /// # Sorting 144 | /// - `Id` 145 | /// - `ModId` 146 | /// - `DateAdded` 147 | /// - `Version` 148 | /// 149 | /// See [modio docs](https://docs.mod.io/restapiref/#get-modfiles) for more information. 150 | /// 151 | /// By default this returns up to `100` items. You can limit the result by using `limit` and 152 | /// `offset`. 153 | /// 154 | /// # Example 155 | /// ``` 156 | /// use modio::filter::prelude::*; 157 | /// use modio::files::filters::Id; 158 | /// 159 | /// let filter = Id::_in(vec![1, 2]).order_by(Id::desc()); 160 | /// ``` 161 | #[rustfmt::skip] 162 | pub mod filters { 163 | #[doc(inline)] 164 | pub use crate::filter::prelude::Fulltext; 165 | #[doc(inline)] 166 | pub use crate::filter::prelude::Id; 167 | #[doc(inline)] 168 | pub use crate::filter::prelude::ModId; 169 | #[doc(inline)] 170 | pub use crate::filter::prelude::DateAdded; 171 | 172 | filter!(DateScanned, DATE_SCANNED, "date_scanned", Eq, NotEq, In, Cmp); 173 | filter!(VirusStatus, VIRUS_STATUS, "virus_status", Eq, NotEq, In, Cmp); 174 | filter!(VirusPositive, VIRUS_POSITIVE, "virus_positive", Eq, NotEq, In, Cmp); 175 | filter!(Filesize, FILESIZE, "filesize", Eq, NotEq, In, Cmp, OrderBy); 176 | filter!(Filehash, FILEHASH, "filehash", Eq, NotEq, In, Like); 177 | filter!(Filename, FILENAME, "filename", Eq, NotEq, In, Like); 178 | filter!(Version, VERSION, "version", Eq, NotEq, In, Like, OrderBy); 179 | filter!(Changelog, CHANGELOG, "changelog", Eq, NotEq, In, Like); 180 | } 181 | 182 | pub struct AddFileOptions { 183 | source: FileSource, 184 | version: Option, 185 | changelog: Option, 186 | active: Option, 187 | filehash: Option, 188 | metadata_blob: Option, 189 | } 190 | 191 | impl AddFileOptions { 192 | pub fn with_read(inner: R, filename: S) -> AddFileOptions 193 | where 194 | R: AsyncRead + Send + Sync + Unpin + 'static, 195 | S: Into, 196 | { 197 | AddFileOptions { 198 | source: FileSource::new_from_read(inner, filename.into(), APPLICATION_OCTET_STREAM), 199 | version: None, 200 | changelog: None, 201 | active: None, 202 | filehash: None, 203 | metadata_blob: None, 204 | } 205 | } 206 | 207 | pub fn with_file>(file: P) -> AddFileOptions { 208 | let file = file.as_ref(); 209 | let filename = file 210 | .file_name() 211 | .and_then(OsStr::to_str) 212 | .map_or_else(String::new, ToString::to_string); 213 | 214 | Self::with_file_name(file, filename) 215 | } 216 | 217 | pub fn with_file_name(file: P, filename: S) -> AddFileOptions 218 | where 219 | P: AsRef, 220 | S: Into, 221 | { 222 | let file = file.as_ref(); 223 | 224 | AddFileOptions { 225 | source: FileSource::new_from_file(file, filename.into(), APPLICATION_OCTET_STREAM), 226 | version: None, 227 | changelog: None, 228 | active: None, 229 | filehash: None, 230 | metadata_blob: None, 231 | } 232 | } 233 | 234 | option!(version); 235 | option!(changelog); 236 | option!(active: bool); 237 | option!(filehash); 238 | option!(metadata_blob); 239 | } 240 | 241 | #[doc(hidden)] 242 | impl From for Form { 243 | fn from(opts: AddFileOptions) -> Form { 244 | let mut form = Form::new(); 245 | if let Some(version) = opts.version { 246 | form = form.text("version", version); 247 | } 248 | if let Some(changelog) = opts.changelog { 249 | form = form.text("changelog", changelog); 250 | } 251 | if let Some(active) = opts.active { 252 | form = form.text("active", active.to_string()); 253 | } 254 | if let Some(filehash) = opts.filehash { 255 | form = form.text("filehash", filehash); 256 | } 257 | if let Some(metadata_blob) = opts.metadata_blob { 258 | form = form.text("metadata_blob", metadata_blob); 259 | } 260 | form.part("filedata", opts.source.into()) 261 | } 262 | } 263 | 264 | #[derive(Default)] 265 | pub struct EditFileOptions { 266 | params: std::collections::BTreeMap<&'static str, String>, 267 | } 268 | 269 | impl EditFileOptions { 270 | option!(version >> "version"); 271 | option!(changelog >> "changelog"); 272 | option!(active: bool >> "active"); 273 | option!(metadata_blob >> "metadata_blob"); 274 | } 275 | 276 | impl_serialize_params!(EditFileOptions >> params); 277 | 278 | pub struct EditPlatformStatusOptions { 279 | approved: Vec, 280 | denied: Vec, 281 | } 282 | 283 | impl EditPlatformStatusOptions { 284 | pub fn new(approved: &[TargetPlatform], denied: &[TargetPlatform]) -> Self { 285 | Self { 286 | approved: approved.to_vec(), 287 | denied: denied.to_vec(), 288 | } 289 | } 290 | } 291 | 292 | impl Serialize for EditPlatformStatusOptions { 293 | fn serialize(&self, serializer: S) -> Result { 294 | let mut s = serializer.serialize_map(Some(self.approved.len() + self.denied.len()))?; 295 | for target in &self.approved { 296 | s.serialize_entry("approved[]", target)?; 297 | } 298 | for target in &self.denied { 299 | s.serialize_entry("denied[]", target)?; 300 | } 301 | s.end() 302 | } 303 | } 304 | -------------------------------------------------------------------------------- /src/games.rs: -------------------------------------------------------------------------------- 1 | //! Games interface 2 | use std::ffi::OsStr; 3 | use std::path::Path; 4 | 5 | use mime::IMAGE_STAR; 6 | 7 | use crate::file_source::FileSource; 8 | use crate::mods::{ModRef, Mods}; 9 | use crate::prelude::*; 10 | use crate::types::id::{GameId, ModId}; 11 | 12 | pub use crate::types::games::{ 13 | ApiAccessOptions, CommunityOptions, CurationOption, Downloads, Game, HeaderImage, Icon, 14 | MaturityOptions, OtherUrl, Platform, PresentationOption, Statistics, SubmissionOption, 15 | TagOption, TagType, Theme, 16 | }; 17 | pub use crate::types::Logo; 18 | pub use crate::types::Status; 19 | 20 | /// Interface for games. 21 | #[derive(Clone)] 22 | pub struct Games { 23 | modio: Modio, 24 | } 25 | 26 | impl Games { 27 | pub(crate) fn new(modio: Modio) -> Self { 28 | Self { modio } 29 | } 30 | 31 | /// Returns a `Query` interface to retrieve games. 32 | /// 33 | /// See [Filters and sorting](filters). 34 | pub fn search(&self, filter: Filter) -> Query { 35 | let route = Route::GetGames { 36 | show_hidden_tags: None, 37 | }; 38 | Query::new(self.modio.clone(), route, filter) 39 | } 40 | 41 | /// Return a reference to a game. 42 | pub fn get(&self, id: GameId) -> GameRef { 43 | GameRef::new(self.modio.clone(), id) 44 | } 45 | } 46 | 47 | /// Reference interface of a game. 48 | #[derive(Clone)] 49 | pub struct GameRef { 50 | modio: Modio, 51 | id: GameId, 52 | } 53 | 54 | impl GameRef { 55 | pub(crate) fn new(modio: Modio, id: GameId) -> Self { 56 | Self { modio, id } 57 | } 58 | 59 | /// Get a reference to the Modio game object that this `GameRef` refers to. 60 | pub async fn get(self) -> Result { 61 | let route = Route::GetGame { 62 | id: self.id, 63 | show_hidden_tags: None, 64 | }; 65 | self.modio.request(route).send().await 66 | } 67 | 68 | /// Return a reference to a mod of a game. 69 | pub fn mod_(&self, mod_id: ModId) -> ModRef { 70 | ModRef::new(self.modio.clone(), self.id, mod_id) 71 | } 72 | 73 | /// Return a reference to an interface that provides access to the mods of a game. 74 | pub fn mods(&self) -> Mods { 75 | Mods::new(self.modio.clone(), self.id) 76 | } 77 | 78 | /// Return the statistics for a game. 79 | pub async fn statistics(self) -> Result { 80 | let route = Route::GetGameStats { game_id: self.id }; 81 | self.modio.request(route).send().await 82 | } 83 | 84 | /// Return a reference to an interface that provides access to the tags of a game. 85 | pub fn tags(&self) -> Tags { 86 | Tags::new(self.modio.clone(), self.id) 87 | } 88 | 89 | /// Add new media to a game. [required: token] 90 | pub async fn edit_media(self, media: EditMediaOptions) -> Result<()> { 91 | let route = Route::AddGameMedia { game_id: self.id }; 92 | self.modio 93 | .request(route) 94 | .multipart(Form::from(media)) 95 | .send::() 96 | .await?; 97 | Ok(()) 98 | } 99 | } 100 | 101 | /// Interface for tag options. 102 | #[derive(Clone)] 103 | pub struct Tags { 104 | modio: Modio, 105 | game_id: GameId, 106 | } 107 | 108 | impl Tags { 109 | fn new(modio: Modio, game_id: GameId) -> Self { 110 | Self { modio, game_id } 111 | } 112 | 113 | /// List tag options. 114 | pub async fn list(self) -> Result> { 115 | let route = Route::GetGameTags { 116 | game_id: self.game_id, 117 | }; 118 | Query::new(self.modio, route, Filter::default()) 119 | .collect() 120 | .await 121 | } 122 | 123 | /// Provides a stream over all tag options. 124 | #[allow(clippy::iter_not_returning_iterator)] 125 | pub async fn iter(self) -> Result>> { 126 | let route = Route::GetGameTags { 127 | game_id: self.game_id, 128 | }; 129 | let filter = Filter::default(); 130 | Query::new(self.modio, route, filter).iter().await 131 | } 132 | 133 | /// Add tag options. [required: token] 134 | #[allow(clippy::should_implement_trait)] 135 | pub async fn add(self, options: AddTagsOptions) -> Result<()> { 136 | let route = Route::AddGameTags { 137 | game_id: self.game_id, 138 | }; 139 | self.modio 140 | .request(route) 141 | .form(&options) 142 | .send::() 143 | .await?; 144 | Ok(()) 145 | } 146 | 147 | /// Delete tag options. [required: token] 148 | pub async fn delete(self, options: DeleteTagsOptions) -> Result { 149 | let route = Route::DeleteGameTags { 150 | game_id: self.game_id, 151 | }; 152 | self.modio.request(route).form(&options).send().await 153 | } 154 | 155 | /// Rename an existing tag, updating all mods in the progress. [required: token] 156 | pub async fn rename(self, from: String, to: String) -> Result<()> { 157 | let route = Route::RenameGameTags { 158 | game_id: self.game_id, 159 | }; 160 | self.modio 161 | .request(route) 162 | .form(&[("from", from), ("to", to)]) 163 | .send::<()>() 164 | .await?; 165 | 166 | Ok(()) 167 | } 168 | } 169 | 170 | /// Game filters and sorting. 171 | /// 172 | /// # Filters 173 | /// - `Fulltext` 174 | /// - `Id` 175 | /// - `Status` 176 | /// - `SubmittedBy` 177 | /// - `DateAdded` 178 | /// - `DateUpdated` 179 | /// - `DateLive` 180 | /// - `Name` 181 | /// - `NameId` 182 | /// - `Summary` 183 | /// - `InstructionsUrl` 184 | /// - `UgcName` 185 | /// - `PresentationOption` 186 | /// - `SubmissionOption` 187 | /// - `CurationOption` 188 | /// - `CommunityOptions` 189 | /// - `RevenueOptions` 190 | /// - `ApiAccessOptions` 191 | /// - `MaturityOptions` 192 | /// 193 | /// # Sorting 194 | /// - `Id` 195 | /// - `Status` 196 | /// - `Name` 197 | /// - `NameId` 198 | /// - `DateUpdated` 199 | /// 200 | /// See [modio docs](https://docs.mod.io/restapiref/#get-games) for more information. 201 | /// 202 | /// By default this returns up to `100` items. You can limit the result by using `limit` and 203 | /// `offset`. 204 | /// 205 | /// # Example 206 | /// ``` 207 | /// use modio::filter::prelude::*; 208 | /// use modio::games::filters::Id; 209 | /// 210 | /// let filter = Id::_in(vec![1, 2]).order_by(Id::desc()); 211 | /// ``` 212 | #[rustfmt::skip] 213 | pub mod filters { 214 | #[doc(inline)] 215 | pub use crate::filter::prelude::Fulltext; 216 | #[doc(inline)] 217 | pub use crate::filter::prelude::Id; 218 | #[doc(inline)] 219 | pub use crate::filter::prelude::Name; 220 | #[doc(inline)] 221 | pub use crate::filter::prelude::NameId; 222 | #[doc(inline)] 223 | pub use crate::filter::prelude::Status; 224 | #[doc(inline)] 225 | pub use crate::filter::prelude::DateAdded; 226 | #[doc(inline)] 227 | pub use crate::filter::prelude::DateUpdated; 228 | #[doc(inline)] 229 | pub use crate::filter::prelude::DateLive; 230 | #[doc(inline)] 231 | pub use crate::filter::prelude::SubmittedBy; 232 | 233 | filter!(Summary, SUMMARY, "summary", Eq, NotEq, Like); 234 | filter!(InstructionsUrl, INSTRUCTIONS_URL, "instructions_url", Eq, NotEq, In, Like); 235 | filter!(UgcName, UGC_NAME, "ugc_name", Eq, NotEq, In, Like); 236 | filter!(PresentationOption, PRESENTATION_OPTION, "presentation_option", Eq, NotEq, In, Cmp, Bit); 237 | filter!(SubmissionOption, SUBMISSION_OPTION, "submission_option", Eq, NotEq, In, Cmp, Bit); 238 | filter!(CurationOption, CURATION_OPTION, "curation_option", Eq, NotEq, In, Cmp, Bit); 239 | filter!(CommunityOptions, COMMUNITY_OPTIONS, "community_options", Eq, NotEq, In, Cmp, Bit); 240 | filter!(RevenueOptions, REVENUE_OPTIONS, "revenue_options", Eq, NotEq, In, Cmp, Bit); 241 | filter!(ApiAccessOptions, API_ACCESS_OPTIONS, "api_access_options", Eq, NotEq, In, Cmp, Bit); 242 | filter!(MaturityOptions, MATURITY_OPTIONS, "maturity_options", Eq, NotEq, In, Cmp, Bit); 243 | } 244 | 245 | pub struct AddTagsOptions { 246 | name: String, 247 | kind: TagType, 248 | hidden: bool, 249 | locked: bool, 250 | tags: Vec, 251 | } 252 | 253 | impl AddTagsOptions { 254 | pub fn new>(name: S, kind: TagType, tags: &[String]) -> Self { 255 | Self { 256 | name: name.into(), 257 | kind, 258 | hidden: false, 259 | locked: false, 260 | tags: tags.to_vec(), 261 | } 262 | } 263 | 264 | pub fn hidden(self, value: bool) -> Self { 265 | Self { 266 | hidden: value, 267 | ..self 268 | } 269 | } 270 | 271 | pub fn locked(self, value: bool) -> Self { 272 | Self { 273 | locked: value, 274 | ..self 275 | } 276 | } 277 | } 278 | 279 | #[doc(hidden)] 280 | impl serde::ser::Serialize for AddTagsOptions { 281 | fn serialize(&self, serializer: S) -> std::result::Result 282 | where 283 | S: serde::ser::Serializer, 284 | { 285 | use serde::ser::SerializeMap; 286 | 287 | let len = 2 + usize::from(self.hidden) + usize::from(self.locked) + self.tags.len(); 288 | let mut map = serializer.serialize_map(Some(len))?; 289 | map.serialize_entry("name", &self.name)?; 290 | map.serialize_entry("type", &self.kind)?; 291 | if self.hidden { 292 | map.serialize_entry("hidden", &self.hidden)?; 293 | } 294 | if self.locked { 295 | map.serialize_entry("locked", &self.locked)?; 296 | } 297 | for t in &self.tags { 298 | map.serialize_entry("tags[]", t)?; 299 | } 300 | map.end() 301 | } 302 | } 303 | 304 | pub struct DeleteTagsOptions { 305 | name: String, 306 | tags: Option>, 307 | } 308 | 309 | impl DeleteTagsOptions { 310 | pub fn all>(name: S) -> Self { 311 | Self { 312 | name: name.into(), 313 | tags: None, 314 | } 315 | } 316 | 317 | pub fn some>(name: S, tags: &[String]) -> Self { 318 | Self { 319 | name: name.into(), 320 | tags: if tags.is_empty() { 321 | None 322 | } else { 323 | Some(tags.to_vec()) 324 | }, 325 | } 326 | } 327 | } 328 | 329 | #[doc(hidden)] 330 | impl serde::ser::Serialize for DeleteTagsOptions { 331 | fn serialize(&self, serializer: S) -> std::result::Result 332 | where 333 | S: serde::ser::Serializer, 334 | { 335 | use serde::ser::SerializeMap; 336 | 337 | let len = self.tags.as_ref().map_or(1, Vec::len); 338 | let mut map = serializer.serialize_map(Some(len + 1))?; 339 | map.serialize_entry("name", &self.name)?; 340 | if let Some(ref tags) = self.tags { 341 | for t in tags { 342 | map.serialize_entry("tags[]", t)?; 343 | } 344 | } else { 345 | map.serialize_entry("tags[]", "")?; 346 | } 347 | map.end() 348 | } 349 | } 350 | 351 | #[derive(Default)] 352 | pub struct EditMediaOptions { 353 | logo: Option, 354 | icon: Option, 355 | header: Option, 356 | } 357 | 358 | impl EditMediaOptions { 359 | #[must_use] 360 | pub fn logo>(self, logo: P) -> Self { 361 | let logo = logo.as_ref(); 362 | let filename = logo 363 | .file_name() 364 | .and_then(OsStr::to_str) 365 | .map_or_else(String::new, ToString::to_string); 366 | 367 | Self { 368 | logo: Some(FileSource::new_from_file(logo, filename, IMAGE_STAR)), 369 | ..self 370 | } 371 | } 372 | 373 | #[must_use] 374 | pub fn icon>(self, icon: P) -> Self { 375 | let icon = icon.as_ref(); 376 | let filename = icon 377 | .file_name() 378 | .and_then(OsStr::to_str) 379 | .map_or_else(String::new, ToString::to_string); 380 | 381 | Self { 382 | icon: Some(FileSource::new_from_file(icon, filename, IMAGE_STAR)), 383 | ..self 384 | } 385 | } 386 | 387 | #[must_use] 388 | pub fn header>(self, header: P) -> Self { 389 | let header = header.as_ref(); 390 | let filename = header 391 | .file_name() 392 | .and_then(OsStr::to_str) 393 | .map_or_else(String::new, ToString::to_string); 394 | 395 | Self { 396 | header: Some(FileSource::new_from_file(header, filename, IMAGE_STAR)), 397 | ..self 398 | } 399 | } 400 | } 401 | 402 | #[doc(hidden)] 403 | impl From for Form { 404 | fn from(opts: EditMediaOptions) -> Form { 405 | let mut form = Form::new(); 406 | if let Some(logo) = opts.logo { 407 | form = form.part("logo", logo.into()); 408 | } 409 | if let Some(icon) = opts.icon { 410 | form = form.part("icon", icon.into()); 411 | } 412 | if let Some(header) = opts.header { 413 | form = form.part("header", header.into()); 414 | } 415 | form 416 | } 417 | } 418 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Modio provides a set of building blocks for interacting with the [mod.io](https://mod.io) API. 2 | //! 3 | //! The client uses asynchronous I/O, backed by the `futures` and `tokio` crates, and requires both 4 | //! to be used alongside. 5 | //! 6 | //! # Authentication 7 | //! 8 | //! To access the API authentication is required and can be done via several ways: 9 | //! 10 | //! - Request an [API key (Read-only)](https://mod.io/me/access) 11 | //! - Manually create an [OAuth 2 Access Token (Read + Write)](https://mod.io/me/access#oauth) 12 | //! - [Email Authentication Flow](auth::Auth#example) to create an OAuth 2 Access Token (Read + Write) 13 | //! - [External Authentication](auth::Auth::external) to create an OAuth 2 Access Token (Read + Write) 14 | //! automatically on platforms such as Steam, GOG, itch.io, Switch, Xbox, Discord and Oculus. 15 | //! 16 | //! # Rate Limiting 17 | //! 18 | //! - API keys linked to a game have **unlimited requests**. 19 | //! - API keys linked to a user have **60 requests per minute**. 20 | //! - OAuth2 user tokens are limited to **120 requests per minute**. 21 | //! 22 | //! [`Error::is_ratelimited`] will return true 23 | //! if the rate limit associated with credentials has been exhausted. 24 | //! 25 | //! # Example: Basic setup 26 | //! 27 | //! ```no_run 28 | //! use modio::{Credentials, Modio}; 29 | //! 30 | //! #[tokio::main] 31 | //! async fn main() -> Result<(), Box> { 32 | //! let modio = Modio::new(Credentials::new("user-or-game-api-key"))?; 33 | //! 34 | //! // create some tasks and execute them 35 | //! // let result = task.await?; 36 | //! Ok(()) 37 | //! } 38 | //! ``` 39 | //! 40 | //! For testing purposes use [`Modio::host`] to create a client for the 41 | //! mod.io [test environment](https://docs.mod.io/restapiref/#testing). 42 | //! 43 | //! # Example: Chaining api requests 44 | //! 45 | //! ```no_run 46 | //! use futures_util::future::try_join3; 47 | //! use modio::filter::Filter; 48 | //! use modio::types::id::Id; 49 | //! # #[tokio::main] 50 | //! # async fn main() -> Result<(), Box> { 51 | //! # let modio = modio::Modio::new("user-or-game-api-key")?; 52 | //! 53 | //! // OpenXcom: The X-Com Files 54 | //! let modref = modio.mod_(Id::new(51), Id::new(158)); 55 | //! 56 | //! // Get mod with its dependencies and all files 57 | //! let deps = modref.dependencies().list(); 58 | //! let files = modref.files().search(Filter::default()).collect(); 59 | //! let mod_ = modref.get(); 60 | //! 61 | //! let (m, deps, files) = try_join3(mod_, deps, files).await?; 62 | //! 63 | //! println!("{}", m.name); 64 | //! println!( 65 | //! "deps: {:?}", 66 | //! deps.into_iter().map(|d| d.mod_id).collect::>() 67 | //! ); 68 | //! for file in files { 69 | //! println!("file id: {} version: {:?}", file.id, file.version); 70 | //! } 71 | //! # Ok(()) 72 | //! # } 73 | //! ``` 74 | //! 75 | //! # Example: Downloading mods 76 | //! 77 | //! ```no_run 78 | //! use modio::download::{DownloadAction, ResolvePolicy}; 79 | //! use modio::types::id::Id; 80 | //! # #[tokio::main] 81 | //! # async fn main() -> Result<(), Box> { 82 | //! # let modio = modio::Modio::new("user-or-game-api-key")?; 83 | //! 84 | //! // Download the primary file of a mod. 85 | //! let action = DownloadAction::Primary { 86 | //! game_id: Id::new(5), 87 | //! mod_id: Id::new(19), 88 | //! }; 89 | //! modio 90 | //! .download(action) 91 | //! .await? 92 | //! .save_to_file("mod.zip") 93 | //! .await?; 94 | //! 95 | //! // Download the specific file of a mod. 96 | //! let action = DownloadAction::File { 97 | //! game_id: Id::new(5), 98 | //! mod_id: Id::new(19), 99 | //! file_id: Id::new(101), 100 | //! }; 101 | //! modio 102 | //! .download(action) 103 | //! .await? 104 | //! .save_to_file("mod.zip") 105 | //! .await?; 106 | //! 107 | //! // Download the specific version of a mod. 108 | //! // if multiple files are found then the latest file is downloaded. 109 | //! // Set policy to `ResolvePolicy::Fail` to return with 110 | //! // `modio::download::Error::MultipleFilesFound` as source error. 111 | //! let action = DownloadAction::Version { 112 | //! game_id: Id::new(5), 113 | //! mod_id: Id::new(19), 114 | //! version: "0.1".to_string(), 115 | //! policy: ResolvePolicy::Latest, 116 | //! }; 117 | //! modio 118 | //! .download(action) 119 | //! .await? 120 | //! .save_to_file("mod.zip") 121 | //! .await?; 122 | //! # Ok(()) 123 | //! # } 124 | //! ``` 125 | #![doc(html_root_url = "https://docs.rs/modio/0.13.0")] 126 | #![deny(rust_2018_idioms)] 127 | #![deny(rustdoc::broken_intra_doc_links)] 128 | #![allow(clippy::upper_case_acronyms)] 129 | 130 | #[macro_use] 131 | mod macros; 132 | 133 | pub mod auth; 134 | #[macro_use] 135 | pub mod filter; 136 | pub mod comments; 137 | pub mod download; 138 | pub mod files; 139 | pub mod games; 140 | pub mod metadata; 141 | pub mod mods; 142 | pub mod reports; 143 | pub mod teams; 144 | pub mod types; 145 | pub mod user; 146 | 147 | mod client; 148 | mod error; 149 | mod file_source; 150 | mod loader; 151 | mod request; 152 | mod routing; 153 | 154 | pub use crate::auth::Credentials; 155 | pub use crate::client::{Builder, Modio}; 156 | pub use crate::download::DownloadAction; 157 | pub use crate::error::{Error, Result}; 158 | pub use crate::loader::{Page, Query}; 159 | pub use crate::types::{Deletion, Editing, TargetPlatform, TargetPortal}; 160 | 161 | mod prelude { 162 | pub use futures_util::Stream; 163 | pub use reqwest::multipart::Form; 164 | pub use reqwest::StatusCode; 165 | 166 | pub use crate::filter::Filter; 167 | pub use crate::loader::Query; 168 | pub use crate::routing::Route; 169 | pub use crate::types::Message; 170 | pub use crate::{Deletion, Editing, Modio, Result}; 171 | } 172 | 173 | /// Re-exports of the used reqwest types. 174 | #[doc(hidden)] 175 | pub mod lib { 176 | pub use reqwest::header; 177 | pub use reqwest::redirect::Policy; 178 | pub use reqwest::ClientBuilder; 179 | #[cfg(feature = "__tls")] 180 | pub use reqwest::{Certificate, Identity}; 181 | pub use reqwest::{Proxy, Url}; 182 | } 183 | -------------------------------------------------------------------------------- /src/loader.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | use std::pin::Pin; 3 | use std::task::{Context, Poll}; 4 | 5 | use futures_util::future::Either; 6 | use futures_util::{stream, Stream, StreamExt, TryStreamExt}; 7 | use pin_project_lite::pin_project; 8 | use serde::de::DeserializeOwned; 9 | 10 | use crate::filter::Filter; 11 | use crate::routing::Route; 12 | use crate::types::List; 13 | use crate::{Modio, Result}; 14 | 15 | /// Interface for retrieving search results. 16 | pub struct Query { 17 | modio: Modio, 18 | route: Route, 19 | filter: Filter, 20 | phantom: PhantomData, 21 | } 22 | 23 | impl Query { 24 | pub(crate) fn new(modio: Modio, route: Route, filter: Filter) -> Self { 25 | Self { 26 | modio, 27 | route, 28 | filter, 29 | phantom: PhantomData, 30 | } 31 | } 32 | } 33 | 34 | impl Query { 35 | /// Returns the first search result. 36 | pub async fn first(mut self) -> Result> { 37 | self.filter = self.filter.limit(1); 38 | let list = self.first_page().await; 39 | list.map(|l| l.into_iter().next()) 40 | } 41 | 42 | /// Returns the first search result page. 43 | pub async fn first_page(self) -> Result> { 44 | let list = self.paged().await?.map_ok(|p| p.0.data).try_next().await; 45 | list.map(Option::unwrap_or_default) 46 | } 47 | 48 | /// Returns the complete search result list. 49 | pub async fn collect(self) -> Result> { 50 | self.paged().await?.map_ok(|p| p.0.data).try_concat().await 51 | } 52 | 53 | /// Provides a stream over all search result items. 54 | /// 55 | /// Beware that a `Filter::with_limit` will NOT limit the number of items returned 56 | /// by the stream, but limits the page size for the underlying API requests. 57 | /// 58 | /// # Example 59 | /// ```no_run 60 | /// use futures_util::TryStreamExt; 61 | /// use modio::filter::prelude::*; 62 | /// use modio::types::id::Id; 63 | /// 64 | /// # use modio::{Credentials, Modio, Result}; 65 | /// # 66 | /// # async fn run() -> Result<()> { 67 | /// # let modio = Modio::new(Credentials::new("apikey"))?; 68 | /// let filter = Fulltext::eq("soldier"); 69 | /// let mut st = modio.game(Id::new(51)).mods().search(filter).iter().await?; 70 | /// 71 | /// // Stream of `Mod` 72 | /// while let Some(mod_) = st.try_next().await? { 73 | /// println!("{}. {}", mod_.id, mod_.name); 74 | /// } 75 | /// 76 | /// use futures_util::StreamExt; 77 | /// 78 | /// // Retrieve the first 10 mods. (Default page size is `100`.) 79 | /// let filter = Fulltext::eq("tftd") + with_limit(10); 80 | /// let st = modio.game(Id::new(51)).mods().search(filter).iter().await?; 81 | /// let mut st = st.take(10); 82 | /// 83 | /// // Stream of `Mod` 84 | /// while let Some(mod_) = st.try_next().await? { 85 | /// println!("{}. {}", mod_.id, mod_.name); 86 | /// } 87 | /// # Ok(()) 88 | /// # } 89 | /// ``` 90 | #[allow(clippy::iter_not_returning_iterator)] 91 | pub async fn iter(self) -> Result>> { 92 | let (st, (total, _)) = stream(self.modio, self.route, self.filter).await?; 93 | let st = st 94 | .map_ok(|list| stream::iter(list.into_iter().map(Ok))) 95 | .try_flatten(); 96 | Ok(Box::pin(ResultStream::new(total as usize, st))) 97 | } 98 | 99 | /// Provides a stream over all search result pages. 100 | /// 101 | /// # Example 102 | /// ```no_run 103 | /// use futures_util::TryStreamExt; 104 | /// use modio::filter::prelude::*; 105 | /// use modio::types::id::Id; 106 | /// 107 | /// # use modio::{Credentials, Modio, Result}; 108 | /// # 109 | /// # async fn run() -> Result<()> { 110 | /// # let modio = Modio::new(Credentials::new("apikey"))?; 111 | /// let filter = Fulltext::eq("tftd").limit(10); 112 | /// let mut st = modio 113 | /// .game(Id::new(51)) 114 | /// .mods() 115 | /// .search(filter) 116 | /// .paged() 117 | /// .await?; 118 | /// 119 | /// // Stream of paged results `Page` with page size = 10 120 | /// while let Some(page) = st.try_next().await? { 121 | /// println!("Page {}/{}", page.current(), page.page_count()); 122 | /// for item in page { 123 | /// println!(" {}. {}", item.id, item.name); 124 | /// } 125 | /// } 126 | /// # Ok(()) 127 | /// # } 128 | /// ``` 129 | pub async fn paged(self) -> Result>>> { 130 | let (st, (total, limit)) = stream(self.modio, self.route, self.filter).await?; 131 | let size_hint = if total == 0 { 132 | 0 133 | } else { 134 | (total - 1) / limit + 1 135 | }; 136 | Ok(Box::pin(ResultStream::new(size_hint as usize, st))) 137 | } 138 | } 139 | 140 | async fn stream( 141 | modio: Modio, 142 | route: Route, 143 | filter: Filter, 144 | ) -> Result<(impl Stream>>, (u32, u32))> 145 | where 146 | T: DeserializeOwned + Send, 147 | { 148 | struct State { 149 | offset: u32, 150 | limit: u32, 151 | remaining: u32, 152 | } 153 | let list = modio 154 | .request(route) 155 | .query(&filter) 156 | .send::>() 157 | .await?; 158 | 159 | let state = State { 160 | offset: list.offset, 161 | limit: list.limit, 162 | remaining: list.total - list.count, 163 | }; 164 | let initial = (modio, route, filter, state); 165 | let stats = (list.total, list.limit); 166 | if list.total == 0 { 167 | return Ok((Either::Left(stream::empty()), stats)); 168 | } 169 | 170 | let first = stream::once(async { Ok::<_, crate::Error>(Page(list)) }); 171 | 172 | let others = stream::try_unfold(initial, |(modio, route, filter, state)| async move { 173 | if let State { remaining: 0, .. } = state { 174 | return Ok(None); 175 | } 176 | let filter = filter.offset((state.offset + state.limit) as usize); 177 | let remaining = state.remaining; 178 | 179 | let list = modio 180 | .request(route) 181 | .query(&filter) 182 | .send::>() 183 | .await?; 184 | 185 | let state = ( 186 | modio, 187 | route, 188 | filter, 189 | State { 190 | offset: list.offset, 191 | limit: list.limit, 192 | remaining: remaining - list.count, 193 | }, 194 | ); 195 | 196 | Ok(Some((Page(list), state))) 197 | }); 198 | 199 | Ok((Either::Right(first.chain(others)), stats)) 200 | } 201 | 202 | /// A `Page` returned by the [`Query::paged`] stream for a search result. 203 | pub struct Page(List); 204 | 205 | impl Page { 206 | pub fn data(&self) -> &Vec { 207 | &self.0.data 208 | } 209 | 210 | pub fn into_data(self) -> Vec { 211 | self.0.data 212 | } 213 | 214 | /// Returns the current page number. 215 | pub fn current(&self) -> usize { 216 | self.0.offset as usize / self.page_size() + 1 217 | } 218 | 219 | /// Returns the number of pages. 220 | pub fn page_count(&self) -> usize { 221 | (self.total() - 1) / self.page_size() + 1 222 | } 223 | 224 | /// Returns the size of a page. 225 | pub fn page_size(&self) -> usize { 226 | self.0.limit as usize 227 | } 228 | 229 | /// Returns the total number of the search result. 230 | pub fn total(&self) -> usize { 231 | self.0.total as usize 232 | } 233 | } 234 | 235 | // Impl IntoIterator & Deref for Page {{{ 236 | impl std::ops::Deref for Page { 237 | type Target = Vec; 238 | 239 | fn deref(&self) -> &Self::Target { 240 | &self.0.data 241 | } 242 | } 243 | 244 | impl<'a, T> std::iter::IntoIterator for &'a Page { 245 | type Item = &'a T; 246 | type IntoIter = std::slice::Iter<'a, T>; 247 | 248 | fn into_iter(self) -> std::slice::Iter<'a, T> { 249 | self.0.data.iter() 250 | } 251 | } 252 | 253 | impl std::iter::IntoIterator for Page { 254 | type Item = T; 255 | type IntoIter = std::vec::IntoIter; 256 | 257 | fn into_iter(self) -> std::vec::IntoIter { 258 | self.0.data.into_iter() 259 | } 260 | } 261 | // }}} 262 | 263 | pin_project! { 264 | struct ResultStream { 265 | total: usize, 266 | #[pin] 267 | stream: St, 268 | } 269 | } 270 | 271 | impl ResultStream { 272 | fn new(total: usize, stream: St) -> ResultStream { 273 | Self { total, stream } 274 | } 275 | } 276 | 277 | impl Stream for ResultStream { 278 | type Item = St::Item; 279 | 280 | fn size_hint(&self) -> (usize, Option) { 281 | (self.total, None) 282 | } 283 | 284 | fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 285 | self.project().stream.poll_next(cx) 286 | } 287 | } 288 | 289 | // vim: fdm=marker 290 | -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | macro_rules! option { 2 | ($(#[$outer:meta])* $name:ident) => { 3 | option!($(#[$outer])* $name: Into); 4 | }; 5 | ($(#[$outer:meta])* $name:ident: Into<$T:ty>) => { 6 | $(#[$outer])* 7 | #[must_use] 8 | pub fn $name>(self, value: T) -> Self { 9 | Self { 10 | $name: Some(value.into()), 11 | ..self 12 | } 13 | } 14 | }; 15 | ($(#[$outer:meta])* $name:ident: $T:ty) => { 16 | $(#[$outer])* 17 | #[must_use] 18 | pub fn $name(self, value: $T) -> Self { 19 | Self { 20 | $name: Some(value), 21 | ..self 22 | } 23 | } 24 | }; 25 | ($(#[$outer:meta])* $name:ident >> $param:expr) => { 26 | $(#[$outer])* 27 | #[must_use] 28 | pub fn $name>(self, value: S) -> Self { 29 | let mut params = self.params; 30 | params.insert($param, value.into()); 31 | Self { params } 32 | } 33 | }; 34 | ($(#[$outer:meta])* $name:ident: Into<$T:ty> >> $param:expr) => { 35 | $(#[$outer])* 36 | #[must_use] 37 | pub fn $name>(self, value: T) -> Self { 38 | let mut params = self.params; 39 | params.insert($param, value.into().to_string()); 40 | Self { params } 41 | } 42 | }; 43 | ($(#[$outer:meta])* $name:ident: $T:ty >> $param:expr) => { 44 | $(#[$outer])* 45 | #[must_use] 46 | pub fn $name(self, value: $T) -> Self { 47 | let mut params = self.params; 48 | params.insert($param, value.to_string()); 49 | Self { params } 50 | } 51 | }; 52 | // This variant prevents the poor macro formatting in auth.rs by rustfmt 53 | ($(#[$outer:meta])* $name:ident $T:ty >> $param:expr) => { 54 | option!($(#[$outer])* $name: $T >> $param); 55 | }; 56 | } 57 | 58 | macro_rules! impl_serialize_params { 59 | ($T:ty >> $map:ident) => { 60 | #[doc(hidden)] 61 | impl ::serde::ser::Serialize for $T { 62 | fn serialize(&self, serializer: S) -> ::std::result::Result 63 | where 64 | S: ::serde::ser::Serializer, 65 | { 66 | use ::serde::ser::SerializeMap; 67 | 68 | let mut map = serializer.serialize_map(Some(self.$map.len()))?; 69 | for (k, v) in &self.$map { 70 | map.serialize_entry(k, v)?; 71 | } 72 | map.end() 73 | } 74 | } 75 | }; 76 | } 77 | -------------------------------------------------------------------------------- /src/metadata.rs: -------------------------------------------------------------------------------- 1 | //! Mod metadata KVP interface 2 | use futures_util::TryStreamExt; 3 | use serde_derive::Deserialize; 4 | 5 | use crate::prelude::*; 6 | use crate::types::id::{GameId, ModId}; 7 | pub use crate::types::mods::MetadataMap; 8 | 9 | #[derive(Clone)] 10 | pub struct Metadata { 11 | modio: Modio, 12 | game: GameId, 13 | mod_id: ModId, 14 | } 15 | 16 | impl Metadata { 17 | pub(crate) fn new(modio: Modio, game: GameId, mod_id: ModId) -> Self { 18 | Self { 19 | modio, 20 | game, 21 | mod_id, 22 | } 23 | } 24 | 25 | /// Return the metadata key value pairs for a mod that this `Metadata` refers to. 26 | pub async fn get(self) -> Result { 27 | #[derive(Deserialize)] 28 | struct KV { 29 | metakey: String, 30 | metavalue: String, 31 | } 32 | 33 | let route = Route::GetModMetadata { 34 | game_id: self.game, 35 | mod_id: self.mod_id, 36 | }; 37 | let filter = Filter::default(); 38 | let mut it = Query::::new(self.modio, route, filter).iter().await?; 39 | 40 | let (size, _) = it.size_hint(); 41 | let mut map = MetadataMap::with_capacity(size); 42 | 43 | while let Some(kv) = it.try_next().await? { 44 | map.entry(kv.metakey).or_default().push(kv.metavalue); 45 | } 46 | Ok(map) 47 | } 48 | 49 | /// Add metadata for a mod that this `Metadata` refers to. 50 | #[allow(clippy::should_implement_trait)] 51 | pub async fn add(self, metadata: MetadataMap) -> Result<()> { 52 | let route = Route::AddModMetadata { 53 | game_id: self.game, 54 | mod_id: self.mod_id, 55 | }; 56 | self.modio 57 | .request(route) 58 | .form(&metadata) 59 | .send::() 60 | .await?; 61 | Ok(()) 62 | } 63 | 64 | /// Delete metadata for a mod that this `Metadata` refers to. 65 | pub async fn delete(self, metadata: MetadataMap) -> Result { 66 | let route = Route::DeleteModMetadata { 67 | game_id: self.game, 68 | mod_id: self.mod_id, 69 | }; 70 | self.modio.request(route).form(&metadata).send().await 71 | } 72 | } 73 | 74 | #[doc(hidden)] 75 | impl serde::ser::Serialize for MetadataMap { 76 | fn serialize(&self, serializer: S) -> std::result::Result 77 | where 78 | S: serde::ser::Serializer, 79 | { 80 | use serde::ser::SerializeMap; 81 | 82 | let len = self.values().map(|v| std::cmp::max(1, v.len())).sum(); 83 | let mut map = serializer.serialize_map(Some(len))?; 84 | for (k, vals) in self.iter() { 85 | if vals.is_empty() { 86 | map.serialize_entry("metadata[]", k)?; 87 | } 88 | for v in vals { 89 | map.serialize_entry("metadata[]", &format!("{k}:{v}"))?; 90 | } 91 | } 92 | map.end() 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/reports.rs: -------------------------------------------------------------------------------- 1 | //! Reports interface 2 | use crate::prelude::*; 3 | use crate::types::id::{GameId, ModId, UserId}; 4 | 5 | #[derive(Clone)] 6 | pub struct Reports { 7 | modio: Modio, 8 | } 9 | 10 | impl Reports { 11 | pub(crate) fn new(modio: Modio) -> Self { 12 | Self { modio } 13 | } 14 | 15 | /// Submit a report for any resource on mod.io. [required: token] 16 | pub async fn submit(self, report: Report) -> Result<()> { 17 | self.modio 18 | .request(Route::SubmitReport) 19 | .form(&report) 20 | .send::() 21 | .await?; 22 | Ok(()) 23 | } 24 | } 25 | 26 | pub struct Report { 27 | pub name: String, 28 | pub contact: Option, 29 | pub summary: String, 30 | pub kind: ReportType, 31 | pub resource: Resource, 32 | } 33 | 34 | pub enum ReportType { 35 | Generic, 36 | DMCA, 37 | NotWorking, 38 | RudeContent, 39 | IllegalContent, 40 | StolenContent, 41 | FalseInformation, 42 | Other, 43 | } 44 | 45 | pub enum Resource { 46 | Game(GameId), 47 | Mod(ModId), 48 | User(UserId), 49 | } 50 | 51 | impl Report { 52 | pub fn new>( 53 | name: S, 54 | contact: Option, 55 | summary: S, 56 | kind: ReportType, 57 | resource: Resource, 58 | ) -> Self { 59 | Self { 60 | name: name.into(), 61 | contact: contact.map(Into::into), 62 | summary: summary.into(), 63 | kind, 64 | resource, 65 | } 66 | } 67 | } 68 | 69 | #[doc(hidden)] 70 | impl serde::ser::Serialize for Report { 71 | fn serialize(&self, serializer: S) -> std::result::Result 72 | where 73 | S: serde::ser::Serializer, 74 | { 75 | use serde::ser::SerializeMap; 76 | 77 | let (resource, id) = match self.resource { 78 | Resource::Game(id) => ("games", id.get()), 79 | Resource::Mod(id) => ("mods", id.get()), 80 | Resource::User(id) => ("users", id.get()), 81 | }; 82 | let kind = match self.kind { 83 | ReportType::Generic => 0, 84 | ReportType::DMCA => 1, 85 | ReportType::NotWorking => 2, 86 | ReportType::RudeContent => 3, 87 | ReportType::IllegalContent => 4, 88 | ReportType::StolenContent => 5, 89 | ReportType::FalseInformation => 6, 90 | ReportType::Other => 7, 91 | }; 92 | 93 | let len = if self.contact.is_some() { 6 } else { 5 }; 94 | let mut map = serializer.serialize_map(Some(len))?; 95 | 96 | if let Some(ref c) = self.contact { 97 | map.serialize_entry("contact", c)?; 98 | } 99 | map.serialize_entry("resource", resource)?; 100 | map.serialize_entry("id", &id)?; 101 | map.serialize_entry("type", &kind)?; 102 | map.serialize_entry("name", &self.name)?; 103 | map.serialize_entry("summary", &self.summary)?; 104 | 105 | map.end() 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/request.rs: -------------------------------------------------------------------------------- 1 | use futures_util::TryFutureExt; 2 | use reqwest::header::{HeaderValue, CONTENT_TYPE}; 3 | use reqwest::multipart::Form; 4 | use reqwest::StatusCode; 5 | use serde::de::DeserializeOwned; 6 | use serde::ser::Serialize; 7 | use tracing::{debug, level_enabled, trace}; 8 | use url::Url; 9 | 10 | use crate::auth::Token; 11 | use crate::error::{self, Result}; 12 | use crate::routing::{Parts, Route}; 13 | use crate::types::ErrorResponse; 14 | use crate::Modio; 15 | 16 | #[allow(dead_code)] 17 | mod headers { 18 | const X_MODIO_ERROR_REF: &str = "x-modio-error-ref"; 19 | const X_MODIO_REQUEST_ID: &str = "x-modio-request-id"; 20 | 21 | use http::header::{HeaderMap, RETRY_AFTER}; 22 | 23 | pub fn retry_after(headers: &HeaderMap) -> Option { 24 | headers 25 | .get(RETRY_AFTER) 26 | .and_then(|v| v.to_str().ok()) 27 | .and_then(|v| v.parse().ok()) 28 | } 29 | } 30 | 31 | pub struct RequestBuilder { 32 | modio: Modio, 33 | request: Result, 34 | } 35 | 36 | impl RequestBuilder { 37 | pub fn new(modio: Modio, route: Route) -> Self { 38 | let Parts { 39 | method, 40 | path, 41 | token_required, 42 | } = route.into_parts(); 43 | 44 | if let (true, None) = (token_required, &modio.inner.credentials.token) { 45 | return Self { 46 | modio, 47 | request: Err(error::token_required()), 48 | }; 49 | } 50 | 51 | let url = format!("{}{}", modio.inner.host, path); 52 | let params = [("api_key", &modio.inner.credentials.api_key)]; 53 | let request = Url::parse_with_params(&url, ¶ms) 54 | .map(|url| { 55 | let mut req = modio.inner.client.request(method, url); 56 | 57 | if let (true, Some(Token { value, .. })) = 58 | (token_required, &modio.inner.credentials.token) 59 | { 60 | req = req.bearer_auth(value); 61 | } 62 | req 63 | }) 64 | .map_err(error::builder); 65 | 66 | Self { modio, request } 67 | } 68 | 69 | pub fn query(self, query: &T) -> Self { 70 | Self { 71 | request: self.request.map(|r| r.query(query)), 72 | ..self 73 | } 74 | } 75 | 76 | pub fn form(self, form: &T) -> Self { 77 | Self { 78 | request: self.request.map(|r| r.form(form)), 79 | ..self 80 | } 81 | } 82 | 83 | pub fn multipart(self, form: Form) -> Self { 84 | Self { 85 | request: self.request.map(|r| r.multipart(form)), 86 | ..self 87 | } 88 | } 89 | 90 | pub async fn send(self) -> Result 91 | where 92 | Out: DeserializeOwned + Send, 93 | { 94 | let mut req = self.request?.build().map_err(error::builder)?; 95 | if !req.headers().contains_key(CONTENT_TYPE) { 96 | req.headers_mut().insert( 97 | CONTENT_TYPE, 98 | HeaderValue::from_static("application/x-www-form-urlencoded"), 99 | ); 100 | } 101 | 102 | debug!("request: {} {}", req.method(), req.url()); 103 | let response = self 104 | .modio 105 | .inner 106 | .client 107 | .execute(req) 108 | .map_err(error::request) 109 | .await?; 110 | 111 | let status = response.status(); 112 | 113 | let retry_after = if status.is_success() { 114 | None 115 | } else { 116 | headers::retry_after(response.headers()) 117 | }; 118 | 119 | trace!("response headers: {:?}", response.headers()); 120 | 121 | let body = response.bytes().map_err(error::request).await?; 122 | 123 | if level_enabled!(tracing::Level::TRACE) { 124 | match std::str::from_utf8(&body) { 125 | Ok(s) => trace!("status: {}, response: {}", status, s), 126 | Err(_) => trace!("status: {}, response: {:?}", status, body), 127 | } 128 | } 129 | 130 | if status == StatusCode::NO_CONTENT { 131 | serde_json::from_str("null").map_err(error::decode) 132 | } else if status.is_success() { 133 | serde_json::from_slice(&body).map_err(error::decode) 134 | } else if let Some(retry_after) = retry_after { 135 | debug!("ratelimit reached: retry after {retry_after} seconds"); 136 | Err(error::ratelimit(retry_after)) 137 | } else { 138 | serde_json::from_slice::(&body) 139 | .map(|mer| Err(error::error_for_status(status, mer.error))) 140 | .map_err(error::decode)? 141 | } 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/teams.rs: -------------------------------------------------------------------------------- 1 | //! Team members interface 2 | use crate::prelude::*; 3 | use crate::types::id::{GameId, ModId}; 4 | 5 | pub use crate::types::mods::{TeamLevel, TeamMember}; 6 | 7 | /// Interface for the team members of a mod. 8 | #[derive(Clone)] 9 | pub struct Members { 10 | modio: Modio, 11 | game: GameId, 12 | mod_id: ModId, 13 | } 14 | 15 | impl Members { 16 | pub(crate) fn new(modio: Modio, game: GameId, mod_id: ModId) -> Self { 17 | Self { 18 | modio, 19 | game, 20 | mod_id, 21 | } 22 | } 23 | 24 | /// Returns a `Query` interface to retrieve all team members. 25 | /// 26 | /// See [Filters and sorting](filters). 27 | pub fn search(&self, filter: Filter) -> Query { 28 | let route = Route::GetModTeamMembers { 29 | game_id: self.game, 30 | mod_id: self.mod_id, 31 | }; 32 | Query::new(self.modio.clone(), route, filter) 33 | } 34 | } 35 | 36 | /// Team member filters and sorting. 37 | /// 38 | /// # Filters 39 | /// - `Fulltext` 40 | /// - `Id` 41 | /// - `UserId` 42 | /// - `Username` 43 | /// - `Level` 44 | /// - `DateAdded` 45 | /// - `Position` 46 | /// 47 | /// # Sorting 48 | /// - `Id` 49 | /// - `UserId` 50 | /// - `Username` 51 | /// 52 | /// See [modio docs](https://docs.mod.io/restapiref/#get-mod-team-members) for more information. 53 | /// 54 | /// By default this returns up to `100` items. You can limit the result by using `limit` and 55 | /// `offset`. 56 | /// 57 | /// # Example 58 | /// ``` 59 | /// use modio::filter::prelude::*; 60 | /// use modio::teams::filters::Id; 61 | /// 62 | /// let filter = Id::_in(vec![1, 2]).order_by(Id::desc()); 63 | /// ``` 64 | #[rustfmt::skip] 65 | pub mod filters { 66 | #[doc(inline)] 67 | pub use crate::filter::prelude::Fulltext; 68 | #[doc(inline)] 69 | pub use crate::filter::prelude::Id; 70 | #[doc(inline)] 71 | pub use crate::filter::prelude::DateAdded; 72 | 73 | filter!(UserId, USER_ID, "user_id", Eq, NotEq, In, Cmp, OrderBy); 74 | filter!(Username, USERNAME, "username", Eq, NotEq, In, Like, OrderBy); 75 | filter!(Level, LEVEL, "level", Eq, NotEq, In, Cmp, OrderBy); 76 | filter!(Position, POSITION, "position", Eq, NotEq, In, Like, OrderBy); 77 | } 78 | -------------------------------------------------------------------------------- /src/types/auth.rs: -------------------------------------------------------------------------------- 1 | use serde_derive::Deserialize; 2 | use url::Url; 3 | 4 | use super::{utils, Timestamp}; 5 | 6 | /// See the [Access Token Object](https://docs.mod.io/restapiref/#access-token-object) docs for more 7 | /// information. 8 | #[derive(Deserialize)] 9 | #[non_exhaustive] 10 | pub struct AccessToken { 11 | #[serde(rename = "access_token")] 12 | pub value: String, 13 | #[serde(rename = "date_expires")] 14 | pub expired_at: Option, 15 | } 16 | 17 | /// See the [Terms Object](https://docs.mod.io/restapiref/#terms-object) docs for more information. 18 | #[derive(Debug, Deserialize)] 19 | #[non_exhaustive] 20 | pub struct Terms { 21 | pub plaintext: String, 22 | pub html: String, 23 | pub links: Links, 24 | } 25 | 26 | /// Part of [`Terms`] 27 | /// 28 | /// See the [Terms Object](https://docs.mod.io/restapiref/#terms-object) docs for more information. 29 | #[derive(Debug, Deserialize)] 30 | #[non_exhaustive] 31 | pub struct Links { 32 | pub website: Link, 33 | pub terms: Link, 34 | pub privacy: Link, 35 | pub manage: Link, 36 | } 37 | 38 | /// Part of [`Terms`] 39 | /// 40 | /// See the [Terms Object](https://docs.mod.io/restapiref/#terms-object) docs for more information. 41 | #[derive(Debug, Deserialize)] 42 | #[non_exhaustive] 43 | pub struct Link { 44 | pub text: String, 45 | #[serde(with = "utils::url")] 46 | pub url: Url, 47 | pub required: bool, 48 | } 49 | -------------------------------------------------------------------------------- /src/types/files.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | use serde::de::{Deserialize, Deserializer, IgnoredAny, MapAccess, Visitor}; 4 | use serde_derive::Deserialize; 5 | use url::Url; 6 | 7 | use crate::types::{DeserializeField, MissingField, TargetPlatform}; 8 | 9 | use super::id::{FileId, ModId}; 10 | use super::{utils, Timestamp}; 11 | 12 | /// See the [Modfile Object](https://docs.mod.io/restapiref/#modfile-object) docs for more information. 13 | #[derive(Debug)] 14 | #[non_exhaustive] 15 | pub struct File { 16 | pub id: FileId, 17 | pub mod_id: ModId, 18 | pub date_added: Timestamp, 19 | pub virus_scan: VirusScan, 20 | pub filesize: u64, 21 | pub filesize_uncompressed: u64, 22 | pub filehash: FileHash, 23 | pub filename: String, 24 | pub version: Option, 25 | pub changelog: Option, 26 | pub metadata_blob: Option, 27 | pub download: Download, 28 | pub platforms: Vec, 29 | } 30 | 31 | impl<'de> Deserialize<'de> for File { 32 | fn deserialize>(deserializer: D) -> Result { 33 | #[derive(Deserialize)] 34 | #[serde(field_identifier, rename_all = "snake_case")] 35 | enum Field { 36 | Id, 37 | ModId, 38 | DateAdded, 39 | DateScanned, 40 | VirusStatus, 41 | VirusPositive, 42 | Filesize, 43 | FilesizeUncompressed, 44 | Filehash, 45 | Filename, 46 | Version, 47 | Changelog, 48 | MetadataBlob, 49 | Download, 50 | Platforms, 51 | #[allow(dead_code)] 52 | Other(String), 53 | } 54 | 55 | struct FileVisitor; 56 | 57 | impl<'de> Visitor<'de> for FileVisitor { 58 | type Value = File; 59 | 60 | fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 61 | formatter.write_str("struct File") 62 | } 63 | 64 | fn visit_map>(self, mut map: A) -> Result { 65 | let mut id = None; 66 | let mut mod_id = None; 67 | let mut date_added = None; 68 | let mut date_scanned = None; 69 | let mut virus_status = None; 70 | let mut virus_result = None; 71 | let mut filesize = None; 72 | let mut filesize_uncompressed = None; 73 | let mut filehash = None; 74 | let mut filename = None; 75 | let mut version = None; 76 | let mut changelog = None; 77 | let mut metadata_blob = None; 78 | let mut download = None; 79 | let mut platforms = None; 80 | 81 | while let Some(key) = map.next_key()? { 82 | match key { 83 | Field::Id => { 84 | id.deserialize_value("id", &mut map)?; 85 | } 86 | Field::ModId => { 87 | mod_id.deserialize_value("mod_id", &mut map)?; 88 | } 89 | Field::DateAdded => { 90 | date_added.deserialize_value("date_added", &mut map)?; 91 | } 92 | Field::DateScanned => { 93 | date_scanned.deserialize_value("date_scanned", &mut map)?; 94 | } 95 | Field::VirusStatus => { 96 | virus_status.deserialize_value("virus_status", &mut map)?; 97 | } 98 | Field::VirusPositive => { 99 | virus_result.deserialize_value("virus_positive", &mut map)?; 100 | } 101 | Field::Filesize => { 102 | filesize.deserialize_value("filesize", &mut map)?; 103 | } 104 | Field::FilesizeUncompressed => { 105 | filesize_uncompressed 106 | .deserialize_value("filesize_uncompressed", &mut map)?; 107 | } 108 | Field::Filehash => { 109 | filehash.deserialize_value("filehash", &mut map)?; 110 | } 111 | Field::Filename => { 112 | filename.deserialize_value("filename", &mut map)?; 113 | } 114 | Field::Version => { 115 | version.deserialize_value("version", &mut map)?; 116 | } 117 | Field::Changelog => { 118 | changelog.deserialize_value("changelog", &mut map)?; 119 | } 120 | Field::MetadataBlob => { 121 | metadata_blob.deserialize_value("metadata_blob", &mut map)?; 122 | } 123 | Field::Download => { 124 | download.deserialize_value("download", &mut map)?; 125 | } 126 | Field::Platforms => { 127 | platforms.deserialize_value("platforms", &mut map)?; 128 | } 129 | Field::Other(_) => { 130 | map.next_value::()?; 131 | } 132 | } 133 | } 134 | 135 | let id = id.missing_field("id")?; 136 | let mod_id = mod_id.missing_field("mod_id")?; 137 | let date_added = date_added.missing_field("date_added")?; 138 | let date_scanned = date_scanned.missing_field("date_scanned")?; 139 | let virus_status = virus_status.missing_field("virus_status")?; 140 | let virus_result = virus_result.missing_field("virus_positive")?; 141 | let filesize = filesize.missing_field("filesize")?; 142 | let filesize_uncompressed = 143 | filesize_uncompressed.missing_field("filesize_uncompressed")?; 144 | let filehash = filehash.missing_field("filehash")?; 145 | let filename = filename.missing_field("filename")?; 146 | let version = version.missing_field("version")?; 147 | let changelog = changelog.missing_field("changelog")?; 148 | let metadata_blob = metadata_blob.missing_field("metadata_blob")?; 149 | let download = download.missing_field("download")?; 150 | let platforms = platforms.missing_field("platforms")?; 151 | 152 | Ok(File { 153 | id, 154 | mod_id, 155 | date_added, 156 | virus_scan: VirusScan { 157 | date_scanned, 158 | status: virus_status, 159 | result: virus_result, 160 | }, 161 | filesize, 162 | filesize_uncompressed, 163 | filehash, 164 | filename, 165 | version, 166 | changelog, 167 | metadata_blob, 168 | download, 169 | platforms, 170 | }) 171 | } 172 | } 173 | 174 | deserializer.deserialize_map(FileVisitor) 175 | } 176 | } 177 | 178 | /// See the [Modfile Object](https://docs.mod.io/restapiref/#modfile-object) docs for more information. 179 | #[derive(Debug)] 180 | #[non_exhaustive] 181 | pub struct VirusScan { 182 | pub date_scanned: Timestamp, 183 | pub status: VirusStatus, 184 | pub result: VirusResult, 185 | } 186 | 187 | newtype_enum! { 188 | /// See the [Modfile Object](https://docs.mod.io/restapiref/#modfile-object) docs for more information. 189 | pub struct VirusStatus: u8 { 190 | const NOT_SCANNED = 0; 191 | const SCAN_COMPLETED = 1; 192 | const IN_PROGRESS = 2; 193 | const TOO_LARGE_TO_SCAN = 3; 194 | const FILE_NOT_FOUND = 4; 195 | const ERROR_SCANNING = 5; 196 | } 197 | 198 | /// See the [Modfile Object](https://docs.mod.io/restapiref/#modfile-object) docs for more information. 199 | pub struct VirusResult: u8 { 200 | const NO_THREATS_DETECTED = 0; 201 | const MALICIOUS = 1; 202 | const POTENTIALLY_HARMFUL = 2; 203 | } 204 | } 205 | 206 | /// See the [Filehash Object](https://docs.mod.io/restapiref/#filehash-object) docs for more information. 207 | #[derive(Debug, Deserialize)] 208 | #[non_exhaustive] 209 | pub struct FileHash { 210 | pub md5: String, 211 | } 212 | 213 | /// See the [Download Object](https://docs.mod.io/restapiref/#download-object) docs for more information. 214 | #[derive(Deserialize)] 215 | #[non_exhaustive] 216 | pub struct Download { 217 | #[serde(with = "utils::url")] 218 | pub binary_url: Url, 219 | pub date_expires: Timestamp, 220 | } 221 | 222 | impl fmt::Debug for Download { 223 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 224 | f.debug_struct("Download") 225 | .field("binary_url", &self.binary_url.as_str()) 226 | .field("date_expires", &self.date_expires) 227 | .finish() 228 | } 229 | } 230 | 231 | /// See the [Modfile Platform Object](https://docs.mod.io/restapiref/#modfile-platform-object) docs for more 232 | /// information. 233 | #[derive(Debug, Deserialize)] 234 | #[non_exhaustive] 235 | pub struct Platform { 236 | #[serde(rename = "platform")] 237 | pub target: TargetPlatform, 238 | pub status: PlatformStatus, 239 | } 240 | 241 | newtype_enum! { 242 | /// See the [Modfile Platform Object](https://docs.mod.io/restapiref/#modfile-platform-object) docs for 243 | /// more information. 244 | pub struct PlatformStatus: u8 { 245 | const PENDING = 0; 246 | const APPROVED = 1; 247 | const DENIED = 2; 248 | } 249 | } 250 | -------------------------------------------------------------------------------- /src/types/games.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::fmt; 3 | 4 | use serde::de::{Deserialize, Deserializer, IgnoredAny, MapAccess, Visitor}; 5 | use serde_derive::{Deserialize, Serialize}; 6 | use url::Url; 7 | 8 | use super::id::GameId; 9 | use super::{deserialize_empty_object, utils, DeserializeField, MissingField}; 10 | use super::{Logo, Status, TargetPlatform, Timestamp}; 11 | 12 | /// See the [Game Object](https://docs.mod.io/restapiref/#game-object) docs for more information. 13 | #[derive(Debug, Deserialize)] 14 | #[non_exhaustive] 15 | pub struct Game { 16 | pub id: GameId, 17 | pub status: Status, 18 | pub date_added: Timestamp, 19 | pub date_updated: Timestamp, 20 | pub date_live: Timestamp, 21 | pub presentation_option: PresentationOption, 22 | pub submission_option: SubmissionOption, 23 | pub dependency_option: DependencyOption, 24 | pub curation_option: CurationOption, 25 | pub community_options: CommunityOptions, 26 | pub api_access_options: ApiAccessOptions, 27 | pub maturity_options: MaturityOptions, 28 | pub ugc_name: String, 29 | pub icon: Icon, 30 | pub logo: Logo, 31 | #[serde(default, deserialize_with = "deserialize_empty_object")] 32 | pub header: Option, 33 | pub name: String, 34 | pub name_id: String, 35 | pub summary: String, 36 | pub instructions: Option, 37 | #[serde(with = "utils::url::opt")] 38 | pub instructions_url: Option, 39 | #[serde(with = "utils::url")] 40 | pub profile_url: Url, 41 | /// The field is `None` when the game object is fetched from `/me/games`. 42 | #[serde(deserialize_with = "deserialize_empty_object")] 43 | pub stats: Option, 44 | /// The field is `None` when the game object is fetched from `/me/games`. 45 | #[serde(deserialize_with = "deserialize_empty_object")] 46 | pub theme: Option, 47 | pub other_urls: Vec, 48 | pub tag_options: Vec, 49 | pub platforms: Vec, 50 | } 51 | 52 | newtype_enum! { 53 | /// Presentation style used on the mod.io website. 54 | pub struct PresentationOption: u8 { 55 | /// Displays mods in a grid. 56 | const GRID_VIEW = 0; 57 | /// Displays mods in a table. 58 | const TABLE_VIEW = 1; 59 | } 60 | 61 | /// Submission process modders must follow. 62 | pub struct SubmissionOption: u8 { 63 | /// Mod uploads must occur via the API using a tool by the game developers. 64 | const API_ONLY = 0; 65 | /// Mod uploads can occur from anywhere, include the website and API. 66 | const ANYWHERE = 1; 67 | } 68 | 69 | /// Dependency option for a game. 70 | pub struct DependencyOption: u8 { 71 | /// Disallow mod dependencies. 72 | const DISALLOWED = 0; 73 | /// Allow mod dependencies, mods must opt in. 74 | const OPT_IN = 1; 75 | /// Allow mod dependencies, mods must opt out. 76 | const OPT_OUT = 2; 77 | /// Allow mod dependencies with no restrictions. 78 | const NO_RESTRICTION = 3; 79 | } 80 | 81 | /// Curation process used to approve mods. 82 | pub struct CurationOption: u8 { 83 | /// No curation: Mods are immediately available to play. 84 | const NO_CURATION = 0; 85 | /// Paid curation: Mods are immediately to play unless they choose to receive 86 | /// donations. These mods must be accepted to be listed. 87 | const PAID = 1; 88 | /// Full curation: All mods must be accepted by someone to be listed. 89 | const FULL = 2; 90 | } 91 | } 92 | 93 | bitflags! { 94 | /// Community features enabled on the mod.io website. 95 | pub struct CommunityOptions: u32 { 96 | /// Discussion board enabled. 97 | #[deprecated(note = "Flag is replaced by `ALLOW_COMMENTS`")] 98 | const DISCUSSIONS = 1; 99 | /// Allow comments on mods. 100 | const ALLOW_COMMENTS = 1; 101 | /// Guides & News enabled. 102 | #[deprecated(note = "Flag is replaced by `ALLOW_GUIDES`")] 103 | const GUIDES_NEWS = 2; 104 | const ALLOW_GUIDES = 2; 105 | const PIN_ON_HOMEPAGE = 4; 106 | const SHOW_ON_HOMEPAGE = 8; 107 | const SHOW_MORE_ON_HOMEPAGE = 16; 108 | const ALLOW_CHANGE_STATUS = 32; 109 | /// Previews enabled (Game must be hidden). 110 | const PREVIEWS = 64; 111 | /// Preview URLs enabled (Previews must be enabled). 112 | const PREVIEW_URLS = 128; 113 | /// Allow negative ratings 114 | const NEGATIVE_RATINGS = 256; 115 | /// Allow mods to be edited via web. 116 | const WEB_EDIT_MODS = 512; 117 | const ALLOW_MOD_DEPENDENCIES = 1024; 118 | /// Allow comments on guides. 119 | const ALLOW_GUIDE_COMMENTS = 2048; 120 | } 121 | 122 | /// Level of API access allowed by a game. 123 | pub struct ApiAccessOptions: u8 { 124 | /// Allow third parties to access a game's API endpoints. 125 | const ALLOW_THIRD_PARTY = 1; 126 | /// Allow mods to be downloaded directly. 127 | const ALLOW_DIRECT_DOWNLOAD = 2; 128 | /// Checks authorization on the mods to be downloaded directly (if enabled the consuming 129 | /// application must send the user's bearer token) 130 | const CHECK_AUTHORIZATION = 4; 131 | /// Checks ownerchip on the mods to be downloaded directly (if enabled the consuming 132 | /// application must send the user's bearer token) 133 | const CHECK_OWNERSHIP = 8; 134 | } 135 | 136 | /// Mature content options. 137 | pub struct MaturityOptions: u8 { 138 | const NOT_ALLOWED = 0; 139 | /// Allow flagging mods as mature. 140 | const ALLOWED = 1; 141 | /// The game is for mature audiences only. 142 | const ADULT_ONLY = 2; 143 | } 144 | } 145 | 146 | /// See the [Icon Object](https://docs.mod.io/restapiref/#icon-object) docs for more information. 147 | #[derive(Deserialize)] 148 | #[non_exhaustive] 149 | pub struct Icon { 150 | pub filename: String, 151 | #[serde(with = "utils::url")] 152 | pub original: Url, 153 | #[serde(with = "utils::url")] 154 | pub thumb_64x64: Url, 155 | #[serde(with = "utils::url")] 156 | pub thumb_128x128: Url, 157 | #[serde(with = "utils::url")] 158 | pub thumb_256x256: Url, 159 | } 160 | 161 | impl fmt::Debug for Icon { 162 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 163 | f.debug_struct("Icon") 164 | .field("filename", &self.filename) 165 | .field("original", &self.original.as_str()) 166 | .field("thumb_64x64", &self.thumb_64x64.as_str()) 167 | .field("thumb_128x128", &self.thumb_128x128.as_str()) 168 | .field("thumb_256x256", &self.thumb_256x256.as_str()) 169 | .finish() 170 | } 171 | } 172 | 173 | /// See the [Header Image Object](https://docs.mod.io/restapiref/#header-image-object) docs for more 174 | /// information. 175 | #[derive(Deserialize)] 176 | #[non_exhaustive] 177 | pub struct HeaderImage { 178 | pub filename: String, 179 | #[serde(with = "utils::url")] 180 | pub original: Url, 181 | } 182 | 183 | impl fmt::Debug for HeaderImage { 184 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 185 | f.debug_struct("HeaderImage") 186 | .field("filename", &self.filename) 187 | .field("original", &self.original.as_str()) 188 | .finish() 189 | } 190 | } 191 | 192 | /// See the [Game Statistics Object](https://docs.mod.io/restapiref/#game-stats-object) docs for more 193 | /// information. 194 | #[derive(Debug)] 195 | #[non_exhaustive] 196 | pub struct Statistics { 197 | pub game_id: GameId, 198 | pub mods_total: u32, 199 | pub subscribers_total: u32, 200 | pub downloads: Downloads, 201 | pub expired_at: Timestamp, 202 | } 203 | 204 | impl<'de> Deserialize<'de> for Statistics { 205 | fn deserialize>(deserializer: D) -> Result { 206 | #[derive(Deserialize)] 207 | #[serde(field_identifier, rename_all = "snake_case")] 208 | enum Field { 209 | GameId, 210 | ModsCountTotal, 211 | ModsSubscribersTotal, 212 | ModsDownloadsTotal, 213 | ModsDownloadsToday, 214 | ModsDownloadsDailyAverage, 215 | DateExpires, 216 | #[allow(dead_code)] 217 | Other(String), 218 | } 219 | 220 | struct StatisticsVisitor; 221 | 222 | impl<'de> Visitor<'de> for StatisticsVisitor { 223 | type Value = Statistics; 224 | 225 | fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 226 | formatter.write_str("struct Statistics") 227 | } 228 | 229 | fn visit_map>(self, mut map: A) -> Result { 230 | let mut game_id = None; 231 | let mut mods_total = None; 232 | let mut subscribers_total = None; 233 | let mut downloads_total = None; 234 | let mut downloads_today = None; 235 | let mut downloads_daily_average = None; 236 | let mut expired_at = None; 237 | 238 | while let Some(key) = map.next_key()? { 239 | match key { 240 | Field::GameId => { 241 | game_id.deserialize_value("game_id", &mut map)?; 242 | } 243 | Field::ModsCountTotal => { 244 | mods_total.deserialize_value("mods_count_total", &mut map)?; 245 | } 246 | Field::ModsSubscribersTotal => { 247 | subscribers_total 248 | .deserialize_value("mods_subscribers_total", &mut map)?; 249 | } 250 | Field::ModsDownloadsToday => { 251 | downloads_today.deserialize_value("mods_downloads_today", &mut map)?; 252 | } 253 | Field::ModsDownloadsTotal => { 254 | downloads_total.deserialize_value("mods_downloads_total", &mut map)?; 255 | } 256 | Field::ModsDownloadsDailyAverage => { 257 | downloads_daily_average 258 | .deserialize_value("mods_downloads_daily_average", &mut map)?; 259 | } 260 | Field::DateExpires => { 261 | expired_at.deserialize_value("date_expires", &mut map)?; 262 | } 263 | Field::Other(_) => { 264 | map.next_value::()?; 265 | } 266 | } 267 | } 268 | 269 | let game_id = game_id.missing_field("game_id")?; 270 | let mods_total = mods_total.missing_field("mods_count_total")?; 271 | let subscribers_total = 272 | subscribers_total.missing_field("mods_subscribers_total")?; 273 | let downloads_total = downloads_total.missing_field("mods_downloads_total")?; 274 | let downloads_today = downloads_today.missing_field("mods_downloads_today")?; 275 | let downloads_daily_average = 276 | downloads_daily_average.missing_field("mods_downloads_daily_average")?; 277 | let expired_at = expired_at.missing_field("date_expires")?; 278 | 279 | Ok(Statistics { 280 | game_id, 281 | mods_total, 282 | subscribers_total, 283 | downloads: Downloads { 284 | total: downloads_total, 285 | today: downloads_today, 286 | daily_average: downloads_daily_average, 287 | }, 288 | expired_at, 289 | }) 290 | } 291 | } 292 | 293 | deserializer.deserialize_map(StatisticsVisitor) 294 | } 295 | } 296 | 297 | /// Part of [`Statistics`] 298 | #[derive(Debug)] 299 | #[non_exhaustive] 300 | pub struct Downloads { 301 | pub total: u32, 302 | pub today: u32, 303 | pub daily_average: u32, 304 | } 305 | 306 | /// See the [Game Tag Option Object](https://docs.mod.io/restapiref/#game-tag-option-object) docs for more 307 | /// information. 308 | #[derive(Debug, Deserialize)] 309 | #[non_exhaustive] 310 | pub struct TagOption { 311 | pub name: String, 312 | #[serde(rename = "type")] 313 | pub kind: TagType, 314 | #[serde(rename = "tag_count_map")] 315 | pub tag_count: HashMap, 316 | pub hidden: bool, 317 | pub locked: bool, 318 | pub tags: Vec, 319 | } 320 | 321 | /// Defines the type of a tag. See [`TagOption`]. 322 | #[derive(Debug, Deserialize, Serialize)] 323 | #[serde(rename_all = "lowercase")] 324 | #[non_exhaustive] 325 | pub enum TagType { 326 | Checkboxes, 327 | Dropdown, 328 | } 329 | 330 | impl fmt::Display for TagType { 331 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { 332 | match self { 333 | Self::Checkboxes => fmt.write_str("checkboxes"), 334 | Self::Dropdown => fmt.write_str("dropdown"), 335 | } 336 | } 337 | } 338 | 339 | /// See the [Theme Object](https://docs.mod.io/restapiref/#theme-object) docs for more information. 340 | #[derive(Debug, Deserialize)] 341 | pub struct Theme { 342 | pub primary: String, 343 | pub dark: String, 344 | pub light: String, 345 | pub success: String, 346 | pub warning: String, 347 | pub danger: String, 348 | } 349 | 350 | /// See the [Game OtherUrls Object](https://docs.mod.io/restapiref/#game-otherurls-object) docs for more information. 351 | #[derive(Deserialize)] 352 | pub struct OtherUrl { 353 | pub label: String, 354 | #[serde(with = "utils::url")] 355 | pub url: Url, 356 | } 357 | 358 | impl fmt::Debug for OtherUrl { 359 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 360 | f.debug_struct("OtherUrl") 361 | .field("label", &self.label) 362 | .field("url", &self.url.as_str()) 363 | .finish() 364 | } 365 | } 366 | 367 | /// See the [Game Platforms Object](https://docs.mod.io/restapiref/#game-platforms-object) docs for more information. 368 | #[derive(Debug, Deserialize)] 369 | #[non_exhaustive] 370 | pub struct Platform { 371 | #[serde(rename = "platform")] 372 | pub target: TargetPlatform, 373 | pub moderated: bool, 374 | /// Indicates if users can upload files for this platform. 375 | pub locked: bool, 376 | } 377 | -------------------------------------------------------------------------------- /src/types/id.rs: -------------------------------------------------------------------------------- 1 | //! Type-safe ID type for each resource. 2 | 3 | use std::cmp::Ordering; 4 | use std::fmt::{self, Write}; 5 | use std::hash::{Hash, Hasher}; 6 | use std::marker::PhantomData; 7 | use std::num::{NonZeroI64, NonZeroU64, ParseIntError, TryFromIntError}; 8 | use std::str::FromStr; 9 | 10 | /// ID with a game marker. 11 | pub type GameId = Id; 12 | /// ID with a mod marker. 13 | pub type ModId = Id; 14 | /// ID with a file marker. 15 | pub type FileId = Id; 16 | /// ID with an event marker. 17 | pub type EventId = Id; 18 | /// ID with a comment marker. 19 | pub type CommentId = Id; 20 | /// ID with a user marker. 21 | pub type UserId = Id; 22 | /// ID with a team member marker. 23 | pub type MemberId = Id; 24 | /// ID with a resource marker. 25 | pub type ResourceId = Id; 26 | 27 | /// Markers for various resource types. 28 | pub mod marker { 29 | /// Marker for game IDs. 30 | #[non_exhaustive] 31 | pub struct GameMarker; 32 | 33 | /// Marker for mod IDs. 34 | #[non_exhaustive] 35 | pub struct ModMarker; 36 | 37 | /// Marker for file IDs. 38 | #[non_exhaustive] 39 | pub struct FileMarker; 40 | 41 | /// Marker for event IDs. 42 | #[non_exhaustive] 43 | pub struct EventMarker; 44 | 45 | /// Marker for comment IDs. 46 | #[non_exhaustive] 47 | pub struct CommentMarker; 48 | 49 | /// Marker for user IDs. 50 | #[non_exhaustive] 51 | pub struct UserMarker; 52 | 53 | /// Marker for team member IDs. 54 | #[non_exhaustive] 55 | pub struct MemberMarker; 56 | 57 | /// Marker for resource IDs. 58 | #[non_exhaustive] 59 | pub struct ResourceMarker; 60 | } 61 | 62 | /// ID of a resource, such as the ID of a [game] or [mod]. 63 | /// 64 | /// [game]: crate::types::games::Game 65 | /// [mod]: crate::types::mods::Mod 66 | #[repr(transparent)] 67 | pub struct Id { 68 | phantom: PhantomData T>, 69 | value: NonZeroU64, 70 | } 71 | 72 | impl Id { 73 | const fn from_nonzero(value: NonZeroU64) -> Self { 74 | Self { 75 | phantom: PhantomData, 76 | value, 77 | } 78 | } 79 | 80 | /// Create a new ID. 81 | /// 82 | /// # Examples 83 | /// 84 | /// ``` 85 | /// use modio::types::id::marker::GameMarker; 86 | /// use modio::types::id::Id; 87 | /// 88 | /// let id: Id = Id::new(123); 89 | /// 90 | /// // Using the provided type aliases. 91 | /// use modio::types::id::GameId; 92 | /// 93 | /// let game_id = GameId::new(123); 94 | /// 95 | /// assert_eq!(id, game_id); 96 | /// ``` 97 | /// 98 | /// # Panics 99 | /// 100 | /// Panics if the value is 0. 101 | #[track_caller] 102 | pub const fn new(value: u64) -> Self { 103 | if let Some(value) = Self::new_checked(value) { 104 | value 105 | } else { 106 | panic!("value is zero") 107 | } 108 | } 109 | 110 | /// Create a new ID if the given value is not zero. 111 | pub const fn new_checked(value: u64) -> Option { 112 | if let Some(value) = NonZeroU64::new(value) { 113 | Some(Self::from_nonzero(value)) 114 | } else { 115 | None 116 | } 117 | } 118 | 119 | pub const fn get(self) -> u64 { 120 | self.value.get() 121 | } 122 | 123 | pub const fn transform(self) -> Id { 124 | Id::new(self.get()) 125 | } 126 | } 127 | 128 | impl Clone for Id { 129 | fn clone(&self) -> Self { 130 | *self 131 | } 132 | } 133 | 134 | impl Copy for Id {} 135 | 136 | impl fmt::Debug for Id { 137 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 138 | f.write_str("Id")?; 139 | 140 | let name = std::any::type_name::(); 141 | if let Some(pos) = name.rfind("::") { 142 | if let Some(marker) = name.get(pos + 2..) { 143 | f.write_char('<')?; 144 | f.write_str(marker)?; 145 | f.write_char('>')?; 146 | } 147 | } 148 | 149 | f.write_char('(')?; 150 | fmt::Debug::fmt(&self.value, f)?; 151 | f.write_char(')') 152 | } 153 | } 154 | 155 | impl fmt::Display for Id { 156 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 157 | fmt::Display::fmt(&self.value, f) 158 | } 159 | } 160 | 161 | impl PartialEq for Id { 162 | fn eq(&self, other: &Self) -> bool { 163 | self.value == other.value 164 | } 165 | } 166 | 167 | impl Eq for Id {} 168 | 169 | impl PartialEq for Id { 170 | fn eq(&self, other: &u64) -> bool { 171 | self.value.get() == *other 172 | } 173 | } 174 | 175 | impl PartialEq> for u64 { 176 | fn eq(&self, other: &Id) -> bool { 177 | other.value.get() == *self 178 | } 179 | } 180 | 181 | impl PartialOrd for Id { 182 | fn partial_cmp(&self, other: &Self) -> Option { 183 | Some(self.cmp(other)) 184 | } 185 | } 186 | 187 | impl Ord for Id { 188 | fn cmp(&self, other: &Self) -> Ordering { 189 | self.value.cmp(&other.value) 190 | } 191 | } 192 | 193 | impl Hash for Id { 194 | fn hash(&self, state: &mut H) { 195 | state.write_u64(self.value.get()); 196 | } 197 | } 198 | 199 | impl From> for u64 { 200 | fn from(value: Id) -> Self { 201 | value.get() 202 | } 203 | } 204 | 205 | impl From for Id { 206 | fn from(value: NonZeroU64) -> Self { 207 | Self::from_nonzero(value) 208 | } 209 | } 210 | 211 | impl TryFrom for Id { 212 | type Error = TryFromIntError; 213 | 214 | fn try_from(value: i64) -> Result { 215 | let value = NonZeroI64::try_from(value)?; 216 | let value = NonZeroU64::try_from(value)?; 217 | Ok(Self::from_nonzero(value)) 218 | } 219 | } 220 | 221 | impl TryFrom for Id { 222 | type Error = TryFromIntError; 223 | 224 | fn try_from(value: u64) -> Result { 225 | let value = NonZeroU64::try_from(value)?; 226 | Ok(Id::from_nonzero(value)) 227 | } 228 | } 229 | 230 | impl FromStr for Id { 231 | type Err = ParseIntError; 232 | 233 | fn from_str(s: &str) -> Result { 234 | NonZeroU64::from_str(s).map(Self::from_nonzero) 235 | } 236 | } 237 | 238 | use serde::de::{Deserialize, Deserializer}; 239 | use serde::ser::{Serialize, Serializer}; 240 | 241 | impl<'de, T> Deserialize<'de> for Id { 242 | fn deserialize>(deserializer: D) -> Result { 243 | NonZeroU64::deserialize(deserializer).map(Self::from_nonzero) 244 | } 245 | } 246 | 247 | impl Serialize for Id { 248 | fn serialize(&self, serializer: S) -> Result { 249 | self.value.serialize(serializer) 250 | } 251 | } 252 | 253 | #[cfg(test)] 254 | mod tests { 255 | use std::str::FromStr; 256 | 257 | use super::marker::*; 258 | use super::Id; 259 | 260 | #[test] 261 | fn from_str() { 262 | assert_eq!( 263 | Id::::new(123), 264 | Id::::from_str("123").unwrap() 265 | ); 266 | assert!(Id::::from_str("0").is_err()); 267 | assert!(Id::::from_str("123a").is_err()); 268 | } 269 | 270 | #[test] 271 | fn try_from() { 272 | assert!(Id::::try_from(-123i64).is_err()); 273 | assert!(Id::::try_from(0i64).is_err()); 274 | assert_eq!(123u64, Id::::try_from(123i64).unwrap()); 275 | 276 | assert!(Id::::try_from(0u64).is_err()); 277 | assert_eq!(123u64, Id::::try_from(123u64).unwrap()); 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /src/types/macros.rs: -------------------------------------------------------------------------------- 1 | // macro: bitflags {{{ 2 | macro_rules! bitflags { 3 | ( 4 | $(#[$outer:meta])* 5 | $vis:vis struct $BitFlags:ident: $T:ty { 6 | $( 7 | $(#[$inner:ident $($args:tt)*])* 8 | const $Flag:ident = $value:expr; 9 | )* 10 | } 11 | 12 | $($t:tt)* 13 | ) => { 14 | $(#[$outer])* 15 | #[derive(Copy, Clone, Eq, PartialEq, Deserialize)] 16 | $vis struct $BitFlags($T); 17 | 18 | bitflags::bitflags! { 19 | impl $BitFlags: $T { 20 | $( 21 | $(#[$inner $($args)*])* 22 | const $Flag = $value; 23 | )* 24 | } 25 | } 26 | 27 | impl std::fmt::Debug for $BitFlags { 28 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 29 | struct Internal($BitFlags); 30 | impl std::fmt::Debug for Internal { 31 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 32 | bitflags::parser::to_writer(&self.0, f) 33 | } 34 | } 35 | let mut tuple = f.debug_tuple(stringify!($BitFlags)); 36 | if self.is_empty() { 37 | tuple.field(&format_args!("{0:#x}", <$T as bitflags::Bits>::EMPTY)); 38 | } else { 39 | tuple.field(&Internal(*self)); 40 | } 41 | tuple.finish() 42 | } 43 | } 44 | 45 | impl ::std::fmt::Display for $BitFlags { 46 | fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { 47 | self.bits().fmt(f) 48 | } 49 | } 50 | 51 | bitflags! { 52 | $($t)* 53 | } 54 | }; 55 | () => {}; 56 | } 57 | // }}} 58 | 59 | // macro: newtype_enum {{{ 60 | macro_rules! newtype_enum { 61 | ( 62 | $(#[$outer:meta])* 63 | $vis:vis struct $NewtypeEnum:ident: $T:ty { 64 | $( 65 | $(#[$inner:meta $($args:tt)*])* 66 | const $Variant:ident = $value:expr; 67 | )* 68 | } 69 | 70 | $($t:tt)* 71 | ) => { 72 | $(#[$outer])* 73 | #[derive(Clone, Copy, Eq, Hash, PartialEq, Deserialize)] 74 | $vis struct $NewtypeEnum($T); 75 | 76 | impl $NewtypeEnum { 77 | $( 78 | $(#[$inner $($args)*])* 79 | pub const $Variant: Self = Self($value); 80 | )* 81 | 82 | /// Create a new value from a raw value. 83 | pub fn new(raw_value: $T) -> Self { 84 | Self(raw_value) 85 | } 86 | 87 | /// Retrieve the raw value. 88 | pub fn get(self) -> $T { 89 | self.0 90 | } 91 | } 92 | 93 | impl std::fmt::Debug for $NewtypeEnum { 94 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 95 | match *self { 96 | $(Self::$Variant => f.write_str(concat!(stringify!($NewtypeEnum), "::", stringify!($Variant))),)* 97 | _ => f.debug_tuple(stringify!($NewtypeEnum)).field(&self.0).finish(), 98 | } 99 | } 100 | } 101 | 102 | impl std::fmt::Display for $NewtypeEnum { 103 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 104 | std::fmt::Display::fmt(&self.0, f) 105 | } 106 | } 107 | 108 | impl From<$T> for $NewtypeEnum { 109 | fn from(value: $T) -> Self { 110 | Self(value) 111 | } 112 | } 113 | 114 | impl From<$NewtypeEnum> for $T { 115 | fn from(value: $NewtypeEnum) -> $T { 116 | value.get() 117 | } 118 | } 119 | 120 | newtype_enum! { 121 | $($t)* 122 | } 123 | }; 124 | ( 125 | $(#[$outer:meta])* 126 | $vis:vis struct $NewtypeEnum:ident<$LENGTH:literal> { 127 | $( 128 | $(#[$inner:meta $($args:tt)*])* 129 | const $Variant:ident = $value:expr; 130 | )* 131 | } 132 | 133 | $($t:tt)* 134 | ) => { 135 | $(#[$outer])* 136 | #[derive(Clone, Copy, Eq, Hash, PartialEq)] 137 | $vis struct $NewtypeEnum(crate::types::utils::SmallStr<$LENGTH>); 138 | 139 | impl $NewtypeEnum { 140 | $( 141 | $(#[$inner $($args)*])* 142 | pub const $Variant: Self = Self::from_bytes($value); 143 | )* 144 | 145 | const fn from_bytes(input: &[u8]) -> Self { 146 | Self(crate::types::utils::SmallStr::from_bytes(input)) 147 | } 148 | 149 | pub fn as_str(&self) -> &str { 150 | self.0.as_str() 151 | } 152 | } 153 | 154 | impl std::fmt::Debug for $NewtypeEnum { 155 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 156 | match *self { 157 | $(Self::$Variant => f.write_str(concat!(stringify!($NewtypeEnum), "::", stringify!($Variant))),)* 158 | _ => f.debug_tuple(stringify!($NewtypeEnum)).field(&self.0).finish(), 159 | } 160 | } 161 | } 162 | 163 | impl PartialEq<&str> for $NewtypeEnum { 164 | fn eq(&self, other: &&str) -> bool { 165 | self.as_str().eq_ignore_ascii_case(other) 166 | } 167 | } 168 | 169 | impl PartialEq<$NewtypeEnum> for &str { 170 | fn eq(&self, other: &$NewtypeEnum) -> bool { 171 | self.eq_ignore_ascii_case(other.as_str()) 172 | } 173 | } 174 | 175 | impl PartialEq for $NewtypeEnum { 176 | fn eq(&self, other: &str) -> bool { 177 | self.as_str().eq_ignore_ascii_case(other) 178 | } 179 | } 180 | 181 | impl PartialEq<$NewtypeEnum> for str { 182 | fn eq(&self, other: &$NewtypeEnum) -> bool { 183 | self.eq_ignore_ascii_case(other.as_str()) 184 | } 185 | } 186 | 187 | newtype_enum! { 188 | $($t)* 189 | } 190 | }; 191 | () => {}; 192 | } 193 | // }}} 194 | 195 | // vim: fdm=marker 196 | -------------------------------------------------------------------------------- /src/types/utils.rs: -------------------------------------------------------------------------------- 1 | use serde::de::{DeserializeOwned, Error, MapAccess}; 2 | 3 | mod smallstr { 4 | use std::fmt; 5 | 6 | use serde::de::{Deserialize, Deserializer, Error, Visitor}; 7 | use serde::ser::{Serialize, Serializer}; 8 | 9 | #[derive(Clone, Copy, Eq, Hash, PartialEq)] 10 | pub struct SmallStr { 11 | bytes: [u8; LENGTH], 12 | } 13 | 14 | impl SmallStr { 15 | pub(crate) const fn from_str(input: &str) -> Option { 16 | if input.len() > LENGTH { 17 | return None; 18 | } 19 | Some(Self::from_bytes(input.as_bytes())) 20 | } 21 | 22 | pub(crate) const fn from_bytes(input: &[u8]) -> Self { 23 | let mut bytes = [0; LENGTH]; 24 | let mut idx = 0; 25 | 26 | while idx < input.len() { 27 | bytes[idx] = input[idx]; 28 | idx += 1; 29 | } 30 | 31 | Self { bytes } 32 | } 33 | 34 | pub fn as_str(&self) -> &str { 35 | std::str::from_utf8(&self.bytes) 36 | .expect("invalid utf8 string") 37 | .trim_end_matches('\0') 38 | } 39 | } 40 | 41 | impl fmt::Debug for SmallStr { 42 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 43 | f.write_str(self.as_str()) 44 | } 45 | } 46 | 47 | impl<'de, const LENGTH: usize> Deserialize<'de> for SmallStr { 48 | fn deserialize>(deserializer: D) -> Result { 49 | struct StrVisitor; 50 | 51 | impl Visitor<'_> for StrVisitor { 52 | type Value = SmallStr; 53 | 54 | fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 55 | formatter.write_str("string") 56 | } 57 | 58 | fn visit_str(self, v: &str) -> Result { 59 | SmallStr::from_str(v).ok_or_else(|| Error::custom("string is too long")) 60 | } 61 | 62 | fn visit_string(self, v: String) -> Result { 63 | SmallStr::from_str(&v).ok_or_else(|| Error::custom("string is too long")) 64 | } 65 | } 66 | 67 | deserializer.deserialize_any(StrVisitor::) 68 | } 69 | } 70 | 71 | impl Serialize for SmallStr { 72 | fn serialize(&self, serializer: S) -> Result { 73 | self.as_str().serialize(serializer) 74 | } 75 | } 76 | } 77 | pub use smallstr::SmallStr; 78 | 79 | pub mod url { 80 | use std::fmt; 81 | 82 | use serde::de::{Deserializer, Error, Visitor}; 83 | use url::Url; 84 | 85 | struct UrlVisitor; 86 | 87 | impl Visitor<'_> for UrlVisitor { 88 | type Value = Url; 89 | 90 | fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 91 | formatter.write_str("a string representing an URL") 92 | } 93 | 94 | fn visit_str(self, s: &str) -> Result { 95 | Url::parse(s).map_err(|err| Error::custom(format!("{err}: {s:?}"))) 96 | } 97 | } 98 | 99 | pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { 100 | deserializer.deserialize_any(UrlVisitor) 101 | } 102 | 103 | pub mod opt { 104 | use std::fmt; 105 | 106 | use serde::de::{Deserializer, Error, Visitor}; 107 | use url::Url; 108 | 109 | struct UrlVisitor; 110 | 111 | impl<'de> Visitor<'de> for UrlVisitor { 112 | type Value = Option; 113 | 114 | fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 115 | formatter.write_str("an optional string representing an URL") 116 | } 117 | 118 | fn visit_some>(self, d: D) -> Result { 119 | d.deserialize_any(super::UrlVisitor).map(Some) 120 | } 121 | 122 | fn visit_none(self) -> Result { 123 | Ok(None) 124 | } 125 | 126 | fn visit_unit(self) -> Result { 127 | Ok(None) 128 | } 129 | } 130 | 131 | pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { 132 | d.deserialize_option(UrlVisitor) 133 | } 134 | } 135 | } 136 | 137 | pub trait DeserializeField { 138 | fn deserialize_value<'de, A: MapAccess<'de>>( 139 | &mut self, 140 | name: &'static str, 141 | map: &mut A, 142 | ) -> Result<(), A::Error>; 143 | } 144 | 145 | impl DeserializeField for Option { 146 | fn deserialize_value<'de, A>(&mut self, name: &'static str, map: &mut A) -> Result<(), A::Error> 147 | where 148 | A: MapAccess<'de>, 149 | { 150 | if self.is_some() { 151 | return Err(A::Error::duplicate_field(name)); 152 | } 153 | self.replace(map.next_value()?); 154 | Ok(()) 155 | } 156 | } 157 | 158 | pub trait MissingField { 159 | fn missing_field(self, name: &'static str) -> Result; 160 | } 161 | 162 | impl MissingField for Option { 163 | fn missing_field(self, name: &'static str) -> Result { 164 | self.ok_or_else(|| Error::missing_field(name)) 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /src/user.rs: -------------------------------------------------------------------------------- 1 | //! User interface 2 | use crate::prelude::*; 3 | use crate::types::files::File; 4 | use crate::types::games::Game; 5 | use crate::types::id::UserId; 6 | use crate::types::mods::Mod; 7 | 8 | pub use crate::types::mods::Rating; 9 | pub use crate::types::{Avatar, User}; 10 | pub use crate::types::{Event, EventType}; 11 | 12 | /// Interface for resources owned by the authenticated user or is team member of. 13 | #[derive(Clone)] 14 | pub struct Me { 15 | modio: Modio, 16 | } 17 | 18 | impl Me { 19 | pub(crate) fn new(modio: Modio) -> Self { 20 | Self { modio } 21 | } 22 | 23 | /// Returns the current user if authenticated. 24 | pub async fn current(self) -> Result> { 25 | if self.modio.inner.credentials.token.is_some() { 26 | let user = self.modio.request(Route::UserAuthenticated).send().await?; 27 | Ok(Some(user)) 28 | } else { 29 | Ok(None) 30 | } 31 | } 32 | 33 | /// Returns a `Query` interface to retrieve all games the authenticated user added or 34 | /// is team member of. [required: token] 35 | /// 36 | /// See [Filters and sorting](filters::games). 37 | pub fn games(&self, filter: Filter) -> Query { 38 | Query::new(self.modio.clone(), Route::UserGames, filter) 39 | } 40 | 41 | /// Returns a `Query` interface to retrieve all mods the authenticated user added or 42 | /// is team member of. [required: token] 43 | /// 44 | /// See [Filters and sorting](filters::mods). 45 | pub fn mods(&self, filter: Filter) -> Query { 46 | Query::new(self.modio.clone(), Route::UserMods, filter) 47 | } 48 | 49 | /// Returns a `Query` interface to retrieve all modfiles the authenticated user uploaded. 50 | /// [required: token] 51 | /// 52 | /// See [Filters and sorting](filters::files). 53 | pub fn files(&self, filter: Filter) -> Query { 54 | Query::new(self.modio.clone(), Route::UserFiles, filter) 55 | } 56 | 57 | /// Returns a `Query` interface to retrieve the events that have been fired specific to the 58 | /// authenticated user. [required: token] 59 | /// 60 | /// See [Filters and sorting](filters::events). 61 | pub fn events(self, filter: Filter) -> Query { 62 | Query::new(self.modio, Route::UserEvents, filter) 63 | } 64 | 65 | /// Returns a `Query` interface to retrieve the mods the authenticated user is subscribed to. 66 | /// [required: token] 67 | /// 68 | /// See [Filters and sorting](filters::subscriptions). 69 | pub fn subscriptions(self, filter: Filter) -> Query { 70 | Query::new(self.modio, Route::UserSubscriptions, filter) 71 | } 72 | 73 | /// Returns a `Query` interface to retrieve the mod ratings submitted by the authenticated user. 74 | /// [required: token] 75 | /// 76 | /// See [Filters and sorting](filters::ratings). 77 | pub fn ratings(self, filter: Filter) -> Query { 78 | Query::new(self.modio, Route::UserRatings, filter) 79 | } 80 | 81 | /// Get all users muted by the authenticated user. [required: token] 82 | pub fn muted_users(self) -> Query { 83 | Query::new(self.modio, Route::UserMuted, Filter::default()) 84 | } 85 | 86 | /// Mute a user. [required: token] 87 | /// 88 | /// This will prevent mod.io from returning mods authored by the muted user. 89 | pub async fn mute_user(self, user_id: UserId) -> Result<()> { 90 | self.modio.request(Route::MuteUser { user_id }).send().await 91 | } 92 | 93 | /// Unmute a previously muted user. [required: token] 94 | /// 95 | /// This will re-enable mod.io return mods authored by the muted user again. 96 | pub async fn unmute_user(self, user_id: UserId) -> Result<()> { 97 | self.modio 98 | .request(Route::UnmuteUser { user_id }) 99 | .send() 100 | .await 101 | } 102 | } 103 | 104 | /// Filters for events, subscriptions and ratings. 105 | #[rustfmt::skip] 106 | pub mod filters { 107 | #[doc(inline)] 108 | pub use crate::games::filters as games; 109 | #[doc(inline)] 110 | pub use crate::mods::filters as mods; 111 | #[doc(inline)] 112 | pub use crate::files::filters as files; 113 | 114 | /// User event filters and sorting. 115 | /// 116 | /// # Filters 117 | /// - `Id` 118 | /// - `GameId` 119 | /// - `ModId` 120 | /// - `UserId` 121 | /// - `DateAdded` 122 | /// - `EventType` 123 | /// 124 | /// # Sorting 125 | /// - `Id` 126 | /// - `DateAdded` 127 | /// 128 | /// See the [modio docs](https://docs.mod.io/restapiref/#get-user-events) for more information. 129 | /// 130 | /// By default this returns up to `100` items. You can limit the result by using `limit` and 131 | /// `offset`. 132 | /// 133 | /// # Example 134 | /// ``` 135 | /// use modio::filter::prelude::*; 136 | /// use modio::mods::EventType; 137 | /// use modio::user::filters::events::EventType as Filter; 138 | /// 139 | /// let filter = Id::gt(1024).and(Filter::eq(EventType::MODFILE_CHANGED)); 140 | /// ``` 141 | pub mod events { 142 | #[doc(inline)] 143 | pub use crate::filter::prelude::Id; 144 | #[doc(inline)] 145 | pub use crate::filter::prelude::ModId; 146 | #[doc(inline)] 147 | pub use crate::filter::prelude::DateAdded; 148 | 149 | #[doc(inline)] 150 | pub use crate::mods::filters::events::UserId; 151 | #[doc(inline)] 152 | pub use crate::mods::filters::events::EventType; 153 | 154 | filter!(GameId, GAME_ID, "game_id", Eq, NotEq, In, Cmp, OrderBy); 155 | } 156 | 157 | /// Subscriptions filters and sorting. 158 | /// 159 | /// # Filters 160 | /// - `Fulltext` 161 | /// - `Id` 162 | /// - `GameId` 163 | /// - `Status` 164 | /// - `Visible` 165 | /// - `SubmittedBy` 166 | /// - `DateAdded` 167 | /// - `DateUpdated` 168 | /// - `DateLive` 169 | /// - `MaturityOption` 170 | /// - `Name` 171 | /// - `NameId` 172 | /// - `Summary` 173 | /// - `Description` 174 | /// - `Homepage` 175 | /// - `Modfile` 176 | /// - `MetadataBlob` 177 | /// - `MetadataKVP` 178 | /// - `Tags` 179 | /// 180 | /// # Sorting 181 | /// - `Id` 182 | /// - `Name` 183 | /// - `Downloads` 184 | /// - `Popular` 185 | /// - `Ratings` 186 | /// - `Subscribers` 187 | /// 188 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#get-user-subscriptions) for more information. 189 | /// 190 | /// By default this returns up to `100` items. you can limit the result by using `limit` and 191 | /// `offset`. 192 | /// 193 | /// # Example 194 | /// ``` 195 | /// use modio::filter::prelude::*; 196 | /// use modio::user::filters::subscriptions::Id; 197 | /// 198 | /// let filter = Id::_in(vec![1, 2]).order_by(Id::desc()); 199 | /// ``` 200 | pub mod subscriptions { 201 | #[doc(inline)] 202 | pub use crate::filter::prelude::Fulltext; 203 | #[doc(inline)] 204 | pub use crate::filter::prelude::Id; 205 | #[doc(inline)] 206 | pub use crate::filter::prelude::Name; 207 | #[doc(inline)] 208 | pub use crate::filter::prelude::NameId; 209 | 210 | #[doc(inline)] 211 | pub use crate::mods::filters::GameId; 212 | #[doc(inline)] 213 | pub use crate::mods::filters::Status; 214 | #[doc(inline)] 215 | pub use crate::mods::filters::Visible; 216 | #[doc(inline)] 217 | pub use crate::mods::filters::SubmittedBy; 218 | #[doc(inline)] 219 | pub use crate::mods::filters::DateAdded; 220 | #[doc(inline)] 221 | pub use crate::mods::filters::DateUpdated; 222 | #[doc(inline)] 223 | pub use crate::mods::filters::DateLive; 224 | #[doc(inline)] 225 | pub use crate::mods::filters::MaturityOption; 226 | #[doc(inline)] 227 | pub use crate::mods::filters::Summary; 228 | #[doc(inline)] 229 | pub use crate::mods::filters::Description; 230 | #[doc(inline)] 231 | pub use crate::mods::filters::Homepage; 232 | #[doc(inline)] 233 | pub use crate::mods::filters::Modfile; 234 | #[doc(inline)] 235 | pub use crate::mods::filters::MetadataBlob; 236 | #[doc(inline)] 237 | pub use crate::mods::filters::MetadataKVP; 238 | #[doc(inline)] 239 | pub use crate::mods::filters::Tags; 240 | 241 | #[doc(inline)] 242 | pub use crate::mods::filters::Downloads; 243 | #[doc(inline)] 244 | pub use crate::mods::filters::Popular; 245 | #[doc(inline)] 246 | pub use crate::mods::filters::Ratings; 247 | #[doc(inline)] 248 | pub use crate::mods::filters::Subscribers; 249 | } 250 | 251 | /// Rating filters and sorting. 252 | /// 253 | /// # Filters 254 | /// - `GameId` 255 | /// - `ModId` 256 | /// - `Rating` 257 | /// - `DateAdded` 258 | /// 259 | /// # Sorting 260 | /// - `GameId` 261 | /// - `ModId` 262 | /// - `Rating` 263 | /// - `DateAdded` 264 | /// 265 | /// See the [mod.io docs](https://docs.mod.io/restapiref/#get-user-ratings) for more information. 266 | /// 267 | /// By default this returns up to `100` items. You can limit the result by using `limit` and 268 | /// `offset`. 269 | /// 270 | /// # Example 271 | /// ``` 272 | /// use modio::filter::prelude::*; 273 | /// use modio::user::filters::ratings::GameId; 274 | /// use modio::user::filters::ratings::DateAdded; 275 | /// use modio::user::filters::ratings::Rating; 276 | /// 277 | /// let filter = GameId::_in(vec![1, 2]).order_by(DateAdded::desc()); 278 | /// 279 | /// let filter = Rating::positive().order_by(DateAdded::desc()); 280 | /// ``` 281 | pub mod ratings { 282 | use crate::filter::prelude::*; 283 | 284 | #[doc(inline)] 285 | pub use crate::filter::prelude::ModId; 286 | 287 | filter!(GameId, GAME_ID, "game_id", Eq, NotEq, In, Cmp, OrderBy); 288 | filter!(Rating, RATING, "rating", Eq, NotEq, In, Cmp, OrderBy); 289 | filter!(DateAdded, DATE_ADDED, "date_added", Eq, NotEq, In, Cmp, OrderBy); 290 | 291 | impl Rating { 292 | pub fn positive() -> Filter { 293 | Rating::eq(1) 294 | } 295 | 296 | pub fn negative() -> Filter { 297 | Rating::eq(-1) 298 | } 299 | } 300 | } 301 | } 302 | -------------------------------------------------------------------------------- /tests/fixtures/games-page5.json: -------------------------------------------------------------------------------- 1 | {"data":[{"id":263,"status":1,"submitted_by":{},"date_added":1575944990,"date_updated":1592887796,"date_live":1575945064,"presentation_option":0,"community_options":2867,"monetization_options":0,"monetization_team":{},"submission_option":1,"dependency_option":0,"curation_option":0,"revenue_options":0,"max_stock":0,"api_access_options":3,"maturity_options":0,"ugc_name":"Mods","token_name":"currency","icon":{"filename":"boxshot.2.png","original":"https:\/\/image.modcdn.io\/games\/8c19\/263\/boxshot.2.png","thumb_64x64":"https:\/\/thumb.modcdn.io\/games\/8c19\/263\/crop_64x64\/boxshot.2.png","thumb_128x128":"https:\/\/thumb.modcdn.io\/games\/8c19\/263\/crop_128x128\/boxshot.2.png","thumb_256x256":"https:\/\/thumb.modcdn.io\/games\/8c19\/263\/crop_256x256\/boxshot.2.png"},"logo":{"filename":"wip_2.1.jpg","original":"https:\/\/image.modcdn.io\/games\/8c19\/263\/wip_2.1.jpg","thumb_320x180":"https:\/\/thumb.modcdn.io\/games\/8c19\/263\/crop_320x180\/wip_2.1.jpg","thumb_640x360":"https:\/\/thumb.modcdn.io\/games\/8c19\/263\/crop_640x360\/wip_2.1.jpg","thumb_1280x720":"https:\/\/thumb.modcdn.io\/games\/8c19\/263\/crop_1280x720\/wip_2.1.jpg"},"header":{"filename":"logo_without_bg.png","original":"https:\/\/image.modcdn.io\/games\/8c19\/263\/logo_without_bg.png"},"name":"OpenMB","name_id":"openmb","summary":"Open Source role-playing game engine for Taleworlds' Mount & Blade Series written in C# using Ogre3d Engine","instructions":null,"instructions_url":null,"profile_url":"https:\/\/mod.io\/g\/openmb","other_urls":[{"url":"https:\/\/www.moddb.com\/games\/openmb","label":"Moddb"},{"url":"https:\/\/github.com\/cookgreen\/OpenMB","label":"Github"}],"tag_options":[],"theme":{"primary":"#8a6820","dark":"#2e281b","light":"#ffffff","success":"#68D391","warning":"#d6af2e","danger":"#ff000e"},"stats":{"game_id":263,"mods_count_total":2,"mods_downloads_today":0,"mods_downloads_total":720,"mods_downloads_daily_average":720,"mods_subscribers_total":13,"date_expires":86400},"platforms":[]},{"id":264,"status":1,"submitted_by":{},"date_added":1575970529,"date_updated":1722602256,"date_live":1583402866,"presentation_option":0,"community_options":2859,"monetization_options":0,"monetization_team":{},"submission_option":1,"dependency_option":3,"curation_option":0,"revenue_options":0,"max_stock":0,"api_access_options":1,"maturity_options":0,"ugc_name":"Items","token_name":"currency","icon":{"filename":"se-icon.png","original":"https:\/\/image.modcdn.io\/games\/d6ba\/264\/se-icon.png","thumb_64x64":"https:\/\/thumb.modcdn.io\/games\/d6ba\/264\/crop_64x64\/se-icon.png","thumb_128x128":"https:\/\/thumb.modcdn.io\/games\/d6ba\/264\/crop_128x128\/se-icon.png","thumb_256x256":"https:\/\/thumb.modcdn.io\/games\/d6ba\/264\/crop_256x256\/se-icon.png"},"logo":{"filename":"gamepreview_1920x1080.1.png","original":"https:\/\/image.modcdn.io\/games\/d6ba\/264\/gamepreview_1920x1080.1.png","thumb_320x180":"https:\/\/thumb.modcdn.io\/games\/d6ba\/264\/crop_320x180\/gamepreview_1920x1080.1.png","thumb_640x360":"https:\/\/thumb.modcdn.io\/games\/d6ba\/264\/crop_640x360\/gamepreview_1920x1080.1.png","thumb_1280x720":"https:\/\/thumb.modcdn.io\/games\/d6ba\/264\/crop_1280x720\/gamepreview_1920x1080.1.png"},"header":{"filename":"gamelogo.1.png","original":"https:\/\/image.modcdn.io\/games\/d6ba\/264\/gamelogo.1.png"},"name":"Space Engineers","name_id":"spaceengineers","summary":"Browse, discover, and download player-created worlds and blueprints. Saved world can be published from the Main Menu Load Game screen. Blueprint can be published as a copy of the grid added to the Blueprint screen.","instructions":"Use console version of Space Engineers to publish worlds and blueprints to mod.io.","instructions_url":"https:\/\/support.keenswh.com\/","profile_url":"https:\/\/mod.io\/g\/spaceengineers","other_urls":[{"url":"https:\/\/www.spaceengineersgame.com\/","label":"Homepage"},{"url":"https:\/\/store.steampowered.com\/app\/244850\/Space_Engineers\/","label":"Steam"},{"url":"https:\/\/www.microsoft.com\/p\/space-engineers\/9n17dxq7fkwn","label":"Xbox"},{"url":"https:\/\/store.playstation.com\/en-cz\/concept\/10002535\/","label":"PlayStation"}],"tag_options":[{"name":"Type","name_localized":"Type","type":"dropdown","tags":["Blueprint","World","ingameScript","Mod","scenario"],"tags_localized":{"Blueprint":"Blueprint","World":"World","ingameScript":"ingameScript","Mod":"Mod","scenario":"scenario"},"tag_count_map":{"Blueprint":122537,"World":14293,"ingameScript":461,"Mod":2363,"scenario":29},"hidden":false,"locked":false},{"name":"Blueprint Categories","name_localized":"Blueprint Categories","type":"checkboxes","tags":["Ship","Rover","Base","Other_Blueprint"],"tags_localized":{"Ship":"Ship","Rover":"Rover","Base":"Base","Other_Blueprint":"Other_Blueprint"},"tag_count_map":{"Ship":85010,"Rover":21560,"Base":16507,"Other_Blueprint":22030},"hidden":false,"locked":false},{"name":"Grid Size","name_localized":"Grid Size","type":"dropdown","tags":["Large_Grid","Small_Grid"],"tags_localized":{"Large_Grid":"Large_Grid","Small_Grid":"Small_Grid"},"tag_count_map":{"Large_Grid":66742,"Small_Grid":55789},"hidden":false,"locked":false},{"name":"World Categories","name_localized":"World Categories","type":"checkboxes","tags":["Story","PvP","Exploration","Survival","Other_World","No_Mod"],"tags_localized":{"Story":"Story","PvP":"PvP","Exploration":"Exploration","Survival":"Survival","Other_World":"Other_World","No_Mod":"No_Mod"},"tag_count_map":{"Story":3851,"PvP":4085,"Exploration":6605,"Survival":11206,"Other_World":5345,"No_Mod":2249},"hidden":false,"locked":false},{"name":"Safety","name_localized":"Safety","type":"dropdown","tags":["Safe","Experimental"],"tags_localized":{"Safe":"Safe","Experimental":"Experimental"},"tag_count_map":{"Safe":104112,"Experimental":10403},"hidden":false,"locked":false},{"name":"Mod Categories","name_localized":"Mod Categories","type":"checkboxes","tags":["Block","Skybox","Character","Animation","Respawn ship","Production","Script","Modpack","Asteroid","Planet","Hud","NPC","Other","NoScripts","ServerScripts"],"tags_localized":{"Block":"Block","Skybox":"Skybox","Character":"Character","Animation":"Animation","Respawn ship":"Respawn ship","Production":"Production","Script":"Script","Modpack":"Modpack","Asteroid":"Asteroid","Planet":"Planet","Hud":"Hud","NPC":"NPC","Other":"Other","NoScripts":"NoScripts","ServerScripts":"ServerScripts"},"tag_count_map":{"Block":1652,"Skybox":130,"Character":212,"Animation":67,"Respawn ship":363,"Production":388,"Script":215,"Modpack":618,"Asteroid":72,"Planet":233,"Hud":66,"NPC":154,"Other":960,"NoScripts":3146,"ServerScripts":154},"hidden":false,"locked":false},{"name":"Script Categories","name_localized":"Script Categories","type":"dropdown","tags":["inventory management","visualization","autopilot","other_script"],"tags_localized":{"inventory management":"inventory management","visualization":"visualization","autopilot":"autopilot","other_script":"other_script"},"tag_count_map":{"inventory management":98,"visualization":96,"autopilot":99,"other_script":302},"hidden":false,"locked":false}],"theme":{"primary":"#c94949","dark":"#151515","light":"#ffffff","success":"#68D391","warning":"#d6af2e","danger":"#ff000e"},"stats":{"game_id":264,"mods_count_total":140044,"mods_downloads_today":40984,"mods_downloads_total":74264676,"mods_downloads_daily_average":74264676,"mods_subscribers_total":10250296,"date_expires":86400},"platforms":[]},{"id":295,"status":1,"submitted_by":{},"date_added":1579748997,"date_updated":1627711703,"date_live":1580109774,"presentation_option":0,"community_options":2859,"monetization_options":0,"monetization_team":{},"submission_option":0,"dependency_option":0,"curation_option":0,"revenue_options":0,"max_stock":0,"api_access_options":3,"maturity_options":0,"ugc_name":"Mods","token_name":"currency","icon":{"filename":"justrpm_512.png","original":"https:\/\/image.modcdn.io\/games\/4918\/295\/justrpm_512.png","thumb_64x64":"https:\/\/thumb.modcdn.io\/games\/4918\/295\/crop_64x64\/justrpm_512.png","thumb_128x128":"https:\/\/thumb.modcdn.io\/games\/4918\/295\/crop_128x128\/justrpm_512.png","thumb_256x256":"https:\/\/thumb.modcdn.io\/games\/4918\/295\/crop_256x256\/justrpm_512.png"},"logo":{"filename":"modiologo.1.png","original":"https:\/\/image.modcdn.io\/games\/4918\/295\/modiologo.1.png","thumb_320x180":"https:\/\/thumb.modcdn.io\/games\/4918\/295\/crop_320x180\/modiologo.1.png","thumb_640x360":"https:\/\/thumb.modcdn.io\/games\/4918\/295\/crop_640x360\/modiologo.1.png","thumb_1280x720":"https:\/\/thumb.modcdn.io\/games\/4918\/295\/crop_1280x720\/modiologo.1.png"},"header":{"filename":"dash-panel.png","original":"https:\/\/image.modcdn.io\/games\/4918\/295\/dash-panel.png"},"name":"Dashpanel","name_id":"dashpanel","summary":"Discover custom dashboards made by the community.","instructions":"Select your dashboard in the user saves tab of DashPanel.\nPress the upload button (Cloud with up arrow)\nFirst time you may need to authenticate via email key.\nFill in details on Upload Layout dialog.\nPress the Submit button.","instructions_url":null,"profile_url":"https:\/\/mod.io\/g\/dashpanel","other_urls":[{"url":"https:\/\/store.steampowered.com\/app\/715670\/DashPanel\/","label":"Steam"},{"url":"https:\/\/play.google.com\/store\/apps\/details?id=com.PyrofrogStudios.DashPanel","label":"Android"},{"url":"https:\/\/apps.apple.com\/au\/app\/dashpanel\/id1441894380","label":"iOS"},{"url":"https:\/\/www.pyrofrogstudios.com\/dashpanel.html","label":"Homepage"}],"tag_options":[{"name":"Style","name_localized":"Style","type":"dropdown","tags":["GT","Formula","Classic","Street","Rally","Prototype","Map","Overlay","Button Box"],"tags_localized":{"GT":"GT","Formula":"Formula","Classic":"Classic","Street":"Street","Rally":"Rally","Prototype":"Prototype","Map":"Map","Overlay":"Overlay","Button Box":"Button Box"},"tag_count_map":{"GT":1380,"Formula":1482,"Classic":626,"Street":708,"Rally":233,"Prototype":404,"Map":111,"Overlay":234,"Button Box":560},"hidden":false,"locked":false},{"name":"Game","name_localized":"Game","type":"dropdown","tags":["Assetto Corsa","ACC","AMS","BeamNG","Dirt","F1 Codemasters","Farming Simulator","Forza","iRacing","KartKraft","Le Mans Ultimate","Live For Speed","pCars","rFactor","R3E","Truck Simulator","Other"],"tags_localized":{"Assetto Corsa":"Assetto Corsa","ACC":"ACC","AMS":"AMS","BeamNG":"BeamNG","Dirt":"Dirt","F1 Codemasters":"F1 Codemasters","Farming Simulator":"Farming Simulator","Forza":"Forza","iRacing":"iRacing","KartKraft":"KartKraft","Le Mans Ultimate":"Le Mans Ultimate","Live For Speed":"Live For Speed","pCars":"pCars","rFactor":"rFactor","R3E":"R3E","Truck Simulator":"Truck Simulator","Other":"Other"},"tag_count_map":{"Assetto Corsa":764,"ACC":392,"AMS":179,"BeamNG":138,"Dirt":132,"F1 Codemasters":988,"Farming Simulator":34,"Forza":739,"iRacing":519,"KartKraft":40,"Le Mans Ultimate":4,"Live For Speed":74,"pCars":441,"rFactor":145,"R3E":347,"Truck Simulator":1348,"Other":287},"hidden":false,"locked":false}],"theme":{"primary":"#7c7ce6","dark":"#272628","light":"#ffffff","success":"#68D391","warning":"#d6af2e","danger":"#ff000e"},"stats":{"game_id":295,"mods_count_total":8134,"mods_downloads_today":339,"mods_downloads_total":988161,"mods_downloads_daily_average":988161,"mods_subscribers_total":69785,"date_expires":86400},"platforms":[]},{"id":296,"status":1,"submitted_by":{},"date_added":1579972656,"date_updated":1580312761,"date_live":1579972947,"presentation_option":0,"community_options":2859,"monetization_options":0,"monetization_team":{},"submission_option":1,"dependency_option":0,"curation_option":0,"revenue_options":0,"max_stock":0,"api_access_options":3,"maturity_options":0,"ugc_name":"Mods","token_name":"currency","icon":{"filename":"icon5.png","original":"https:\/\/image.modcdn.io\/games\/d296\/296\/icon5.png","thumb_64x64":"https:\/\/thumb.modcdn.io\/games\/d296\/296\/crop_64x64\/icon5.png","thumb_128x128":"https:\/\/thumb.modcdn.io\/games\/d296\/296\/crop_128x128\/icon5.png","thumb_256x256":"https:\/\/thumb.modcdn.io\/games\/d296\/296\/crop_256x256\/icon5.png"},"logo":{"filename":"modio1_c2.png","original":"https:\/\/image.modcdn.io\/games\/d296\/296\/modio1_c2.png","thumb_320x180":"https:\/\/thumb.modcdn.io\/games\/d296\/296\/crop_320x180\/modio1_c2.png","thumb_640x360":"https:\/\/thumb.modcdn.io\/games\/d296\/296\/crop_640x360\/modio1_c2.png","thumb_1280x720":"https:\/\/thumb.modcdn.io\/games\/d296\/296\/crop_1280x720\/modio1_c2.png"},"header":{"filename":"duskwhite.png","original":"https:\/\/image.modcdn.io\/games\/d296\/296\/duskwhite.png"},"name":"DUSK","name_id":"dusk","summary":"The DUSK SDK currently supports custom maps, textures, and sounds... with support for scripting, models and much more coming... SOON\u2122","instructions":null,"instructions_url":"https:\/\/dev.newblood.games\/index.php\/Main_Page","profile_url":"https:\/\/mod.io\/g\/dusk","other_urls":[{"url":"https:\/\/discordapp.com\/invite\/newblood","label":"the New Blood Discord"},{"url":"https:\/\/dev.newblood.games\/index.php\/Main_Page","label":"New Blood Dev Wiki"},{"url":"https:\/\/steamcommunity.com\/app\/519860\/discussions\/7\/","label":"Steam SDK Forums"},{"url":"https:\/\/twitter.com\/DuskDev","label":"and Twitter"}],"tag_options":[{"name":"Mods","name_localized":"Mods","type":"checkboxes","tags":["Levels","Textures","Sounds"],"tags_localized":{"Levels":"Levels","Textures":"Textures","Sounds":"Sounds"},"tag_count_map":{"Levels":85,"Textures":64,"Sounds":53},"hidden":false,"locked":false}],"theme":{"primary":"#eb1515","dark":"#030303","light":"#ffffff","success":"#68D391","warning":"#d6af2e","danger":"#ff000e"},"stats":{"game_id":296,"mods_count_total":174,"mods_downloads_today":2,"mods_downloads_total":156723,"mods_downloads_daily_average":156723,"mods_subscribers_total":4832,"date_expires":86400},"platforms":[]},{"id":304,"status":1,"submitted_by":{},"date_added":1580710696,"date_updated":1611569908,"date_live":1598282281,"presentation_option":0,"community_options":2856,"monetization_options":0,"monetization_team":{},"submission_option":0,"dependency_option":0,"curation_option":0,"revenue_options":0,"max_stock":0,"api_access_options":2,"maturity_options":0,"ugc_name":"Worlds","token_name":"currency","icon":{"filename":"fun_with_ragdolls_icon_half.jpg","original":"https:\/\/image.modcdn.io\/games\/37bc\/304\/fun_with_ragdolls_icon_half.jpg","thumb_64x64":"https:\/\/thumb.modcdn.io\/games\/37bc\/304\/crop_64x64\/fun_with_ragdolls_icon_half.jpg","thumb_128x128":"https:\/\/thumb.modcdn.io\/games\/37bc\/304\/crop_128x128\/fun_with_ragdolls_icon_half.jpg","thumb_256x256":"https:\/\/thumb.modcdn.io\/games\/37bc\/304\/crop_256x256\/fun_with_ragdolls_icon_half.jpg"},"logo":{"filename":"fwrdtg.jpg","original":"https:\/\/image.modcdn.io\/games\/37bc\/304\/fwrdtg.jpg","thumb_320x180":"https:\/\/thumb.modcdn.io\/games\/37bc\/304\/crop_320x180\/fwrdtg.jpg","thumb_640x360":"https:\/\/thumb.modcdn.io\/games\/37bc\/304\/crop_640x360\/fwrdtg.jpg","thumb_1280x720":"https:\/\/thumb.modcdn.io\/games\/37bc\/304\/crop_1280x720\/fwrdtg.jpg"},"header":{"filename":"fun_with_ragdolls_logo_white.png","original":"https:\/\/image.modcdn.io\/games\/37bc\/304\/fun_with_ragdolls_logo_white.png"},"name":"Fun with Ragdolls: The Game","name_id":"funwithragdolls","summary":"Explore community-created worlds!","instructions":null,"instructions_url":"https:\/\/www.funwithragdolls.com\/","profile_url":"https:\/\/mod.io\/g\/funwithragdolls","other_urls":[{"url":"https:\/\/store.steampowered.com\/app\/1142500\/Fun_with_Ragdolls_The_Game\/","label":"Steam"},{"url":"https:\/\/apps.apple.com\/us\/app\/fun-with-ragdolls\/id1459459021","label":"iOS"}],"tag_options":[{"name":"World Type","name_localized":"World Type","type":"dropdown","tags":["Official","Minigame","Exploration","Art","Puzzle","Chaos"],"tags_localized":{"Official":"Official","Minigame":"Minigame","Exploration":"Exploration","Art":"Art","Puzzle":"Puzzle","Chaos":"Chaos"},"tag_count_map":{"Official":95,"Minigame":5683,"Exploration":2817,"Art":907,"Puzzle":1185,"Chaos":8231},"hidden":false,"locked":false}],"theme":{"primary":"#fb900e","dark":"#04101f","light":"#ffffff","success":"#68D391","warning":"#d6af2e","danger":"#ff000e"},"stats":{"game_id":304,"mods_count_total":24670,"mods_downloads_today":2864,"mods_downloads_total":15353335,"mods_downloads_daily_average":15353335,"mods_subscribers_total":454790,"date_expires":86400},"platforms":[]}],"result_count":5,"result_offset":28,"result_limit":7,"result_total":33} -------------------------------------------------------------------------------- /tests/query.rs: -------------------------------------------------------------------------------- 1 | use futures_util::{Stream, TryStreamExt}; 2 | use httptest::{matchers::*, responders::*}; 3 | use httptest::{Expectation, Server}; 4 | 5 | use modio::filter::prelude::*; 6 | use modio::types::id::Id; 7 | use modio::{Modio, Result}; 8 | 9 | macro_rules! expect_requests { 10 | ($server:expr, $(query:$query:expr, body:$body:expr),*) => { 11 | $( 12 | $server.expect( 13 | Expectation::matching(all_of![ 14 | request::method("GET"), 15 | request::path("/v1/games"), 16 | request::query(url_decoded($query)), 17 | ]) 18 | .respond_with(status_code(200).body($body)), 19 | ); 20 | )* 21 | }; 22 | } 23 | 24 | fn create_empty_result() -> Server { 25 | let server = Server::run(); 26 | 27 | expect_requests!( 28 | server, 29 | query: any(), 30 | body: r#"{"data":[],"result_count":0,"result_offset":0,"result_limit":100,"result_total":0}"# 31 | ); 32 | 33 | server 34 | } 35 | 36 | fn create_first_page_only() -> Server { 37 | let server = Server::run(); 38 | 39 | expect_requests!( 40 | server, 41 | query: not(contains(key("_offset"))), 42 | body: include_str!("fixtures/games-page1.json") 43 | ); 44 | 45 | server 46 | } 47 | 48 | fn create_games_endpoint() -> Server { 49 | let server = Server::run(); 50 | 51 | expect_requests!( 52 | server, 53 | query: not(contains(key("_offset"))), 54 | body: include_str!("fixtures/games-page1.json"), 55 | 56 | query: contains(("_offset", "7")), 57 | body: include_str!("fixtures/games-page2.json"), 58 | 59 | query: contains(("_offset", "14")), 60 | body: include_str!("fixtures/games-page3.json"), 61 | 62 | query: contains(("_offset", "21")), 63 | body: include_str!("fixtures/games-page4.json"), 64 | 65 | query: contains(("_offset", "28")), 66 | body: include_str!("fixtures/games-page5.json") 67 | ); 68 | 69 | server 70 | } 71 | 72 | #[tokio::test] 73 | async fn empty_first() -> Result<()> { 74 | let server = create_empty_result(); 75 | 76 | let modio = Modio::host(server.url_str("/v1"), "foobar")?; 77 | let first = modio.games().search(Filter::default()).first().await?; 78 | 79 | assert!(first.is_none()); 80 | Ok(()) 81 | } 82 | 83 | #[tokio::test] 84 | async fn first() -> Result<()> { 85 | let server = create_first_page_only(); 86 | 87 | let modio = Modio::host(server.url_str("/v1"), "foobar")?; 88 | let first = modio.games().search(Filter::default()).first().await?; 89 | 90 | assert!(first.is_some()); 91 | assert_eq!(Id::new(2), first.unwrap().id, "id of first item"); 92 | Ok(()) 93 | } 94 | 95 | #[tokio::test] 96 | async fn empty_first_page() -> Result<()> { 97 | let server = create_empty_result(); 98 | 99 | let modio = Modio::host(server.url_str("/v1"), "foobar")?; 100 | let filter = Filter::default(); 101 | let list = modio.games().search(filter).first_page().await?; 102 | 103 | assert!(list.is_empty()); 104 | Ok(()) 105 | } 106 | 107 | #[tokio::test] 108 | async fn first_page() -> Result<()> { 109 | let server = create_first_page_only(); 110 | 111 | let modio = Modio::host(server.url_str("/v1"), "foobar")?; 112 | let filter = Filter::default(); 113 | let list = modio.games().search(filter).first_page().await?; 114 | 115 | assert_eq!(7, list.len(), "result count"); 116 | assert_eq!(Id::new(2), list[0].id, "id of first item"); 117 | assert_eq!(Id::new(51), list[6].id, "id of last item"); 118 | Ok(()) 119 | } 120 | 121 | #[tokio::test] 122 | async fn empty_collect() -> Result<()> { 123 | let server = create_empty_result(); 124 | 125 | let modio = Modio::host(server.url_str("/v1"), "foobar")?; 126 | let list = modio.games().search(Filter::default()).collect().await?; 127 | 128 | assert!(list.is_empty()); 129 | Ok(()) 130 | } 131 | 132 | #[tokio::test] 133 | async fn collect() -> Result<()> { 134 | let server = create_games_endpoint(); 135 | 136 | let modio = Modio::host(server.url_str("/v1"), "foobar")?; 137 | let list = modio.games().search(Filter::default()).collect().await?; 138 | 139 | assert_eq!(33, list.len(), "result count"); 140 | assert_eq!(Id::new(2), list[0].id, "id of first item"); 141 | assert_eq!(Id::new(295), list[30].id, "id of last item"); 142 | Ok(()) 143 | } 144 | 145 | #[tokio::test] 146 | async fn empty_paged() -> Result<()> { 147 | let server = create_empty_result(); 148 | 149 | let modio = Modio::host(server.url_str("/v1"), "foobar")?; 150 | let mut st = modio.games().search(Filter::default()).paged().await?; 151 | 152 | assert_eq!((0, None), st.size_hint()); 153 | assert!(st.try_next().await?.is_none()); 154 | Ok(()) 155 | } 156 | 157 | #[tokio::test] 158 | async fn paged() -> Result<()> { 159 | let server = create_games_endpoint(); 160 | 161 | let modio = Modio::host(server.url_str("/v1"), "foobar")?; 162 | let filter = with_limit(7); 163 | 164 | let mut iter = modio.games().search(filter).paged().await?; 165 | let mut total = 0; 166 | let mut count = 0; 167 | // First & Last Game ID's of every loaded page result 168 | let mut ids = vec![(2, 51), (63, 139), (152, 214), (224, 254), (263, 304)].into_iter(); 169 | let size_hint = iter.size_hint(); 170 | 171 | while let Ok(Some(list)) = iter.try_next().await { 172 | if let Some((first, last)) = ids.next().map(|(i, j)| (Id::new(i), Id::new(j))) { 173 | assert_eq!( 174 | list.first().map(|g| g.id), 175 | Some(first), 176 | "id of first item from page {}", 177 | count + 1 178 | ); 179 | assert_eq!( 180 | list.last().map(|g| g.id), 181 | Some(last), 182 | "id of last item from page {}", 183 | count + 1 184 | ); 185 | } 186 | count += 1; 187 | total += list.len(); 188 | } 189 | 190 | assert_eq!(count, 5); 191 | assert_eq!(total, 33); 192 | assert_eq!((count, None), size_hint); 193 | Ok(()) 194 | } 195 | 196 | #[tokio::test] 197 | async fn iter() -> Result<()> { 198 | let server = create_games_endpoint(); 199 | 200 | let modio = Modio::host(server.url_str("/v1"), "foobar")?; 201 | let filter = with_limit(7); 202 | 203 | let mut iter = modio.games().search(filter).iter().await?; 204 | let mut count = 0; 205 | let size_hint = iter.size_hint(); 206 | 207 | while let Ok(Some(_)) = iter.try_next().await { 208 | count += 1; 209 | } 210 | 211 | assert_eq!(count, 33); 212 | assert_eq!((count, None), size_hint); 213 | Ok(()) 214 | } 215 | --------------------------------------------------------------------------------