mirror of
https://github.com/tribufu/sdk-rust
synced 2026-02-04 17:33:07 +00:00
Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fdb135051b | |||
|
|
e701f20c1a | ||
|
|
7c2ce3bcb6 | ||
|
|
bff0dc0344 | ||
|
|
d9c4c40749 | ||
|
|
9861f51733 | ||
|
|
890c899a8b | ||
|
|
0168cd14e7 | ||
|
|
d29a5f6216 | ||
|
|
a2dec0eaa5 | ||
|
|
b583d26e44 | ||
|
|
40a5cd78f8 | ||
|
|
8947084800 | ||
|
|
f702516ad1 | ||
|
|
ddca33b5ee | ||
|
|
7e8c8d1d4c | ||
|
|
f1219f0fa3 | ||
|
|
a7d4bc3fe3 | ||
|
|
f63f64103c |
27
Cargo.toml
27
Cargo.toml
@@ -1,30 +1,49 @@
|
||||
[package]
|
||||
name = "tribufu"
|
||||
version = "0.0.4"
|
||||
version = "0.1.0"
|
||||
description = "Tribufu SDK"
|
||||
repository = "https://github.com/Tribufu/SDK-Rust"
|
||||
repository = "https://github.com/Tribufu/TribufuRust"
|
||||
authors = ["Tribufu <contact@tribufu.com>"]
|
||||
license = "Apache-2.0"
|
||||
license = "MIT"
|
||||
readme = "README.md"
|
||||
edition = "2021"
|
||||
publish = true
|
||||
|
||||
exclude = [".github/", ".vscode/", ".editorconfig", ".gitattributes"]
|
||||
exclude = [
|
||||
".editorconfig",
|
||||
".gitattributes",
|
||||
".github/",
|
||||
".vscode/",
|
||||
"examples/",
|
||||
"scripts/",
|
||||
]
|
||||
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["src/*"]
|
||||
|
||||
[lib]
|
||||
name = "tribufu"
|
||||
crate-type = ["rlib"]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[features]
|
||||
#actix = ["tribufu-actix"]
|
||||
|
||||
[dependencies]
|
||||
#tribufu-actix = { version = "0.1.0", path = "./src/actix", optional = true }
|
||||
alnilam-consts = { version = "0.0.4" }
|
||||
anyhow = "1.0.75"
|
||||
base64 = "0.21.5"
|
||||
chrono = { version = "0.4.22", features = ["serde", "rustc-serialize"] }
|
||||
derive_more = "0.99.17"
|
||||
mintaka-error = { version = "0.0.1" }
|
||||
reqwest = { version = "0.11.18", features = ["json", "stream"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = { version = "1.0", features = ["raw_value"] }
|
||||
serde_with = "3.4.0"
|
||||
tribufu-constants = { version = "0.1.0", path = "./src/constants" }
|
||||
tribufu-types = { version = "0.1.0", path = "./src/types" }
|
||||
|
||||
[dev-dependencies]
|
||||
dotenv = "0.15.0"
|
||||
|
||||
214
LICENSE.txt
214
LICENSE.txt
@@ -1,201 +1,21 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
MIT License
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
1. Definitions.
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
24
README.md
24
README.md
@@ -1 +1,23 @@
|
||||
# Tribufu SDK
|
||||
# Tribufu Rust
|
||||
|
||||
Rust SDK to access Tribufu APIs and services.
|
||||
|
||||
[![Crates.io][crates-badge]][crates-url]
|
||||
[![MIT License][mit-badge]][mit-url]
|
||||
[![Discord Chat][discord-badge]][discord-url]
|
||||
|
||||
[crates-badge]: https://img.shields.io/crates/v/tribufu.svg
|
||||
[crates-url]: https://crates.io/crates/tribufu
|
||||
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
|
||||
[mit-url]: https://github.com/Tribufu/TribufuRust/blob/main/LICENSE.txt
|
||||
[discord-badge]: https://img.shields.io/discord/276504514616623104.svg?logo=discord&style=flat-square
|
||||
[discord-url]: https://www.tribufu.com/discord
|
||||
|
||||
[Website](https://www.tribufu.com) |
|
||||
[Discord](https://www.tribufu.com/discord)
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the [MIT License].
|
||||
|
||||
[MIT License]: https://github.com/Tribufu/TribufuRust/blob/main/LICENSE.txt
|
||||
|
||||
10
examples/api.rs
Normal file
10
examples/api.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved
|
||||
|
||||
use tribufu::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let api = TribufuApi::default();
|
||||
let games = api.get_games(Some(1)).await.unwrap();
|
||||
println!("{:?}", games);
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved
|
||||
|
||||
use tribufu::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
match TribufuClient::new(0, "client_secret") {
|
||||
Ok(client) => println!("client_id: {}", client.id()),
|
||||
Err(e) => println!("error: {:?}", e),
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,10 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved
|
||||
|
||||
use dotenv::dotenv;
|
||||
use std::env;
|
||||
use tribufu::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
dotenv().ok();
|
||||
|
||||
let client_id = env::var("CLIENT_ID").unwrap().parse::<u64>().unwrap();
|
||||
let client_secret = env::var("CLIENT_SECRET").unwrap();
|
||||
|
||||
let mut client = TribufuClient::new(client_id, client_secret).unwrap();
|
||||
|
||||
client.get_token(None).await.unwrap();
|
||||
|
||||
let games = client.get_games().await.unwrap();
|
||||
|
||||
games.iter().for_each(|game| {
|
||||
println!("{}", game.name);
|
||||
});
|
||||
let api = TribufuApi::with_client_from_env().unwrap_or_default();
|
||||
let games = api.get_games(Some(1)).await.unwrap();
|
||||
println!("{:?}", games);
|
||||
}
|
||||
|
||||
34
scripts/publish.ps1
Normal file
34
scripts/publish.ps1
Normal file
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env pwsh
|
||||
|
||||
$crates = @(
|
||||
"tribufu-types",
|
||||
"tribufu-constants",
|
||||
"tribufu-api",
|
||||
"tribufu"
|
||||
)
|
||||
|
||||
$batchSize = 6
|
||||
$waitTime = 300
|
||||
|
||||
function Process-Batch {
|
||||
param (
|
||||
[Parameter(Mandatory=$true)]
|
||||
[array]$batch
|
||||
)
|
||||
|
||||
foreach ($element in $batch) {
|
||||
Write-Output "Processing element $element"
|
||||
cargo publish --package $element
|
||||
}
|
||||
}
|
||||
|
||||
for ($i = 0; $i -lt $crates.Count; $i += $batchSize) {
|
||||
$currentBatch = $crates[$i..($i + $batchSize - 1)]
|
||||
|
||||
Process-Batch -batch $currentBatch
|
||||
|
||||
if ($i -lt ($crates.Count - $batchSize)) {
|
||||
Write-Output "Waiting for $waitTime seconds..."
|
||||
Start-Sleep -Seconds $waitTime
|
||||
}
|
||||
}
|
||||
19
src/actix/Cargo.toml
Normal file
19
src/actix/Cargo.toml
Normal file
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "tribufu-actix"
|
||||
version = "0.1.0"
|
||||
description = "Tribufu Actix Extension"
|
||||
repository = "https://github.com/Tribufu/TribufuRust"
|
||||
authors = ["Tribufu <contact@tribufu.com>"]
|
||||
license = "MIT"
|
||||
edition = "2021"
|
||||
publish = true
|
||||
|
||||
[lib]
|
||||
name = "tribufu_actix"
|
||||
crate-type = ["rlib"]
|
||||
path = "lib.rs"
|
||||
|
||||
[dependencies]
|
||||
#tribufu-api = { path = "../api" }
|
||||
actix-web = { version = "4", features = ["rustls"] }
|
||||
mintaka-error = { version = "0.0.1" }
|
||||
25
src/actix/lib.rs
Normal file
25
src/actix/lib.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
use actix_web::HttpRequest;
|
||||
|
||||
pub trait TribufuApiActixExtension {
|
||||
fn from_actix(req: &HttpRequest) -> Self;
|
||||
}
|
||||
|
||||
/*
|
||||
impl TribufuApiActixExtension for TribufuApi {
|
||||
fn from_actix(req: &HttpRequest) -> Self {
|
||||
let mut api = Self::with_client_from_env().unwrap_or_default();
|
||||
|
||||
if let Some(authorization) = req.headers().get("Authorization") {
|
||||
let authorization = authorization.to_str().unwrap();
|
||||
|
||||
if authorization.starts_with("Bearer ") {
|
||||
api = Self::with_user(authorization[7..].to_string());
|
||||
}
|
||||
}
|
||||
|
||||
return api;
|
||||
}
|
||||
}
|
||||
*/
|
||||
118
src/api.rs
Normal file
118
src/api.rs
Normal file
@@ -0,0 +1,118 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
use std::env;
|
||||
|
||||
use reqwest::{
|
||||
header::{HeaderMap, HeaderValue, AUTHORIZATION},
|
||||
Client as HttpClient,
|
||||
};
|
||||
use tribufu_constants::{TRIBUFU_API_URL, TRIBUFU_VERSION};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub enum TribufuApiOptions {
|
||||
#[default]
|
||||
Anonymous,
|
||||
ApiKey {
|
||||
api_key: String,
|
||||
},
|
||||
Token {
|
||||
access_token: String,
|
||||
refresh_token: Option<String>,
|
||||
expires_in: Option<u64>,
|
||||
},
|
||||
}
|
||||
|
||||
/// **Tribufu API**
|
||||
///
|
||||
/// Use this class to interact with the Tribufu API.
|
||||
///
|
||||
/// *There are three ways to use the Tribufu API:*
|
||||
/// - A api key give you public read only access to the Tribufu API.
|
||||
/// - A bot give you read and write access to the Tribufu API as a bot account.
|
||||
/// - A client give you read and write access to the Tribufu API as a client application.
|
||||
pub struct TribufuApi {
|
||||
pub(crate) http: HttpClient,
|
||||
pub(crate) options: TribufuApiOptions,
|
||||
}
|
||||
|
||||
impl Default for TribufuApi {
|
||||
fn default() -> Self {
|
||||
Self::new(TribufuApiOptions::Anonymous)
|
||||
}
|
||||
}
|
||||
|
||||
impl TribufuApi {
|
||||
pub fn new(options: TribufuApiOptions) -> Self {
|
||||
let http = HttpClient::builder()
|
||||
.default_headers(Self::default_headers())
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
TribufuApi { http, options }
|
||||
}
|
||||
|
||||
pub fn with_api_key(api_key: String) -> Self {
|
||||
Self::new(TribufuApiOptions::ApiKey { api_key })
|
||||
}
|
||||
|
||||
pub fn from_env(prefix: Option<&str>) -> Option<Self> {
|
||||
let prefix = if let Some(prefix) = prefix {
|
||||
format!("{}_", prefix)
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
|
||||
if let Ok(api_key) = env::var(format!("{prefix}API_KEY")) {
|
||||
Some(Self::with_api_key(api_key))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_env_or_default(prefix: Option<&str>) -> Self {
|
||||
Self::from_env(prefix).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn debug_enabled() -> bool {
|
||||
return cfg!(debug_assertions);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn get_base_url() -> String {
|
||||
if Self::debug_enabled() {
|
||||
return env::var("TRIBUFU_API_URL").unwrap_or(TRIBUFU_API_URL.to_string());
|
||||
}
|
||||
|
||||
TRIBUFU_API_URL.to_string()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn default_headers() -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("X-Tribufu-Language", "rust".parse().unwrap());
|
||||
headers.insert("X-Tribufu-Version", TRIBUFU_VERSION.parse().unwrap());
|
||||
headers
|
||||
}
|
||||
|
||||
pub(crate) fn headers(&self) -> HeaderMap {
|
||||
let mut headers = TribufuApi::default_headers();
|
||||
|
||||
match &self.options {
|
||||
TribufuApiOptions::ApiKey { api_key } => {
|
||||
headers.insert(
|
||||
"Authorization",
|
||||
HeaderValue::from_str(&format!("ApiKey {}", api_key)).unwrap(),
|
||||
);
|
||||
}
|
||||
TribufuApiOptions::Token { access_token, .. } => {
|
||||
headers.insert(
|
||||
"Authorization",
|
||||
HeaderValue::from_str(&format!("Bearer {}", access_token)).unwrap(),
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
headers
|
||||
}
|
||||
}
|
||||
386
src/api2.rs
Normal file
386
src/api2.rs
Normal file
@@ -0,0 +1,386 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
use alnilam_consts::TARGET_TRIPLE;
|
||||
use mintaka_error::{Error, Result};
|
||||
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
|
||||
use reqwest::Client;
|
||||
use std::env;
|
||||
use tribufu_constants::TRIBUFU_VERSION;
|
||||
use tribufu_types::games::Game;
|
||||
use tribufu_types::oauth2::{OAuth2GrantType, OAuth2TokenRequest, OAuth2TokenResponse};
|
||||
use tribufu_types::users::*;
|
||||
|
||||
pub enum Credentials {
|
||||
Anonymous,
|
||||
ApiKey {
|
||||
api_key: String,
|
||||
},
|
||||
Client {
|
||||
client_id: u64,
|
||||
client_secret: String,
|
||||
},
|
||||
}
|
||||
|
||||
pub enum Token {
|
||||
ApiKey {
|
||||
api_key: String,
|
||||
},
|
||||
Basic {
|
||||
basic_token: String,
|
||||
},
|
||||
Bearer {
|
||||
access_token: String,
|
||||
refresh_token: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct TribufuApi {
|
||||
|
||||
}
|
||||
|
||||
impl TribufuApi {
|
||||
const TRIBUFU_API_URL: &'static str = "https://api.tribufu.com";
|
||||
|
||||
pub fn new(credentials: Credentials) -> Self {
|
||||
let http = Client::builder()
|
||||
.user_agent(Self::user_agent())
|
||||
.default_headers(Self::default_headers())
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
Self {
|
||||
base_url: Self::get_base_url(),
|
||||
credentials,
|
||||
token: None,
|
||||
http,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn debug_enabled(&self) -> bool {
|
||||
return cfg!(debug_assertions);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn user_agent() -> String {
|
||||
format!(
|
||||
"Tribufu/{} (+https://api.tribufu.com; {})",
|
||||
TRIBUFU_VERSION, TARGET_TRIPLE
|
||||
)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn default_headers() -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("X-Tribufu-Language", HeaderValue::from_static("rust"));
|
||||
headers.insert(
|
||||
"X-Tribufu-Version",
|
||||
HeaderValue::from_static(TRIBUFU_VERSION),
|
||||
);
|
||||
headers
|
||||
}
|
||||
|
||||
fn get_base_url() -> String {
|
||||
if cfg!(debug_assertions) {
|
||||
return env::var("TRIBUFU_API_URL")
|
||||
.unwrap_or_else(|_| Self::TRIBUFU_API_URL.to_string());
|
||||
}
|
||||
|
||||
Self::TRIBUFU_API_URL.to_string()
|
||||
}
|
||||
|
||||
pub fn with_api_key(api_key: String) -> Self {
|
||||
Self::new(Credentials::ApiKey { api_key })
|
||||
}
|
||||
|
||||
pub fn with_client(client_id: u64, client_secret: String) -> Self {
|
||||
Self::new(Credentials::Client {
|
||||
client_id,
|
||||
client_secret,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn with_api_key_from_env() -> Option<Self> {
|
||||
if let Ok(api_key) = env::var("TRIBUFU_API_KEY") {
|
||||
Some(Self::with_api_key(api_key))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_client_from_env() -> Option<Self> {
|
||||
let client_id = env::var("TRIBUFU_CLIENT_ID");
|
||||
let client_secret = env::var("TRIBUFU_CLIENT_SECRET");
|
||||
|
||||
if let (Ok(client_id), Ok(client_secret)) = (client_id, client_secret) {
|
||||
Some(Self::with_client(client_id.parse().unwrap(), client_secret))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_anonymous(&mut self) {
|
||||
self.credentials = Credentials::Anonymous;
|
||||
}
|
||||
|
||||
pub fn set_api_key(&mut self, api_key: String) {
|
||||
self.credentials = Credentials::ApiKey { api_key };
|
||||
}
|
||||
|
||||
pub fn set_clients(&mut self, client_id: u64, client_secret: String) {
|
||||
self.credentials = Credentials::Client {
|
||||
client_id,
|
||||
client_secret,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn set_basic_token(&mut self, basic_token: String) {
|
||||
self.token = Some(Token::Basic { basic_token });
|
||||
}
|
||||
|
||||
pub fn set_bearer_token(&mut self, access_token: String, refresh_token: Option<String>) {
|
||||
self.token = Some(Token::Bearer {
|
||||
access_token,
|
||||
refresh_token,
|
||||
});
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn headers(&self) -> HeaderMap {
|
||||
let mut headers = Self::default_headers();
|
||||
|
||||
match &self.token {
|
||||
Some(token) => match token {
|
||||
Token::ApiKey { api_key } => {
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("ApiKey {}", api_key)).unwrap(),
|
||||
);
|
||||
}
|
||||
Token::Basic { basic_token } => {
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("Basic {}", basic_token)).unwrap(),
|
||||
);
|
||||
}
|
||||
Token::Bearer { access_token, .. } => {
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("Bearer {}", access_token)).unwrap(),
|
||||
);
|
||||
}
|
||||
},
|
||||
None => {}
|
||||
}
|
||||
|
||||
headers
|
||||
}
|
||||
|
||||
pub async fn get_token_with_code(
|
||||
&mut self,
|
||||
code: String,
|
||||
client_id: u64,
|
||||
client_secret: String,
|
||||
) -> Result<OAuth2TokenResponse> {
|
||||
self.get_oauth_token(
|
||||
OAuth2GrantType::AuthorizationCode,
|
||||
Some(code),
|
||||
client_id,
|
||||
client_secret,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_token_from_password(
|
||||
&mut self,
|
||||
username: String,
|
||||
password: String,
|
||||
client_id: u64,
|
||||
client_secret: String,
|
||||
) -> Result<OAuth2TokenResponse> {
|
||||
self.get_oauth_token(
|
||||
OAuth2GrantType::Password,
|
||||
Some(password),
|
||||
client_id,
|
||||
client_secret,
|
||||
None,
|
||||
Some(username),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_token_from_passkey(
|
||||
&mut self,
|
||||
username: String,
|
||||
passkey: String,
|
||||
client_id: u64,
|
||||
client_secret: String,
|
||||
) -> Result<OAuth2TokenResponse> {
|
||||
self.get_oauth_token(
|
||||
OAuth2GrantType::Passkey,
|
||||
Some(passkey),
|
||||
client_id,
|
||||
client_secret,
|
||||
None,
|
||||
Some(username),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn refresh_token(
|
||||
&mut self,
|
||||
refresh_token: String,
|
||||
client_id: u64,
|
||||
client_secret: String,
|
||||
) -> Result<OAuth2TokenResponse> {
|
||||
self.get_oauth_token(
|
||||
OAuth2GrantType::RefreshToken,
|
||||
Some(refresh_token),
|
||||
client_id,
|
||||
client_secret,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_client_token(
|
||||
&mut self,
|
||||
client_id: u64,
|
||||
client_secret: String,
|
||||
) -> Result<OAuth2TokenResponse> {
|
||||
self.get_oauth_token(
|
||||
OAuth2GrantType::ClientCredentials,
|
||||
None,
|
||||
client_id,
|
||||
client_secret,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_server_token(
|
||||
&mut self,
|
||||
server_id: u64,
|
||||
client_id: u64,
|
||||
client_secret: String,
|
||||
) -> Result<OAuth2TokenResponse> {
|
||||
self.get_oauth_token(
|
||||
OAuth2GrantType::ClientCredentials,
|
||||
None,
|
||||
client_id,
|
||||
client_secret,
|
||||
Some("server_id".to_string()),
|
||||
Some(server_id.to_string()),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn get_oauth_token(
|
||||
&self,
|
||||
grant_type: OAuth2GrantType,
|
||||
grant_value: Option<String>,
|
||||
client_id: u64,
|
||||
client_secret: String,
|
||||
subject_key: Option<String>,
|
||||
subject_value: Option<String>,
|
||||
) -> Result<OAuth2TokenResponse> {
|
||||
let code = if grant_type == OAuth2GrantType::AuthorizationCode {
|
||||
grant_value.clone()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let refresh_token = if grant_type == OAuth2GrantType::RefreshToken {
|
||||
grant_value.clone()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let mut require_username = false;
|
||||
|
||||
let password = if grant_type == OAuth2GrantType::Password {
|
||||
require_username = true;
|
||||
grant_value.clone()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let passkey = if grant_type == OAuth2GrantType::Passkey {
|
||||
require_username = true;
|
||||
grant_value.clone()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let username = if require_username && subject_value.is_some() {
|
||||
subject_value.clone()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let request_body = OAuth2TokenRequest {
|
||||
grant_type,
|
||||
code,
|
||||
refresh_token,
|
||||
username,
|
||||
password,
|
||||
passkey,
|
||||
client_id: Some(client_id.to_string()),
|
||||
client_secret: Some(client_secret.clone()),
|
||||
redirect_uri: None,
|
||||
};
|
||||
|
||||
let params = if subject_key.is_some() && subject_value.is_some() {
|
||||
format!("?{}={}", subject_key.unwrap(), subject_value.unwrap())
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
|
||||
let url = format!("{}/v1/oauth2/token{}", self.base_url, params);
|
||||
let headers = self.headers();
|
||||
let response = self
|
||||
.http
|
||||
.post(url)
|
||||
.headers(headers)
|
||||
.form(&request_body)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
if response.status() != 200 {
|
||||
return Err(Error::msg(format!(
|
||||
"Failed to get token: {}",
|
||||
response.status()
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(response.json().await?)
|
||||
}
|
||||
|
||||
pub async fn get_user_info(&self) -> Result<Profile> {
|
||||
let url = format!("{}/v1/oauth2/userinfo", self.base_url);
|
||||
let headers = self.headers();
|
||||
let response = self.http.get(url).headers(headers).send().await?;
|
||||
|
||||
Ok(response.json().await?)
|
||||
}
|
||||
|
||||
pub async fn get_games(&self, page: Option<u32>) -> Result<Vec<Game>> {
|
||||
let page = page.unwrap_or(1);
|
||||
let url = format!("{}/v1/packages?page={}", self.base_url, page);
|
||||
let headers = self.headers();
|
||||
let response = self.http.get(url).headers(headers).send().await?;
|
||||
|
||||
Ok(response.json().await?)
|
||||
}
|
||||
|
||||
pub async fn get_game(&self, id: u64) -> Result<Game> {
|
||||
let url = format!("{}/v1/packages/{}", self.base_url, id);
|
||||
let headers = self.headers();
|
||||
let response = self.http.get(url).headers(headers).send().await?;
|
||||
|
||||
Ok(response.json().await?)
|
||||
}
|
||||
}
|
||||
1
src/bot.rs
Normal file
1
src/bot.rs
Normal file
@@ -0,0 +1 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
206
src/client.rs
206
src/client.rs
@@ -1,171 +1,83 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
use crate::games::Game;
|
||||
use crate::oauth2::*;
|
||||
use crate::VERSION;
|
||||
use alnilam_consts::TARGET_TRIPLE;
|
||||
use anyhow::{Error, Result};
|
||||
use reqwest::header;
|
||||
use reqwest::header::{HeaderMap, HeaderValue};
|
||||
use reqwest::Client;
|
||||
use std::env;
|
||||
|
||||
use reqwest::header::{HeaderMap, HeaderValue};
|
||||
|
||||
use crate::{TribufuApi, TribufuApiOptions};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TribufuClient {
|
||||
client_id: u64,
|
||||
client_secret: String,
|
||||
token: Option<OAuth2TokenResponse>,
|
||||
api: TribufuApi,
|
||||
}
|
||||
|
||||
impl TribufuClient {
|
||||
//const BASE_URL: &'static str = "https://api.tribufu.com";
|
||||
const BASE_URL: &'static str = "http://localhost:5000";
|
||||
pub fn new(client_id: u64, client_secret: impl Into<String>) -> Self {
|
||||
Self {
|
||||
client_id,
|
||||
client_secret: client_secret.into(),
|
||||
api: TribufuApi::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new(id: u64, secret: impl Into<String>) -> Result<TribufuClient> {
|
||||
Ok(TribufuClient {
|
||||
client_id: id,
|
||||
client_secret: secret.into(),
|
||||
token: None,
|
||||
})
|
||||
pub fn from_env(prefix: Option<&str>) -> Option<Self> {
|
||||
let prefix = if let Some(prefix) = prefix {
|
||||
format!("{}_", prefix)
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
|
||||
let client_id = env::var(format!("{prefix}CLIENT_ID"));
|
||||
let client_secret = env::var(format!("{prefix}CLIENT_SECRET"));
|
||||
|
||||
if let (Ok(client_id), Ok(client_secret)) = (client_id, client_secret) {
|
||||
Some(Self::new(client_id.parse().unwrap(), client_secret))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_tokens(
|
||||
&mut self,
|
||||
access_token: String,
|
||||
refresh_token: Option<String>,
|
||||
expires_in: Option<u64>,
|
||||
) {
|
||||
self.api.options = TribufuApiOptions::Token {
|
||||
access_token,
|
||||
refresh_token,
|
||||
expires_in,
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn clear_tokens(&mut self) {
|
||||
self.api.options = TribufuApiOptions::Anonymous;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn id(&self) -> u64 {
|
||||
self.client_id
|
||||
}
|
||||
fn oauth_headers(&self) -> HeaderMap {
|
||||
let mut headers = self.api.headers();
|
||||
|
||||
#[inline]
|
||||
pub fn user_agent() -> String {
|
||||
format!(
|
||||
"Tribufu/{} (+https://api.tribufu.com; {})",
|
||||
VERSION, TARGET_TRIPLE
|
||||
)
|
||||
}
|
||||
headers.insert("Authorization", HeaderValue::from_str("Basic").unwrap());
|
||||
|
||||
headers.insert(
|
||||
"Content-Type",
|
||||
HeaderValue::from_str("application/x-www-form-urlencoded").unwrap(),
|
||||
);
|
||||
|
||||
#[inline]
|
||||
fn default_headers() -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("X-Tribufu-Language", HeaderValue::from_static("rust"));
|
||||
headers.insert("X-Tribufu-Version", HeaderValue::from_static(VERSION));
|
||||
headers
|
||||
}
|
||||
|
||||
fn http_client(&self) -> Result<Client> {
|
||||
let user_agent = Self::user_agent();
|
||||
let mut headers = Self::default_headers();
|
||||
|
||||
if let Some(token) = &self.token {
|
||||
headers.insert(
|
||||
header::AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("Bearer {}", token.access_token))?,
|
||||
);
|
||||
pub fn api(&self) -> &TribufuApi {
|
||||
&self.api
|
||||
}
|
||||
|
||||
let http = Client::builder()
|
||||
.user_agent(user_agent)
|
||||
.default_headers(headers)
|
||||
.build()?;
|
||||
|
||||
Ok(http)
|
||||
pub fn api_mut(&mut self) -> &mut TribufuApi {
|
||||
&mut self.api
|
||||
}
|
||||
|
||||
pub async fn get_token(&mut self, server_id: Option<u64>) -> Result<()> {
|
||||
let server_id = if let Some(server_id) = server_id {
|
||||
Some(server_id.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let body = OAuth2TokenRequest {
|
||||
grant_type: OAuth2GrantType::ClientCredentials,
|
||||
code: None,
|
||||
refresh_token: None,
|
||||
username: None,
|
||||
password: None,
|
||||
client_id: Some(self.client_id.to_string()),
|
||||
client_secret: Some(self.client_secret.clone()),
|
||||
redirect_uri: None,
|
||||
server_id,
|
||||
};
|
||||
|
||||
let url = format!("{}/v1/oauth2/token", Self::BASE_URL);
|
||||
let response = self.http_client()?.post(url).form(&body).send().await?;
|
||||
|
||||
if response.status() != 200 {
|
||||
return Err(Error::msg(format!(
|
||||
"Failed to get token: {}",
|
||||
response.status()
|
||||
)));
|
||||
}
|
||||
|
||||
self.token = Some(response.json().await?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn refresh_token_token(&mut self) -> Result<()> {
|
||||
let token = if let Some(token) = &self.token {
|
||||
token
|
||||
} else {
|
||||
return Err(Error::msg(
|
||||
format!("Failed to refresh: self.token == None",),
|
||||
));
|
||||
};
|
||||
|
||||
if token.refresh_token.is_none() {
|
||||
return Err(Error::msg(format!(
|
||||
"Failed to refresh: self.token.refresh_token == None",
|
||||
)));
|
||||
}
|
||||
|
||||
let body = OAuth2TokenRequest {
|
||||
grant_type: OAuth2GrantType::RefreshToken,
|
||||
code: None,
|
||||
refresh_token: token.refresh_token.clone(),
|
||||
username: None,
|
||||
password: None,
|
||||
client_id: Some(self.client_id.to_string()),
|
||||
client_secret: Some(self.client_secret.clone()),
|
||||
redirect_uri: None,
|
||||
server_id: None,
|
||||
};
|
||||
|
||||
let url = format!("{}/v1/oauth2/token", Self::BASE_URL);
|
||||
let response = self.http_client()?.post(url).form(&body).send().await?;
|
||||
|
||||
if response.status() != 200 {
|
||||
return Err(Error::msg(format!(
|
||||
"Failed to get token: {}",
|
||||
response.status()
|
||||
)));
|
||||
}
|
||||
|
||||
self.token = Some(response.json().await?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_games(&self) -> Result<Vec<Game>> {
|
||||
let url = format!("{}/v1/packages", Self::BASE_URL);
|
||||
let response = self.http_client()?.get(url).send().await?;
|
||||
|
||||
Ok(response.json().await?)
|
||||
}
|
||||
|
||||
pub async fn get_game(&self, id: u64) -> Result<Game> {
|
||||
let url = format!("{}/v1/packages/{}", Self::BASE_URL, id);
|
||||
let response = self.http_client()?.get(url).send().await?;
|
||||
|
||||
Ok(response.json().await?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_client() {
|
||||
let client = TribufuClient::new(0, "client_secret").unwrap();
|
||||
assert_eq!(client.id(), 0);
|
||||
pub fn client_id(&self) -> u64 {
|
||||
self.client_id
|
||||
}
|
||||
}
|
||||
|
||||
16
src/constants/Cargo.toml
Normal file
16
src/constants/Cargo.toml
Normal file
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "tribufu-constants"
|
||||
version = "0.1.0"
|
||||
description = "Tribufu Constants"
|
||||
repository = "https://github.com/Tribufu/TribufuRust"
|
||||
authors = ["Tribufu <contact@tribufu.com>"]
|
||||
license = "MIT"
|
||||
edition = "2021"
|
||||
publish = true
|
||||
|
||||
[lib]
|
||||
name = "tribufu_constants"
|
||||
crate-type = ["rlib"]
|
||||
path = "lib.rs"
|
||||
|
||||
[dependencies]
|
||||
13
src/constants/lib.rs
Normal file
13
src/constants/lib.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
/// The version of the Tribufu SDK.
|
||||
pub const TRIBUFU_VERSION: &'static str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// The default Tribufu API URL.
|
||||
pub const TRIBUFU_API_URL: &'static str = "https://api.tribufu.com";
|
||||
|
||||
/// The default Tribufu WEB URL.
|
||||
pub const TRIBUFU_WEB_URL: &'static str = "https://www.tribufu.com";
|
||||
|
||||
/// The default Tribufu CDN URL.
|
||||
pub const TRIBUFU_CDN_URL: &'static str = "https://cdn.tribufu.com";
|
||||
15
src/lib.rs
15
src/lib.rs
@@ -1,12 +1,17 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
#![allow(dead_code)]
|
||||
#![allow(unused_imports)]
|
||||
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
pub use tribufu_constants::TRIBUFU_VERSION;
|
||||
pub use tribufu_types as types;
|
||||
|
||||
pub mod client;
|
||||
pub mod games;
|
||||
pub mod oauth2;
|
||||
pub mod token;
|
||||
mod api;
|
||||
mod bot;
|
||||
mod client;
|
||||
mod server;
|
||||
|
||||
pub use api::*;
|
||||
pub use bot::*;
|
||||
pub use client::*;
|
||||
pub use server::*;
|
||||
|
||||
37
src/server.rs
Normal file
37
src/server.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
use crate::{TribufuApi, TribufuClient};
|
||||
|
||||
pub struct TribufuServer {
|
||||
server_id: u64,
|
||||
client: TribufuClient,
|
||||
}
|
||||
|
||||
impl TribufuServer {
|
||||
pub fn new(server_id: u64, client_id: u64, client_secret: impl Into<String>) -> Self {
|
||||
Self {
|
||||
server_id,
|
||||
client: TribufuClient::new(client_id, client_secret),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn api(&self) -> &TribufuApi {
|
||||
self.client.api()
|
||||
}
|
||||
|
||||
pub fn api_mut(&mut self) -> &mut TribufuApi {
|
||||
self.client.api_mut()
|
||||
}
|
||||
|
||||
pub fn client(&self) -> &TribufuClient {
|
||||
&self.client
|
||||
}
|
||||
|
||||
pub fn client_mut(&mut self) -> &mut TribufuClient {
|
||||
&mut self.client
|
||||
}
|
||||
|
||||
pub fn server_id(&self) -> u64 {
|
||||
self.server_id
|
||||
}
|
||||
}
|
||||
11
src/token.rs
11
src/token.rs
@@ -1,11 +0,0 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
use crate::oauth2::OAuth2TokenResponse;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Credentials {
|
||||
ApiKey(String),
|
||||
Token(OAuth2TokenResponse),
|
||||
}
|
||||
22
src/types/Cargo.toml
Normal file
22
src/types/Cargo.toml
Normal file
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "tribufu-types"
|
||||
version = "0.1.0"
|
||||
description = "Tribufu Types"
|
||||
repository = "https://github.com/Tribufu/TribufuRust"
|
||||
authors = ["Tribufu <contact@tribufu.com>"]
|
||||
license = "MIT"
|
||||
edition = "2021"
|
||||
publish = true
|
||||
|
||||
[lib]
|
||||
name = "tribufu_types"
|
||||
crate-type = ["rlib"]
|
||||
path = "lib.rs"
|
||||
|
||||
[dependencies]
|
||||
chrono = { version = "0.4.22", features = ["serde", "rustc-serialize"] }
|
||||
derive_more = "0.99.17"
|
||||
mintaka-error = { version = "0.0.1" }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = { version = "1.0", features = ["raw_value"] }
|
||||
serde_with = "3.4.0"
|
||||
6
src/types/lib.rs
Normal file
6
src/types/lib.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
pub mod games;
|
||||
pub mod oauth2;
|
||||
pub mod servers;
|
||||
pub mod users;
|
||||
@@ -2,38 +2,39 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OAuth2ResponseType {
|
||||
Code,
|
||||
Token,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OAuth2ClientType {
|
||||
Confidential,
|
||||
Public,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OAuth2TokenHintType {
|
||||
AccessToken,
|
||||
RefreshToken,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OAuth2GrantType {
|
||||
AuthorizationCode,
|
||||
ClientCredentials,
|
||||
DeviceCode,
|
||||
Passkey,
|
||||
Password,
|
||||
RefreshToken,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OAuth2AuthorizeError {
|
||||
AccessDenied,
|
||||
@@ -45,7 +46,7 @@ pub enum OAuth2AuthorizeError {
|
||||
UnsupportedResponseType,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OAuth2TokenType {
|
||||
Bearer,
|
||||
@@ -86,34 +87,47 @@ pub struct OAuth2ErrorResponse {
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct OAuth2TokenRequest {
|
||||
pub grant_type: OAuth2GrantType,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub code: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub refresh_token: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub username: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub password: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub passkey: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub client_id: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub client_secret: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub redirect_uri: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub server_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct OAuth2TokenResponse {
|
||||
pub token_type: OAuth2TokenType,
|
||||
|
||||
pub access_token: String,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub refresh_token: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub scope: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub state: Option<String>,
|
||||
|
||||
pub expires_in: u64,
|
||||
}
|
||||
|
||||
@@ -141,7 +155,7 @@ pub struct OAuth2IntrospectionResponse {
|
||||
}
|
||||
|
||||
impl OAuth2IntrospectionResponse {
|
||||
fn inative() -> Self {
|
||||
pub fn inative() -> Self {
|
||||
Self {
|
||||
active: false,
|
||||
client_id: None,
|
||||
82
src/types/servers.rs
Normal file
82
src/types/servers.rs
Normal file
@@ -0,0 +1,82 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
use crate::users::MiniProfile;
|
||||
use chrono::NaiveDateTime;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use serde_with::{serde_as, DisplayFromStr};
|
||||
|
||||
#[serde_as]
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Server {
|
||||
#[serde_as(as = "DisplayFromStr")]
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub address: String,
|
||||
pub game_port: Option<u16>,
|
||||
pub query_port: u16,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub rcon_port: Option<u16>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub rcon_password: Option<String>,
|
||||
#[serde_as(as = "DisplayFromStr")]
|
||||
pub package_id: u64,
|
||||
pub package_icon_url: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub package: Option<ServerPackage>,
|
||||
pub version: Option<String>,
|
||||
pub cluster_id: Option<u32>,
|
||||
pub website_url: Option<String>,
|
||||
pub banner_url: Option<String>,
|
||||
pub owner_id: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub owner: Option<MiniProfile>,
|
||||
#[serde(skip)]
|
||||
pub uptime: f64,
|
||||
pub last_online: Option<NaiveDateTime>,
|
||||
#[serde(flatten)]
|
||||
pub stats: ServerStats,
|
||||
pub country: Option<String>,
|
||||
pub steam: bool,
|
||||
pub discord_server_id: Option<String>,
|
||||
pub youtube_video_url: Option<String>,
|
||||
pub tags: Option<Value>,
|
||||
pub comment_count: u32,
|
||||
#[serde(skip)]
|
||||
pub secret: Option<String>,
|
||||
pub created: NaiveDateTime,
|
||||
pub updated: Option<NaiveDateTime>,
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ServerStatus {
|
||||
Unknown,
|
||||
Offline,
|
||||
Online,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ServerStats {
|
||||
pub status: ServerStatus,
|
||||
pub ping: Option<u32>,
|
||||
pub map: Option<String>,
|
||||
pub used_slots: Option<i32>,
|
||||
pub max_slots: Option<i32>,
|
||||
pub motd: Option<String>,
|
||||
pub players: Option<Value>,
|
||||
}
|
||||
|
||||
#[serde_as]
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ServerPackage {
|
||||
#[serde_as(as = "DisplayFromStr")]
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub slug: Option<String>,
|
||||
pub rust_gamedig_id: Option<String>,
|
||||
pub node_gamedig_id: Option<String>,
|
||||
pub server_connect_url: Option<String>,
|
||||
}
|
||||
55
src/types/users.rs
Normal file
55
src/types/users.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
use chrono::{NaiveDate, NaiveDateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_with::{serde_as, DisplayFromStr};
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum UserType {
|
||||
User = 0,
|
||||
Bot = 1,
|
||||
Org = 2,
|
||||
}
|
||||
|
||||
#[serde_as]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Profile {
|
||||
#[serde_as(as = "DisplayFromStr")]
|
||||
pub id: u64,
|
||||
pub uuid: String,
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(rename = "type")]
|
||||
pub kind: UserType,
|
||||
pub public_flags: u64,
|
||||
pub verified: bool,
|
||||
pub level: u32,
|
||||
pub experience: f64,
|
||||
pub public_birthday: bool,
|
||||
pub birthday: Option<NaiveDate>,
|
||||
pub points: f64,
|
||||
pub location: Option<String>,
|
||||
pub photo_url: Option<String>,
|
||||
pub banner_url: Option<String>,
|
||||
pub last_online: Option<NaiveDateTime>,
|
||||
pub biography: Option<String>,
|
||||
pub view_count: u32,
|
||||
pub created: NaiveDateTime,
|
||||
pub updated: Option<NaiveDateTime>,
|
||||
}
|
||||
|
||||
#[serde_as]
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct MiniProfile {
|
||||
#[serde_as(as = "DisplayFromStr")]
|
||||
pub id: u64,
|
||||
pub uuid: String,
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(rename = "type")]
|
||||
pub kind: UserType,
|
||||
pub verified: bool,
|
||||
pub photo_url: String,
|
||||
}
|
||||
Reference in New Issue
Block a user