mirror of
https://github.com/tribufu/sdk-rust
synced 2025-06-15 10:44:18 +00:00
Prototype API (#1)
* Add oauth2 client * Update LICENSE.txt * Create .env.example * Add dotenv to example * Add oauth2 types * Update lib.rs * Update Cargo.toml * Update lib.rs * Add games routes
This commit is contained in:
@ -1,2 +0,0 @@
|
||||
[build]
|
||||
target-dir = "Intermediate/Target"
|
@ -10,3 +10,6 @@ insert_final_newline = true
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.env*]
|
||||
insert_final_newline = false
|
||||
|
3
.env.example
Normal file
3
.env.example
Normal file
@ -0,0 +1,3 @@
|
||||
CLIENT_ID=
|
||||
CLIENT_SECRET=
|
||||
TRIBUFU_API_URL=https://api.tribufu.com
|
38
.gitignore
vendored
38
.gitignore
vendored
@ -1,6 +1,40 @@
|
||||
[Bb]inaries/
|
||||
[Ii]ntermediate/
|
||||
__pycache__/
|
||||
.gradle/
|
||||
.idea/
|
||||
.metals/
|
||||
.next/
|
||||
.parcel-cache/
|
||||
.vs/
|
||||
.vscode/
|
||||
bin/
|
||||
binaries/
|
||||
build/
|
||||
node_modules/
|
||||
obj/
|
||||
saved/
|
||||
target/
|
||||
|
||||
.DS_Store
|
||||
.env
|
||||
*.crt
|
||||
*.csproj
|
||||
*.filters
|
||||
*.fsproj
|
||||
*.key
|
||||
*.log
|
||||
*.make
|
||||
*.mwb.bak
|
||||
*.pem
|
||||
*.sln
|
||||
*.user
|
||||
*.vcxproj
|
||||
*.vpp.*
|
||||
*.wasm
|
||||
*.xcodeproj
|
||||
*.xcworkspace
|
||||
Cargo.lock
|
||||
desktop.ini
|
||||
keystore.jks
|
||||
local.properties
|
||||
Makefile
|
||||
next-env.d.ts
|
||||
|
31
Cargo.toml
31
Cargo.toml
@ -1,24 +1,31 @@
|
||||
[package]
|
||||
name = "tribufu"
|
||||
version = "0.0.3"
|
||||
description = "TribuFu SDK"
|
||||
repository = "https://github.com/TribuFu/SDK-RS"
|
||||
authors = ["TribuFu <contact@tribufu.com>"]
|
||||
version = "0.0.4"
|
||||
description = "Tribufu SDK"
|
||||
repository = "https://github.com/Tribufu/SDK-Rust"
|
||||
authors = ["Tribufu <contact@tribufu.com>"]
|
||||
license = "Apache-2.0"
|
||||
readme = "README.md"
|
||||
edition = "2021"
|
||||
publish = true
|
||||
|
||||
exclude = [
|
||||
".github/",
|
||||
".vscode/",
|
||||
".editorconfig",
|
||||
".gitattributes",
|
||||
]
|
||||
exclude = [".github/", ".vscode/", ".editorconfig", ".gitattributes"]
|
||||
|
||||
[lib]
|
||||
name = "TribuFu"
|
||||
name = "tribufu"
|
||||
crate-type = ["rlib"]
|
||||
path = "Source/lib.rs"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
alnilam-consts = { version = "0.0.4" }
|
||||
anyhow = "1.0.75"
|
||||
chrono = { version = "0.4.22", features = ["serde", "rustc-serialize"] }
|
||||
derive_more = "0.99.17"
|
||||
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"
|
||||
|
||||
[dev-dependencies]
|
||||
dotenv = "0.15.0"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
|
@ -186,7 +186,7 @@
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright (c) TribuFu. All Rights Reserved
|
||||
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.
|
||||
|
@ -1,5 +0,0 @@
|
||||
// Copyright (c) TribuFu. All Rights Reserved
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
11
examples/client.rs
Normal file
11
examples/client.rs
Normal file
@ -0,0 +1,11 @@
|
||||
// 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),
|
||||
}
|
||||
}
|
23
examples/token.rs
Normal file
23
examples/token.rs
Normal file
@ -0,0 +1,23 @@
|
||||
// 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);
|
||||
});
|
||||
}
|
171
src/client.rs
Normal file
171
src/client.rs
Normal file
@ -0,0 +1,171 @@
|
||||
// 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;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TribufuClient {
|
||||
client_id: u64,
|
||||
client_secret: String,
|
||||
token: Option<OAuth2TokenResponse>,
|
||||
}
|
||||
|
||||
impl TribufuClient {
|
||||
//const BASE_URL: &'static str = "https://api.tribufu.com";
|
||||
const BASE_URL: &'static str = "http://localhost:5000";
|
||||
|
||||
pub fn new(id: u64, secret: impl Into<String>) -> Result<TribufuClient> {
|
||||
Ok(TribufuClient {
|
||||
client_id: id,
|
||||
client_secret: secret.into(),
|
||||
token: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn id(&self) -> u64 {
|
||||
self.client_id
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn user_agent() -> String {
|
||||
format!(
|
||||
"Tribufu/{} (+https://api.tribufu.com; {})",
|
||||
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(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))?,
|
||||
);
|
||||
}
|
||||
|
||||
let http = Client::builder()
|
||||
.user_agent(user_agent)
|
||||
.default_headers(headers)
|
||||
.build()?;
|
||||
|
||||
Ok(http)
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
29
src/games.rs
Normal file
29
src/games.rs
Normal file
@ -0,0 +1,29 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
use chrono::NaiveDateTime;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_with::{serde_as, DisplayFromStr};
|
||||
|
||||
#[serde_as]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Game {
|
||||
#[serde_as(as = "DisplayFromStr")]
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub icon_url: Option<String>,
|
||||
pub banner_url: Option<String>,
|
||||
pub capsule_image_url: Option<String>,
|
||||
pub library_image_url: Option<String>,
|
||||
pub slug: Option<String>,
|
||||
pub game_port: Option<u16>,
|
||||
pub query_port: Option<u16>,
|
||||
pub rcon_port: Option<u16>,
|
||||
pub steam_app_id: Option<u32>,
|
||||
pub steam_server_app_id: Option<u32>,
|
||||
pub rust_gamedig_id: Option<String>,
|
||||
pub node_gamedig_id: Option<String>,
|
||||
pub server_connect_url: Option<String>,
|
||||
pub created: NaiveDateTime,
|
||||
pub updated: Option<NaiveDateTime>,
|
||||
}
|
12
src/lib.rs
Normal file
12
src/lib.rs
Normal file
@ -0,0 +1,12 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
#![allow(dead_code)]
|
||||
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
pub mod client;
|
||||
pub mod games;
|
||||
pub mod oauth2;
|
||||
pub mod token;
|
||||
|
||||
pub use client::*;
|
153
src/oauth2.rs
Normal file
153
src/oauth2.rs
Normal file
@ -0,0 +1,153 @@
|
||||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OAuth2ResponseType {
|
||||
Code,
|
||||
Token,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OAuth2ClientType {
|
||||
Confidential,
|
||||
Public,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OAuth2TokenHintType {
|
||||
AccessToken,
|
||||
RefreshToken,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OAuth2GrantType {
|
||||
AuthorizationCode,
|
||||
ClientCredentials,
|
||||
DeviceCode,
|
||||
Password,
|
||||
RefreshToken,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OAuth2AuthorizeError {
|
||||
AccessDenied,
|
||||
InvalidRequest,
|
||||
InvalidScope,
|
||||
ServerError,
|
||||
TemporarilyUnavailable,
|
||||
UnauthorizedClient,
|
||||
UnsupportedResponseType,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OAuth2TokenType {
|
||||
Bearer,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct OAuth2AuthorizeRequest {
|
||||
pub response_type: OAuth2ResponseType,
|
||||
pub client_id: String,
|
||||
pub client_secret: Option<String>,
|
||||
pub redirect_uri: String,
|
||||
pub scope: Option<String>,
|
||||
pub state: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct OAuth2CodeResponse {
|
||||
pub code: String,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub state: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct OAuth2ErrorResponse {
|
||||
pub error: OAuth2AuthorizeError,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error_description: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error_uri: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub state: Option<String>,
|
||||
}
|
||||
|
||||
#[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 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,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct OAuth2RevokeRequest {
|
||||
pub token: String,
|
||||
pub token_type_hint: OAuth2TokenHintType,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct OAuth2IntrospectionResponse {
|
||||
pub active: bool,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub client_id: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub username: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub scope: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub exp: Option<i64>,
|
||||
}
|
||||
|
||||
impl OAuth2IntrospectionResponse {
|
||||
fn inative() -> Self {
|
||||
Self {
|
||||
active: false,
|
||||
client_id: None,
|
||||
username: None,
|
||||
scope: None,
|
||||
exp: None,
|
||||
}
|
||||
}
|
||||
}
|
11
src/token.rs
Normal file
11
src/token.rs
Normal file
@ -0,0 +1,11 @@
|
||||
// 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),
|
||||
}
|
Reference in New Issue
Block a user