repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
helsing-ai/dson | https://github.com/helsing-ai/dson/blob/eef903f2120ed8415e5f9d1792d10c72c387f533/examples/transaction_sync.rs | examples/transaction_sync.rs | use dson::{
CausalDotStore, Identifier, OrMap,
crdts::{mvreg::MvRegValue, snapshot::ToValue},
transaction::CrdtValue,
};
fn main() {
// Simulate a distributed system with 3 replicas
let mut replica_a = CausalDotStore::<OrMap<String>>::default();
let mut replica_b = CausalDotStore::<OrMap<String>>::default();
let mut replica_c = CausalDotStore::<OrMap<String>>::default();
let id_a = Identifier::new(0, 0);
let id_b = Identifier::new(1, 0);
let id_c = Identifier::new(2, 0);
println!("Three replicas start with empty state\n");
// Replica A initializes a counter
let delta_a1 = {
let mut tx = replica_a.transact(id_a);
tx.write_register("counter", MvRegValue::U64(0));
tx.commit()
};
println!("Replica A: initialized counter to 0");
// Broadcast delta_a1 to all replicas
replica_b.join_or_replace_with(delta_a1.0.store.clone(), &delta_a1.0.context);
replica_c.join_or_replace_with(delta_a1.0.store, &delta_a1.0.context);
println!("Replicas B and C: received initialization\n");
// All three replicas concurrently increment
let delta_a2 = {
let mut tx = replica_a.transact(id_a);
tx.write_register("counter", MvRegValue::U64(1));
tx.commit()
};
println!("Replica A: incremented to 1");
let delta_b1 = {
let mut tx = replica_b.transact(id_b);
tx.write_register("counter", MvRegValue::U64(1));
tx.commit()
};
println!("Replica B: incremented to 1");
let delta_c1 = {
let mut tx = replica_c.transact(id_c);
tx.write_register("counter", MvRegValue::U64(1));
tx.commit()
};
println!("Replica C: incremented to 1\n");
// Exchange deltas (full mesh)
println!("Synchronizing replicas...");
replica_a.join_or_replace_with(delta_b1.0.store.clone(), &delta_b1.0.context);
replica_a.join_or_replace_with(delta_c1.0.store.clone(), &delta_c1.0.context);
replica_b.join_or_replace_with(delta_a2.0.store.clone(), &delta_a2.0.context);
replica_b.join_or_replace_with(delta_c1.0.store.clone(), &delta_c1.0.context);
replica_c.join_or_replace_with(delta_a2.0.store, &delta_a2.0.context);
replica_c.join_or_replace_with(delta_b1.0.store, &delta_b1.0.context);
// Verify convergence
assert_eq!(replica_a, replica_b);
assert_eq!(replica_b, replica_c);
println!("All replicas converged to the same state!\n");
// Read final value
{
let tx = replica_a.transact(id_a);
if let Some(CrdtValue::Register(reg)) = tx.get(&"counter".to_string()) {
if let Ok(MvRegValue::U64(value)) = reg.value() {
println!("Final counter value: {value}");
}
}
}
println!("\nThe transaction API makes distributed systems easy!");
println!("Deltas are small, composable, and automatically managed.");
}
| rust | Apache-2.0 | eef903f2120ed8415e5f9d1792d10c72c387f533 | 2026-01-04T20:19:34.202571Z | false |
helsing-ai/dson | https://github.com/helsing-ai/dson/blob/eef903f2120ed8415e5f9d1792d10c72c387f533/examples/transaction_nested.rs | examples/transaction_nested.rs | use dson::{
CausalDotStore, Identifier, OrMap,
crdts::{mvreg::MvRegValue, snapshot::ToValue},
transaction::CrdtValue,
};
fn main() {
let mut store = CausalDotStore::<OrMap<String>>::default();
let id = Identifier::new(0, 0);
// Create nested data structure
{
let mut tx = store.transact(id);
// Write to nested map for user "alice"
tx.in_map("alice", |alice_tx| {
alice_tx.write_register("email", MvRegValue::String("alice@example.com".to_string()));
alice_tx.write_register("age", MvRegValue::U64(30));
});
// Write to nested map for user "bob"
tx.in_map("bob", |bob_tx| {
bob_tx.write_register("email", MvRegValue::String("bob@example.com".to_string()));
bob_tx.write_register("active", MvRegValue::Bool(true));
});
let _delta = tx.commit();
}
// Read nested data
{
let tx = store.transact(id);
// Read Alice's data
let alice_map = tx.get(&"alice".to_string()).expect("Alice should exist");
let CrdtValue::Map(alice_map) = alice_map else {
panic!("Alice value should be a map");
};
println!("Alice's data:");
let alice_email = alice_map
.get(&"email".to_string())
.expect("Alice email should exist");
let email = alice_email
.reg
.value()
.expect("Alice email should have a value");
println!(" Email: {email:?}");
assert_eq!(email, &MvRegValue::String("alice@example.com".to_string()));
let alice_age = alice_map
.get(&"age".to_string())
.expect("Alice age should exist");
let age = alice_age
.reg
.value()
.expect("Alice age should have a value");
println!(" Age: {age:?}");
assert_eq!(age, &MvRegValue::U64(30));
// Read Bob's data
let bob_map = tx.get(&"bob".to_string()).expect("Bob should exist");
let CrdtValue::Map(bob_map) = bob_map else {
panic!("Bob value should be a map");
};
println!("\nBob's data:");
let bob_email = bob_map
.get(&"email".to_string())
.expect("Bob email should exist");
let email = bob_email
.reg
.value()
.expect("Bob email should have a value");
println!(" Email: {email:?}");
assert_eq!(email, &MvRegValue::String("bob@example.com".to_string()));
let bob_active = bob_map
.get(&"active".to_string())
.expect("Bob active should exist");
let active = bob_active
.reg
.value()
.expect("Bob active should have a value");
println!(" Active: {active:?}");
assert_eq!(active, &MvRegValue::Bool(true));
}
// Deeply nested structure: map -> array -> map -> array
// Structure: projects -> items -> properties
{
let mut tx = store.transact(id);
tx.in_map("project", |project_tx| {
project_tx.write_register("name", MvRegValue::String("Website Redesign".to_string()));
// Array of task maps
project_tx.in_array("tasks", |tasks_tx| {
tasks_tx.insert_map(0, |task_tx| {
task_tx
.write_register("title", MvRegValue::String("Design mockups".to_string()));
task_tx.write_register("done", MvRegValue::Bool(true));
});
tasks_tx.insert_map(1, |task_tx| {
task_tx.write_register(
"title",
MvRegValue::String("Implement frontend".to_string()),
);
task_tx.write_register("done", MvRegValue::Bool(false));
});
});
});
let _delta = tx.commit();
}
// Read deeply nested data
{
let tx = store.transact(id);
println!("\nDeeply nested structure:");
let project = tx
.get(&"project".to_string())
.expect("project should exist");
let CrdtValue::Map(project_map) = project else {
panic!("project should be a map");
};
let name = project_map
.get(&"name".to_string())
.expect("name should exist");
println!(" Project: {:?}", name.reg.value().unwrap());
let tasks = project_map
.get(&"tasks".to_string())
.expect("tasks should exist");
let tasks_len = tasks.array.len();
println!(" {tasks_len} tasks");
let task0 = tasks.array.get(0).expect("task 0 should exist");
let title0 = task0
.map
.get(&"title".to_string())
.expect("title should exist");
println!(" Task 0: {:?}", title0.reg.value().unwrap());
let task1 = tasks.array.get(1).expect("task 1 should exist");
let title1 = task1
.map
.get(&"title".to_string())
.expect("title should exist");
println!(" Task 1: {:?}", title1.reg.value().unwrap());
}
println!("\nNested transactions make hierarchical data simple!");
}
| rust | Apache-2.0 | eef903f2120ed8415e5f9d1792d10c72c387f533 | 2026-01-04T20:19:34.202571Z | false |
helsing-ai/dson | https://github.com/helsing-ai/dson/blob/eef903f2120ed8415e5f9d1792d10c72c387f533/examples/transaction_basic.rs | examples/transaction_basic.rs | use dson::{
CausalDotStore, Identifier, OrMap,
crdts::{mvreg::MvRegValue, snapshot::ToValue},
transaction::CrdtValue,
};
fn main() {
// Create a DSON store
let mut store = CausalDotStore::<OrMap<String>>::default();
let id = Identifier::new(0, 0);
// Write some data using the transaction API
{
let mut tx = store.transact(id);
tx.write_register("name", MvRegValue::String("Alice".to_string()));
tx.write_register("age", MvRegValue::U64(30));
tx.write_register("active", MvRegValue::Bool(true));
let delta = tx.commit();
println!(
"Created delta with {} bytes",
serde_json::to_string(&delta.0).unwrap().len()
);
}
// Read the data back
{
let tx = store.transact(id);
match tx.get(&"name".to_string()) {
Some(CrdtValue::Register(reg)) => {
if let Ok(MvRegValue::String(name)) = reg.value() {
println!("Name: {name}");
}
}
_ => println!("Name not found or wrong type"),
}
match tx.get(&"age".to_string()) {
Some(CrdtValue::Register(reg)) => {
if let Ok(MvRegValue::U64(age)) = reg.value() {
println!("Age: {age}");
}
}
_ => println!("Age not found or wrong type"),
}
}
println!("\nTransaction API makes DSON easy to use!");
}
| rust | Apache-2.0 | eef903f2120ed8415e5f9d1792d10c72c387f533 | 2026-01-04T20:19:34.202571Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/lib.rs | src/lib.rs | //! # `rbxcloud` - CLI & SDK for Roblox Open Cloud APIs
//!
//! `rbxcloud` is both a CLI and an SDK for the Roblox
//! Open Cloud APIs. For in-depth documentation on
//! both the CLI and SDK functionality, visit the
//! [documentation](https://sleitnick.github.io/rbxcloud/)
//! website.
//!
//! ## Usage
//!
//! Add `rbxcloud` as a dependency.
//! ```sh
//! $ cargo add rbxcloud
//! ```
//!
//! Example: Publishing a message.
//! ```rust,no_run
//! use rbxcloud::rbx::{error::Error, v1::RbxCloud, types::UniverseId};
//!
//! async fn publish_message() -> Result<(), Error> {
//! let api_key = "my_api_key";
//! let universe_id = UniverseId(9876543210);
//! let topic = "MyTopic";
//! let cloud = RbxCloud::new(api_key);
//! let messaging = cloud.messaging(universe_id, topic);
//! messaging.publish("Hello world").await
//! }
//! ```
//!
//! Consuming the message from a Roblox script.
//! ```lua
//! local MessagingService = game:GetService("MessagingService")
//! MessagingService:SubscribeAsync("MyTopic"):Connect(function(payload)
//! print(payload)
//! --> {"message": "Hello world"}
//! end)
//! ```
pub mod rbx;
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/main.rs | src/main.rs | mod cli;
use clap::Parser;
use cli::Cli;
use std::process;
#[tokio::main]
async fn main() {
let cli_args = Cli::parse();
match cli_args.run().await {
Ok(str) => {
if let Some(s) = str {
println!("{s}");
}
}
Err(err) => {
eprintln!("{err:?}");
process::exit(1);
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/error.rs | src/rbx/error.rs | //! Error handling.
use crate::rbx::v1::ds_error::DataStoreErrorResponse;
/// `rbxcloud` error.
#[derive(Debug)]
pub enum Error {
/// An error occurred regarding reading a file from the file system.
FileLoadError(String),
/// Failed to infer asset type.
InferAssetTypeError(String),
/// A non-OK HTTP status was returned.
HttpStatusError { code: u16, msg: String },
/// An error within the `reqwest` module occurred.
ReqwestError(reqwest::Error),
/// An IO error occurred.
IOError(std::io::Error),
/// A JSON serialization error occurred.
SerdeJsonError(serde_json::Error),
/// A DataStore error occurred.
DataStoreError(DataStoreErrorResponse),
/// Failed to parse a float.
ParseFloatError(std::num::ParseFloatError),
/// Endpoint error.
EndpointError(String),
}
impl std::error::Error for Error {}
impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Self {
Self::ReqwestError(e)
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Self::IOError(e)
}
}
impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Self {
Self::SerdeJsonError(e)
}
}
impl From<std::num::ParseFloatError> for Error {
fn from(e: std::num::ParseFloatError) -> Self {
Self::ParseFloatError(e)
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::FileLoadError(s) => write!(f, "failed to read file: {s}"),
Self::InferAssetTypeError(s) => write!(f, "failed to infer asset type: {s}"),
Self::HttpStatusError { code, msg } => write!(f, "http {code}: {msg}"),
Self::ReqwestError(e) => write!(f, "{e:?}"),
Self::IOError(e) => write!(f, "{e:?}"),
Self::SerdeJsonError(e) => write!(f, "{e:?}"),
Self::DataStoreError(e) => write!(f, "{e:?}"),
Self::ParseFloatError(e) => write!(f, "{e:?}"),
Self::EndpointError(s) => write!(f, "endpoint error: {s}"),
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/types.rs | src/rbx/types.rs | use serde::{Deserialize, Serialize};
/// Represents the UniverseId of a Roblox experience.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct UniverseId(pub u64);
/// Represents the PlaceId of a specific place within a Roblox experience.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct PlaceId(pub u64);
// Number of items to return.
#[derive(Debug, Clone, Copy)]
pub struct ReturnLimit(pub u64);
/// Represents a Roblox user's ID.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct RobloxUserId(pub u64);
#[derive(Debug, Clone, Copy)]
pub struct PageSize(pub u64);
#[derive(Debug, Clone, Copy)]
pub struct GroupId(pub u64);
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/util.rs | src/rbx/util.rs | use base64::{engine::general_purpose::STANDARD, Engine as _};
use md5::{Digest, Md5};
pub type QueryString = Vec<(&'static str, String)>;
#[inline]
pub fn get_checksum_base64(data: &String) -> String {
let mut md5_hash = Md5::new();
md5_hash.update(data.as_bytes());
STANDARD.encode(md5_hash.finalize())
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/mod.rs | src/rbx/mod.rs | //! Access into Roblox APIs.
//!
//! Most usage should go through the `RbxCloud` struct.
pub mod error;
pub mod types;
pub(crate) mod util;
pub mod v1;
pub mod v2;
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v1/ds_error.rs | src/rbx/v1/ds_error.rs | use std::fmt;
use serde::Deserialize;
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DataStoreErrorResponse {
pub error: String,
pub message: String,
pub error_details: Vec<DataStoreErrorDetail>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DataStoreErrorDetail {
pub error_detail_type: String,
pub datastore_error_code: DataStoreErrorCode,
}
#[derive(Deserialize, Debug)]
pub enum DataStoreErrorCode {
ContentLengthRequired,
InvalidUniverseId,
InvalidCursor,
InvalidVersionId,
ExistingValueNotNumeric,
IncrementValueTooLarge,
IncrementValueTooSmall,
InvalidDataStoreScope,
InvalidEntryKey,
InvalidDataStoreName,
InvalidStartTime,
InvalidEndTime,
InvalidAttributes,
InvalidUserIds,
ExclusiveCreateAndMatchVersionCannotBeSet,
ContentTooBig,
ChecksumMismatch,
ContentNotJson,
InvalidSortOrder,
Forbidden,
InsufficientScope,
DatastoreNotFound,
EntryNotFound,
VersionNotFound,
TooManyRequests,
Unknown,
}
impl fmt::Display for DataStoreErrorResponse {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let details = self
.error_details
.iter()
.map(|item| format!("{:?}", item.datastore_error_code))
.collect::<Vec<String>>()
.join(", ");
write!(f, "[{}] - {}", details, self.message)
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v1/messaging.rs | src/rbx/v1/messaging.rs | //! Low-level Messaging API operations.
use serde_json::json;
use crate::rbx::error::Error;
use crate::rbx::v1::UniverseId;
/// Message publishing parameters.
pub struct PublishMessageParams {
pub api_key: String,
pub universe_id: UniverseId,
pub topic: String,
pub message: String,
}
/// Publish a message.
pub async fn publish_message(params: &PublishMessageParams) -> Result<(), Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/messaging-service/v1/universes/{universeId}/topics/{topic}",
universeId = params.universe_id,
topic = params.topic,
);
let body_json = json!({
"message": ¶ms.message,
});
let body = serde_json::to_string(&body_json)?;
let res = client
.post(url)
.header("x-api-key", ¶ms.api_key)
.header("Content-Type", "application/json")
.body(body)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
if code == 400 {
return Err(Error::HttpStatusError {
code,
msg: "invalid request".to_string(),
});
} else if code == 401 {
return Err(Error::HttpStatusError {
code,
msg: "api key not valid for operation".to_string(),
});
} else if code == 403 {
return Err(Error::HttpStatusError {
code,
msg: "publish not allowed on place".to_string(),
});
} else if code == 500 {
return Err(Error::HttpStatusError {
code,
msg: "internal server error".to_string(),
});
}
return Err(Error::HttpStatusError {
code,
msg: status.canonical_reason().unwrap_or_default().to_string(),
});
}
Ok(())
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v1/datastore.rs | src/rbx/v1/datastore.rs | //! Low-level DataStore API operations.
//!
//! Typically, these operations should be consumed through the `RbxExperience`
//! struct, obtained through the `RbxCloud` struct.
use reqwest::Response;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use crate::rbx::{
error::Error,
util::{get_checksum_base64, QueryString},
};
use crate::rbx::v1::{ds_error::DataStoreErrorResponse, ReturnLimit, RobloxUserId, UniverseId};
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ListDataStoreEntry {
pub name: String,
pub created_time: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ListDataStoresResponse {
pub datastores: Vec<ListDataStoreEntry>,
pub next_page_cursor: Option<String>,
}
pub struct ListDataStoresParams {
pub api_key: String,
pub universe_id: UniverseId,
pub prefix: Option<String>,
pub limit: ReturnLimit,
pub cursor: Option<String>,
}
pub struct ListEntriesParams {
pub api_key: String,
pub universe_id: UniverseId,
pub datastore_name: String,
pub scope: Option<String>,
pub all_scopes: bool,
pub prefix: Option<String>,
pub limit: ReturnLimit,
pub cursor: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ListEntriesResponse {
pub keys: Vec<ListEntriesKey>,
pub next_page_cursor: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ListEntriesKey {
pub scope: String,
pub key: String,
}
pub struct GetEntryParams {
pub api_key: String,
pub universe_id: UniverseId,
pub datastore_name: String,
pub scope: Option<String>,
pub key: String,
}
pub struct SetEntryParams {
pub api_key: String,
pub universe_id: UniverseId,
pub datastore_name: String,
pub scope: Option<String>,
pub key: String,
pub match_version: Option<String>,
pub exclusive_create: Option<bool>,
pub roblox_entry_user_ids: Option<Vec<RobloxUserId>>,
pub roblox_entry_attributes: Option<String>,
pub data: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SetEntryResponse {
pub version: String,
pub deleted: bool,
pub content_length: u64,
pub created_time: String,
pub object_created_time: String,
}
pub struct IncrementEntryParams {
pub api_key: String,
pub universe_id: UniverseId,
pub datastore_name: String,
pub scope: Option<String>,
pub key: String,
pub roblox_entry_user_ids: Option<Vec<RobloxUserId>>,
pub roblox_entry_attributes: Option<String>,
pub increment_by: f64,
}
pub struct DeleteEntryParams {
pub api_key: String,
pub universe_id: UniverseId,
pub datastore_name: String,
pub scope: Option<String>,
pub key: String,
}
pub struct ListEntryVersionsParams {
pub api_key: String,
pub universe_id: UniverseId,
pub datastore_name: String,
pub scope: Option<String>,
pub key: String,
pub start_time: Option<String>,
pub end_time: Option<String>,
pub sort_order: String,
pub limit: ReturnLimit,
pub cursor: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ListEntryVersionsResponse {
pub versions: Vec<ListEntryVersion>,
pub next_page_cursor: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ListEntryVersion {
pub version: String,
pub deleted: bool,
pub content_length: u64,
pub created_time: String,
pub object_created_time: String,
}
pub struct GetEntryVersionParams {
pub api_key: String,
pub universe_id: UniverseId,
pub datastore_name: String,
pub scope: Option<String>,
pub key: String,
pub version_id: String,
}
async fn handle_datastore_err<T>(res: Response) -> Result<T, Error> {
let response_text = res.text().await?;
match serde_json::from_str::<DataStoreErrorResponse>(&response_text) {
Ok(err_res) => Err(Error::DataStoreError(err_res)),
Err(_) => Err(Error::EndpointError(response_text)),
}
}
async fn handle_res<T: DeserializeOwned>(res: Response) -> Result<T, Error> {
match res.status().is_success() {
true => {
let body = res.json::<T>().await?;
Ok(body)
}
false => handle_datastore_err::<T>(res).await,
}
}
async fn handle_res_string(res: Response) -> Result<String, Error> {
match res.status().is_success() {
true => {
let body = res.text().await?;
Ok(body)
}
false => handle_datastore_err::<String>(res).await,
}
}
async fn handle_res_ok(res: Response) -> Result<(), Error> {
match res.status().is_success() {
true => Ok(()),
false => handle_datastore_err::<()>(res).await,
}
}
fn build_url(endpoint: &str, universe_id: UniverseId) -> String {
if endpoint.is_empty() {
format!("https://apis.roblox.com/datastores/v1/universes/{universe_id}/standard-datastores",)
} else {
format!(
"https://apis.roblox.com/datastores/v1/universes/{universe_id}/standard-datastores{endpoint}",
)
}
}
/// List all DataStores within an experience.
pub async fn list_datastores(
params: &ListDataStoresParams,
) -> Result<ListDataStoresResponse, Error> {
let client = reqwest::Client::new();
let url = build_url("", params.universe_id);
let mut query: QueryString = vec![("limit", params.limit.to_string())];
if let Some(prefix) = ¶ms.prefix {
query.push(("prefix", prefix.clone()));
}
if let Some(cursor) = ¶ms.cursor {
query.push(("cursor", cursor.clone()));
}
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
handle_res::<ListDataStoresResponse>(res).await
}
/// List all entries of a DataStore.
pub async fn list_entries(params: &ListEntriesParams) -> Result<ListEntriesResponse, Error> {
let client = reqwest::Client::new();
let url = build_url("/datastore/entries", params.universe_id);
let mut query: QueryString = vec![
("datastoreName", params.datastore_name.clone()),
("limit", params.limit.to_string()),
("AllScopes", params.all_scopes.to_string()),
(
"scope",
params.scope.clone().unwrap_or_else(|| "global".to_string()),
),
];
if let Some(prefix) = ¶ms.prefix {
query.push(("prefix", prefix.clone()));
}
if let Some(cursor) = ¶ms.cursor {
query.push(("cursor", cursor.clone()));
}
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
handle_res::<ListEntriesResponse>(res).await
}
async fn get_entry_response(params: &GetEntryParams) -> Result<Response, Error> {
let client = reqwest::Client::new();
let url = build_url("/datastore/entries/entry", params.universe_id);
let query: QueryString = vec![
("datastoreName", params.datastore_name.clone()),
(
"scope",
params.scope.clone().unwrap_or_else(|| "global".to_string()),
),
("entryKey", params.key.clone()),
];
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
Ok(res)
}
/// Get the value of an entry as a string.
pub async fn get_entry_string(params: &GetEntryParams) -> Result<String, Error> {
let res = get_entry_response(params).await?;
handle_res_string(res).await
}
/// Get the value of an entry as a JSON-deserialized type `T`.
pub async fn get_entry<T: DeserializeOwned>(params: &GetEntryParams) -> Result<T, Error> {
let res = get_entry_response(params).await?;
handle_res::<T>(res).await
}
fn build_ids_csv(ids: &Option<Vec<RobloxUserId>>) -> String {
ids.as_ref()
.unwrap_or(&vec![])
.iter()
.map(|id| format!("{id}"))
.collect::<Vec<String>>()
.join(",")
}
/// Set the value of an entry.
pub async fn set_entry(params: &SetEntryParams) -> Result<SetEntryResponse, Error> {
let client = reqwest::Client::new();
let url = build_url("/datastore/entries/entry", params.universe_id);
let mut query: QueryString = vec![
("datastoreName", params.datastore_name.clone()),
(
"scope",
params.scope.clone().unwrap_or_else(|| "global".to_string()),
),
("entryKey", params.key.clone()),
];
if let Some(match_version) = ¶ms.match_version {
query.push(("matchVersion", match_version.clone()));
}
if let Some(exclusive_create) = ¶ms.exclusive_create {
query.push(("exclusiveCreate", exclusive_create.to_string()));
}
let res = client
.post(url)
.header("x-api-key", ¶ms.api_key)
.header("Content-Type", "application/json")
.header(
"roblox-entry-userids",
format!("[{}]", build_ids_csv(¶ms.roblox_entry_user_ids)),
)
.header(
"roblox-entry-attributes",
params
.roblox_entry_attributes
.as_ref()
.unwrap_or(&String::from("{}")),
)
.header("content-md5", get_checksum_base64(¶ms.data))
.body(params.data.clone())
.query(&query)
.send()
.await?;
handle_res::<SetEntryResponse>(res).await
}
/// Increment the value of an entry.
pub async fn increment_entry(params: &IncrementEntryParams) -> Result<f64, Error> {
let client = reqwest::Client::new();
let url = build_url("/datastore/entries/entry/increment", params.universe_id);
let query: QueryString = vec![
("datastoreName", params.datastore_name.clone()),
(
"scope",
params.scope.clone().unwrap_or_else(|| "global".to_string()),
),
("entryKey", params.key.clone()),
("incrementBy", params.increment_by.to_string()),
];
let ids = build_ids_csv(¶ms.roblox_entry_user_ids);
let res = client
.post(url)
.header("x-api-key", ¶ms.api_key)
.header("roblox-entry-userids", format!("[{ids}]"))
.header(
"roblox-entry-attributes",
params
.roblox_entry_attributes
.as_ref()
.unwrap_or(&"{}".to_string()),
)
.query(&query)
.send()
.await?;
match handle_res_string(res).await {
Ok(data) => match data.parse::<f64>() {
Ok(num) => Ok(num),
Err(e) => Err(e.into()),
},
Err(err) => Err(err),
}
}
/// Delete an entry.
pub async fn delete_entry(params: &DeleteEntryParams) -> Result<(), Error> {
let client = reqwest::Client::new();
let url = build_url("/datastore/entries/entry", params.universe_id);
let query: QueryString = vec![
("datastoreName", params.datastore_name.clone()),
(
"scope",
params.scope.clone().unwrap_or_else(|| "global".to_string()),
),
("entryKey", params.key.clone()),
];
let res = client
.delete(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
handle_res_ok(res).await
}
/// List all of the versions of an entry.
pub async fn list_entry_versions(
params: &ListEntryVersionsParams,
) -> Result<ListEntryVersionsResponse, Error> {
let client = reqwest::Client::new();
let url = build_url("/datastore/entries/entry/versions", params.universe_id);
let mut query: QueryString = vec![
("datastoreName", params.datastore_name.clone()),
(
"scope",
params.scope.clone().unwrap_or_else(|| "global".to_string()),
),
("entryKey", params.key.to_string()),
("limit", params.limit.to_string()),
("sortOrder", params.sort_order.to_string()),
];
if let Some(start_time) = ¶ms.start_time {
query.push(("startTime", start_time.clone()));
}
if let Some(end_time) = ¶ms.end_time {
query.push(("endTime", end_time.clone()));
}
if let Some(cursor) = ¶ms.cursor {
query.push(("cursor", cursor.clone()));
}
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
handle_res::<ListEntryVersionsResponse>(res).await
}
/// Get the value of a specific entry version.
pub async fn get_entry_version(params: &GetEntryVersionParams) -> Result<String, Error> {
let client = reqwest::Client::new();
let url = build_url(
"/datastore/entries/entry/versions/version",
params.universe_id,
);
let query: QueryString = vec![
("datastoreName", params.datastore_name.clone()),
(
"scope",
params.scope.clone().unwrap_or_else(|| "global".to_string()),
),
("entryKey", params.key.to_string()),
("versionId", params.version_id.to_string()),
];
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
handle_res_string(res).await
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v1/mod.rs | src/rbx/v1/mod.rs | //! Access into Roblox v1 APIs.
//!
//! Most usage should go through the `RbxCloud` struct.
pub mod assets;
pub mod datastore;
pub(crate) mod ds_error;
pub mod experience;
pub mod messaging;
pub mod ordered_datastore;
use crate::rbx::error;
use assets::{ArchiveAssetParams, AssetInfo, GetAssetOperationParams, GetAssetParams};
pub use experience::PublishVersionType;
use serde::de::DeserializeOwned;
use self::{
assets::{
AssetCreation, AssetGetOperation, AssetOperation, AssetType, CreateAssetParams,
CreateAssetParamsWithContents, UpdateAssetParams,
},
datastore::{
DeleteEntryParams, GetEntryParams, GetEntryVersionParams, IncrementEntryParams,
ListDataStoresParams, ListDataStoresResponse, ListEntriesParams, ListEntriesResponse,
ListEntryVersionsParams, ListEntryVersionsResponse, SetEntryParams, SetEntryResponse,
},
error::Error,
experience::{PublishExperienceParams, PublishExperienceResponse},
messaging::PublishMessageParams,
ordered_datastore::{
OrderedCreateEntryParams, OrderedEntry, OrderedEntryParams, OrderedIncrementEntryParams,
OrderedListEntriesParams, OrderedListEntriesResponse, OrderedUpdateEntryParams,
},
};
use super::types::{PageSize, PlaceId, ReturnLimit, RobloxUserId, UniverseId};
impl std::fmt::Display for UniverseId {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::fmt::Display for PlaceId {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::fmt::Display for ReturnLimit {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::fmt::Display for RobloxUserId {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::fmt::Display for PageSize {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::convert::From<u64> for PageSize {
fn from(item: u64) -> Self {
PageSize(item)
}
}
pub struct RbxExperience {
pub universe_id: UniverseId,
pub place_id: PlaceId,
pub api_key: String,
}
impl RbxExperience {
/// Publish a place.
///
/// The filename should point to a `*.rbxl` or `*.rbxlx` file.
pub async fn publish(
&self,
filename: &str,
version_type: PublishVersionType,
) -> Result<PublishExperienceResponse, Error> {
experience::publish_experience(&PublishExperienceParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
place_id: self.place_id,
version_type,
filename: filename.to_string(),
})
.await
}
}
pub struct RbxMessaging {
pub api_key: String,
pub universe_id: UniverseId,
pub topic: String,
}
impl RbxMessaging {
/// Publish a message.
pub async fn publish(&self, message: &str) -> Result<(), Error> {
messaging::publish_message(&PublishMessageParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
topic: self.topic.clone(),
message: message.to_string(),
})
.await
}
}
pub struct RbxDataStore {
pub api_key: String,
pub universe_id: UniverseId,
}
pub struct DataStoreListStores {
pub prefix: Option<String>,
pub limit: ReturnLimit,
pub cursor: Option<String>,
}
pub struct DataStoreListEntries {
pub name: String,
pub scope: Option<String>,
pub all_scopes: bool,
pub prefix: Option<String>,
pub limit: ReturnLimit,
pub cursor: Option<String>,
}
pub struct DataStoreGetEntry {
pub name: String,
pub scope: Option<String>,
pub key: String,
}
pub struct DataStoreSetEntry {
pub name: String,
pub scope: Option<String>,
pub key: String,
pub match_version: Option<String>,
pub exclusive_create: Option<bool>,
pub roblox_entry_user_ids: Option<Vec<RobloxUserId>>,
pub roblox_entry_attributes: Option<String>,
pub data: String,
}
pub struct DataStoreIncrementEntry {
pub name: String,
pub scope: Option<String>,
pub key: String,
pub roblox_entry_user_ids: Option<Vec<RobloxUserId>>,
pub roblox_entry_attributes: Option<String>,
pub increment_by: f64,
}
pub struct DataStoreDeleteEntry {
pub name: String,
pub scope: Option<String>,
pub key: String,
}
pub struct DataStoreListEntryVersions {
pub name: String,
pub scope: Option<String>,
pub key: String,
pub start_time: Option<String>,
pub end_time: Option<String>,
pub sort_order: String,
pub limit: ReturnLimit,
pub cursor: Option<String>,
}
pub struct DataStoreGetEntryVersion {
pub name: String,
pub scope: Option<String>,
pub key: String,
pub version_id: String,
}
impl RbxDataStore {
/// List DataStores within the experience.
pub async fn list_stores(
&self,
params: &DataStoreListStores,
) -> Result<ListDataStoresResponse, Error> {
datastore::list_datastores(&ListDataStoresParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
prefix: params.prefix.clone(),
limit: params.limit,
cursor: params.cursor.clone(),
})
.await
}
/// List key entries in a specific DataStore.
pub async fn list_entries(
&self,
params: &DataStoreListEntries,
) -> Result<ListEntriesResponse, Error> {
datastore::list_entries(&ListEntriesParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
datastore_name: params.name.clone(),
scope: params.scope.clone(),
all_scopes: params.all_scopes,
prefix: params.prefix.clone(),
limit: params.limit,
cursor: params.cursor.clone(),
})
.await
}
/// Get the entry string representation of a specific key.
pub async fn get_entry_string(&self, params: &DataStoreGetEntry) -> Result<String, Error> {
datastore::get_entry_string(&GetEntryParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
datastore_name: params.name.clone(),
scope: params.scope.clone(),
key: params.key.clone(),
})
.await
}
/// Get the entry of a specific key, deserialized as `T`.
pub async fn get_entry<T: DeserializeOwned>(
&self,
params: &DataStoreGetEntry,
) -> Result<T, Error> {
datastore::get_entry::<T>(&GetEntryParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
datastore_name: params.name.clone(),
scope: params.scope.clone(),
key: params.key.clone(),
})
.await
}
/// Set (or create) the entry value of a specific key.
pub async fn set_entry(&self, params: &DataStoreSetEntry) -> Result<SetEntryResponse, Error> {
datastore::set_entry(&SetEntryParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
datastore_name: params.name.clone(),
scope: params.scope.clone(),
key: params.key.clone(),
match_version: params.match_version.clone(),
exclusive_create: params.exclusive_create,
roblox_entry_user_ids: params.roblox_entry_user_ids.clone(),
roblox_entry_attributes: params.roblox_entry_attributes.clone(),
data: params.data.clone(),
})
.await
}
/// Increment (or create) the value of a specific key.
///
/// If the value does not yet exist, it will be treated as `0`, and thus
/// the resulting value will simply be the increment amount.
///
/// If the value _does_ exist, but it is _not_ a number, then the increment
/// process will fail, and a DataStore error will be returned in the result.
pub async fn increment_entry(&self, params: &DataStoreIncrementEntry) -> Result<f64, Error> {
datastore::increment_entry(&IncrementEntryParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
datastore_name: params.name.clone(),
scope: params.scope.clone(),
key: params.key.clone(),
roblox_entry_user_ids: params.roblox_entry_user_ids.clone(),
roblox_entry_attributes: params.roblox_entry_attributes.clone(),
increment_by: params.increment_by,
})
.await
}
/// Delete an entry.
pub async fn delete_entry(&self, params: &DataStoreDeleteEntry) -> Result<(), Error> {
datastore::delete_entry(&DeleteEntryParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
datastore_name: params.name.clone(),
scope: params.scope.clone(),
key: params.key.clone(),
})
.await
}
/// List all versions of an entry.
///
/// To get the specific value of a given entry, use `get_entry_version()`.
pub async fn list_entry_versions(
&self,
params: &DataStoreListEntryVersions,
) -> Result<ListEntryVersionsResponse, Error> {
datastore::list_entry_versions(&ListEntryVersionsParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
datastore_name: params.name.clone(),
scope: params.scope.clone(),
key: params.key.clone(),
start_time: params.start_time.clone(),
end_time: params.end_time.clone(),
sort_order: params.sort_order.clone(),
limit: params.limit,
cursor: params.cursor.clone(),
})
.await
}
/// Get the entry value of a specific version.
pub async fn get_entry_version(
&self,
params: &DataStoreGetEntryVersion,
) -> Result<String, Error> {
datastore::get_entry_version(&GetEntryVersionParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
datastore_name: params.name.clone(),
scope: params.scope.clone(),
key: params.key.clone(),
version_id: params.version_id.clone(),
})
.await
}
}
pub struct RbxOrderedDataStore {
pub api_key: String,
pub universe_id: UniverseId,
}
pub struct OrderedDataStoreListEntries {
pub name: String,
pub scope: Option<String>,
pub max_page_size: Option<PageSize>,
pub page_token: Option<String>,
pub order_by: Option<String>,
pub filter: Option<String>,
}
pub struct OrderedDataStoreCreateEntry {
pub name: String,
pub scope: Option<String>,
pub id: String,
pub value: i64,
}
pub struct OrderedDataStoreUpdateEntry {
pub name: String,
pub scope: Option<String>,
pub id: String,
pub value: i64,
pub allow_missing: Option<bool>,
}
pub struct OrderedDataStoreIncrementEntry {
pub name: String,
pub scope: Option<String>,
pub id: String,
pub increment: i64,
}
pub struct OrderedDataStoreEntry {
pub name: String,
pub scope: Option<String>,
pub id: String,
}
impl RbxOrderedDataStore {
/// List key entries
pub async fn list_entries(
&self,
params: &OrderedDataStoreListEntries,
) -> Result<OrderedListEntriesResponse, Error> {
ordered_datastore::list_entries(&OrderedListEntriesParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
ordered_datastore_name: params.name.clone(),
scope: params.scope.clone(),
max_page_size: params.max_page_size,
page_token: params.page_token.clone(),
order_by: params.order_by.clone(),
filter: params.filter.clone(),
})
.await
}
/// Create an entry
pub async fn create_entry(
&self,
params: &OrderedDataStoreCreateEntry,
) -> Result<OrderedEntry, Error> {
ordered_datastore::create_entry(&OrderedCreateEntryParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
ordered_datastore_name: params.name.clone(),
scope: params.scope.clone(),
id: params.id.to_string(),
value: params.value,
})
.await
}
/// Get an entry
pub async fn get_entry(&self, params: &OrderedDataStoreEntry) -> Result<OrderedEntry, Error> {
ordered_datastore::get_entry(&OrderedEntryParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
ordered_datastore_name: params.name.clone(),
scope: params.scope.clone(),
id: params.id.to_string(),
})
.await
}
/// Delete an entry
pub async fn delete_entry(&self, params: &OrderedDataStoreEntry) -> Result<(), Error> {
ordered_datastore::delete_entry(&OrderedEntryParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
ordered_datastore_name: params.name.clone(),
scope: params.scope.clone(),
id: params.id.to_string(),
})
.await
}
/// Update an entry
pub async fn update_entry(
&self,
params: &OrderedDataStoreUpdateEntry,
) -> Result<OrderedEntry, Error> {
ordered_datastore::update_entry(&OrderedUpdateEntryParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
ordered_datastore_name: params.name.clone(),
scope: params.scope.clone(),
id: params.id.to_string(),
value: params.value,
allow_missing: params.allow_missing,
})
.await
}
/// Increment an entry
pub async fn increment_entry(
&self,
params: &OrderedDataStoreIncrementEntry,
) -> Result<OrderedEntry, Error> {
ordered_datastore::increment_entry(&OrderedIncrementEntryParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
ordered_datastore_name: params.name.clone(),
scope: params.scope.clone(),
id: params.id.to_string(),
increment: params.increment,
})
.await
}
}
pub struct RbxAssets {
/// Roblox API key.
pub api_key: String,
}
pub struct CreateAsset {
pub asset: AssetCreation,
pub filepath: String,
}
pub struct CreateAssetWithContents<'a> {
pub asset: AssetCreation,
pub contents: &'a [u8],
}
pub struct UpdateAsset {
pub asset_id: u64,
pub asset_type: AssetType,
pub filepath: String,
}
pub struct GetAssetOperation {
pub operation_id: String,
}
pub struct GetAsset {
pub asset_id: u64,
pub read_mask: Option<String>,
}
pub struct ArchiveAsset {
pub asset_id: u64,
}
impl RbxAssets {
/// Create an asset
pub async fn create(&self, params: &CreateAsset) -> Result<AssetOperation, Error> {
assets::create_asset(&CreateAssetParams {
api_key: self.api_key.clone(),
asset: params.asset.clone(),
filepath: params.filepath.clone(),
})
.await
}
pub async fn create_with_contents<'a>(
&self,
params: &CreateAssetWithContents<'a>,
) -> Result<AssetOperation, Error> {
assets::create_asset_with_contents(&CreateAssetParamsWithContents {
api_key: self.api_key.clone(),
asset: params.asset.clone(),
contents: params.contents,
})
.await
}
/// Update an asset
pub async fn update(&self, params: &UpdateAsset) -> Result<AssetOperation, Error> {
assets::update_asset(&UpdateAssetParams {
api_key: self.api_key.clone(),
asset_id: params.asset_id,
asset_type: params.asset_type,
filepath: params.filepath.clone(),
})
.await
}
/// Get asset information
pub async fn get_operation(
&self,
params: &GetAssetOperation,
) -> Result<AssetGetOperation, Error> {
assets::get_operation(&GetAssetOperationParams {
api_key: self.api_key.clone(),
operation_id: params.operation_id.clone(),
})
.await
}
pub async fn get(&self, params: &GetAsset) -> Result<AssetInfo, Error> {
assets::get_asset(&GetAssetParams {
api_key: self.api_key.clone(),
asset_id: params.asset_id,
read_mask: params.read_mask.clone(),
})
.await
}
pub async fn archive(&self, params: &ArchiveAsset) -> Result<AssetInfo, Error> {
assets::archive_asset(&ArchiveAssetParams {
api_key: self.api_key.clone(),
asset_id: params.asset_id,
})
.await
}
pub async fn restore(&self, params: &ArchiveAsset) -> Result<AssetInfo, Error> {
assets::restore_asset(&ArchiveAssetParams {
api_key: self.api_key.clone(),
asset_id: params.asset_id,
})
.await
}
}
/// Access into the Roblox Open Cloud APIs.
///
/// ```rust,no_run
/// use rbxcloud::rbx::v1::RbxCloud;
///
/// let cloud = RbxCloud::new("API_KEY");
/// ```
#[derive(Debug)]
pub struct RbxCloud {
/// Roblox API key.
pub api_key: String,
}
impl RbxCloud {
pub fn new(api_key: &str) -> RbxCloud {
RbxCloud {
api_key: api_key.to_string(),
}
}
pub fn assets(&self) -> RbxAssets {
RbxAssets {
api_key: self.api_key.clone(),
}
}
pub fn experience(&self, universe_id: UniverseId, place_id: PlaceId) -> RbxExperience {
RbxExperience {
api_key: self.api_key.clone(),
universe_id,
place_id,
}
}
pub fn messaging(&self, universe_id: UniverseId, topic: &str) -> RbxMessaging {
RbxMessaging {
api_key: self.api_key.clone(),
universe_id,
topic: topic.to_string(),
}
}
pub fn datastore(&self, universe_id: UniverseId) -> RbxDataStore {
RbxDataStore {
api_key: self.api_key.clone(),
universe_id,
}
}
pub fn ordered_datastore(&self, universe_id: UniverseId) -> RbxOrderedDataStore {
RbxOrderedDataStore {
api_key: self.api_key.clone(),
universe_id,
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v1/experience.rs | src/rbx/v1/experience.rs | //! Low-level Experience API operations.
use std::fmt;
use serde::{Deserialize, Serialize};
use crate::rbx::error::Error;
use crate::rbx::v1::{PlaceId, UniverseId};
/// The version type of a place publish operation.
#[derive(Debug, Clone)]
pub enum PublishVersionType {
/// Place is saved as the most-recent version. Players who play
/// the game will _not_ see this version, but it _will_ be the
/// version that is seen when loaded in with Studio.
Saved,
/// Place is saved as the most-recent live version. Players who
/// play the game will play this version.
Published,
}
impl fmt::Display for PublishVersionType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{self:?}")
}
}
/// Parameters for publishing a place.
pub struct PublishExperienceParams {
pub api_key: String,
pub universe_id: UniverseId,
pub place_id: PlaceId,
pub version_type: PublishVersionType,
pub filename: String,
}
/// Response from Roblox when place is published or saved.
///
/// The version number represents the latest version uploaded
/// to Roblox.
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PublishExperienceResponse {
pub version_number: u64,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct PublishExperienceErrorResponse {
message: String,
}
/// Publish a place under a specific experience.
pub async fn publish_experience(
params: &PublishExperienceParams,
) -> Result<PublishExperienceResponse, Error> {
let client = reqwest::Client::new();
let bytes_data_buf = std::fs::read(¶ms.filename)?;
let url = format!(
"https://apis.roblox.com/universes/v1/{universeId}/places/{placeId}/versions?versionType={versionType}",
universeId=params.universe_id,
placeId=params.place_id,
versionType=params.version_type,
);
let res = client
.post(url)
.header("x-api-key", ¶ms.api_key)
.header("Content-Type", "application/octet-stream")
.body(bytes_data_buf)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
let msg_text = res.text().await;
let msg_json = msg_text
.map(|txt| {
serde_json::from_str::<PublishExperienceErrorResponse>(txt.as_str())
.unwrap_or(PublishExperienceErrorResponse { message: txt })
})
.map(|err| err.message);
let msg = msg_json.unwrap_or(status.canonical_reason().unwrap_or_default().to_string());
return match code {
400 | 401 | 403 | 404 | 409 | 500 => Err(Error::HttpStatusError { code, msg }),
_ => Err(Error::HttpStatusError {
code,
msg: status.canonical_reason().unwrap_or_default().to_string(),
}),
};
}
let body = res.json::<PublishExperienceResponse>().await?;
Ok(body)
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v1/ordered_datastore.rs | src/rbx/v1/ordered_datastore.rs | //! Low-level OrderedDataStore API operations.
//!
//! Typically, these operations should be consumed through the `RbxExperience`
//! struct, obtained through the `RbxCloud` struct.
//!
use reqwest::Response;
use serde::Serialize;
use serde::{de::DeserializeOwned, Deserialize};
use serde_json::json;
use crate::rbx::v1::{PageSize, UniverseId};
use crate::rbx::{error::Error, util::QueryString};
pub struct OrderedListEntriesParams {
pub api_key: String,
pub universe_id: UniverseId,
pub ordered_datastore_name: String,
pub scope: Option<String>,
pub max_page_size: Option<PageSize>,
pub page_token: Option<String>,
pub order_by: Option<String>,
pub filter: Option<String>,
}
pub struct OrderedCreateEntryParams {
pub api_key: String,
pub universe_id: UniverseId,
pub ordered_datastore_name: String,
pub scope: Option<String>,
pub id: String,
pub value: i64,
}
pub struct OrderedUpdateEntryParams {
pub api_key: String,
pub universe_id: UniverseId,
pub ordered_datastore_name: String,
pub scope: Option<String>,
pub id: String,
pub value: i64,
pub allow_missing: Option<bool>,
}
pub struct OrderedIncrementEntryParams {
pub api_key: String,
pub universe_id: UniverseId,
pub ordered_datastore_name: String,
pub scope: Option<String>,
pub id: String,
pub increment: i64,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OrderedEntry {
pub path: String,
pub id: String,
pub value: i64,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OrderedListEntriesResponse {
pub entries: Vec<OrderedEntry>,
pub next_page_token: Option<String>,
}
pub struct OrderedEntryParams {
pub api_key: String,
pub universe_id: UniverseId,
pub ordered_datastore_name: String,
pub scope: Option<String>,
pub id: String,
}
async fn handle_res<T: DeserializeOwned>(res: Response) -> Result<T, Error> {
let status = res.status();
match status.is_success() {
true => {
let body = res.json::<T>().await?;
Ok(body)
}
false => {
let text = res.text().await?;
Err(Error::HttpStatusError {
code: status.as_u16(),
msg: text,
})
}
}
}
async fn handle_res_ok(res: Response) -> Result<(), Error> {
let status = res.status();
match status.is_success() {
true => Ok(()),
false => {
let text = res.text().await?;
Err(Error::HttpStatusError {
code: status.as_u16(),
msg: text,
})
}
}
}
fn build_url(
endpoint: &str,
universe_id: UniverseId,
data_store: &str,
scope: Option<&str>,
) -> String {
let s = scope.unwrap_or("global");
if endpoint.is_empty() {
format!("https://apis.roblox.com/ordered-data-stores/v1/universes/{universe_id}/orderedDataStores/{data_store}/scopes/{s}")
} else {
format!(
"https://apis.roblox.com/ordered-data-stores/v1/universes/{universe_id}/orderedDataStores/{data_store}/scopes/{s}{endpoint}",
)
}
}
/// List entries of an OrderedDataStore.
pub async fn list_entries(
params: &OrderedListEntriesParams,
) -> Result<OrderedListEntriesResponse, Error> {
let client = reqwest::Client::new();
let url = build_url(
"/entries",
params.universe_id,
¶ms.ordered_datastore_name,
params.scope.as_deref(),
);
let mut query: QueryString = vec![];
if let Some(max_page_size) = ¶ms.max_page_size {
query.push(("max_page_size", max_page_size.to_string()));
}
if let Some(page_token) = ¶ms.page_token {
query.push(("page_token", page_token.to_string()));
}
if let Some(order_by) = ¶ms.order_by {
query.push(("order_by", order_by.to_string()));
}
if let Some(filter) = ¶ms.filter {
query.push(("filter", filter.to_string()));
}
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
handle_res::<OrderedListEntriesResponse>(res).await
}
/// Add a new entry to an OrderedDataStore.
pub async fn create_entry(params: &OrderedCreateEntryParams) -> Result<OrderedEntry, Error> {
let client = reqwest::Client::new();
let url = build_url(
"/entries",
params.universe_id,
¶ms.ordered_datastore_name,
params.scope.as_deref(),
);
let query: QueryString = vec![("id", params.id.to_string())];
let body_json = json!({
"value": ¶ms.value,
});
let body = serde_json::to_string(&body_json)?;
let res = client
.post(url)
.header("x-api-key", ¶ms.api_key)
.header("Content-Type", "application/json")
.query(&query)
.body(body.clone())
.send()
.await?;
handle_res::<OrderedEntry>(res).await
}
pub async fn get_entry(params: &OrderedEntryParams) -> Result<OrderedEntry, Error> {
let client = reqwest::Client::new();
let url = build_url(
format!("/entries/{entry}", entry = params.id).as_str(),
params.universe_id,
¶ms.ordered_datastore_name,
params.scope.as_deref(),
);
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.send()
.await?;
handle_res::<OrderedEntry>(res).await
}
pub async fn delete_entry(params: &OrderedEntryParams) -> Result<(), Error> {
let client = reqwest::Client::new();
let url = build_url(
format!("/entries/{entry}", entry = params.id).as_str(),
params.universe_id,
¶ms.ordered_datastore_name,
params.scope.as_deref(),
);
let res = client
.delete(url)
.header("x-api-key", ¶ms.api_key)
.send()
.await?;
handle_res_ok(res).await
}
pub async fn update_entry(params: &OrderedUpdateEntryParams) -> Result<OrderedEntry, Error> {
let client = reqwest::Client::new();
let url = build_url(
format!("/entries/{entry}", entry = params.id).as_str(),
params.universe_id,
¶ms.ordered_datastore_name,
params.scope.as_deref(),
);
let mut query: QueryString = vec![];
if let Some(allow_missing) = ¶ms.allow_missing {
query.push(("allow_missing", allow_missing.to_string()));
}
let body_json = json!({
"value": ¶ms.value,
});
let body = serde_json::to_string(&body_json)?;
let res = client
.patch(url)
.header("x-api-key", ¶ms.api_key)
.header("Content-Type", "application/json")
.body(body)
.query(&query)
.send()
.await?;
handle_res::<OrderedEntry>(res).await
}
pub async fn increment_entry(params: &OrderedIncrementEntryParams) -> Result<OrderedEntry, Error> {
let client = reqwest::Client::new();
let url = build_url(
format!("/entries/{entry}:increment", entry = params.id).as_str(),
params.universe_id,
¶ms.ordered_datastore_name,
params.scope.as_deref(),
);
let body_json = json!({
"amount": ¶ms.increment,
});
let body = serde_json::to_string(&body_json)?;
let res = client
.post(url)
.header("x-api-key", ¶ms.api_key)
.header("Content-Type", "application/json")
.body(body)
.send()
.await?;
handle_res::<OrderedEntry>(res).await
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v1/assets.rs | src/rbx/v1/assets.rs | use std::{fs, path::Path};
use crate::rbx::{error::Error, util::QueryString};
use reqwest::{multipart, Response};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::json;
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AssetUserCreator {
pub user_id: String,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AssetGroupCreator {
pub group_id: String,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(untagged)]
pub enum AssetCreator {
User(AssetUserCreator),
Group(AssetGroupCreator),
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AssetCreationContext {
pub creator: AssetCreator,
pub expected_price: Option<u64>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Asset {
pub asset_type: String,
pub asset_id: u64,
pub creation_context: AssetCreationContext,
pub description: String,
pub display_name: String,
pub path: String,
pub revision_id: String,
pub revision_create_time: String,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AssetCreation {
pub asset_type: AssetType,
pub display_name: String,
pub description: String,
pub creation_context: AssetCreationContext,
}
pub struct CreateAssetParams {
pub api_key: String,
pub asset: AssetCreation,
pub filepath: String,
}
pub struct CreateAssetParamsWithContents<'a> {
pub api_key: String,
pub asset: AssetCreation,
pub contents: &'a [u8],
}
pub struct UpdateAssetParams {
pub api_key: String,
pub asset_id: u64,
pub asset_type: AssetType,
pub filepath: String,
}
pub struct GetAssetOperationParams {
pub api_key: String,
pub operation_id: String,
}
pub struct GetAssetParams {
pub api_key: String,
pub asset_id: u64,
pub read_mask: Option<String>,
}
pub struct ArchiveAssetParams {
pub api_key: String,
pub asset_id: u64,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct AssetOperation {
pub path: Option<String>,
pub metadata: Option<ProtobufAny>,
pub done: Option<bool>,
pub error: Option<AssetErrorStatus>,
pub response: Option<ProtobufAny>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ProtobufAny {
#[serde(rename = "@type")]
pub message_type: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct AssetGetOperation {
pub path: String,
pub done: Option<bool>,
pub response: Option<AssetGetOperationResponse>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct AssetGetOperationResponse {
pub path: String,
pub revision_id: String,
pub revision_create_time: String,
pub asset_id: String,
pub display_name: String,
pub description: String,
pub asset_type: String,
pub creation_context: AssetCreationContext,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct AssetInfo {
pub asset_type: AssetTypeCategory,
pub asset_id: String,
pub creation_context: AssetCreationContext,
pub description: String,
pub display_name: String,
pub path: String,
pub revision_id: String,
pub revision_create_time: String,
pub moderation_result: ModerationResult,
pub state: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ModerationResult {
/// Note: There's a discrepancy between the Open Cloud docs and the actual
/// data from the API regarding what this value can be, hence it has been
/// left as a string and not an enum.
pub moderation_state: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct AssetErrorStatus {
pub code: u64,
pub message: String,
pub details: Vec<ProtobufAny>,
}
#[derive(Debug, Clone, Copy, clap::ValueEnum, Deserialize)]
pub enum AssetType {
AudioMp3,
AudioOgg,
AudioFlac,
AudioWav,
DecalPng,
DecalJpeg,
DecalBmp,
DecalTga,
ModelFbx,
}
#[derive(Debug, Clone, Copy, clap::ValueEnum, Serialize, Deserialize)]
pub enum AssetTypeCategory {
Audio,
Decal,
Model,
}
impl AssetType {
fn content_type(&self) -> &'static str {
match self {
Self::AudioMp3 => "audio/mpeg",
Self::AudioOgg => "audio/ogg",
Self::AudioFlac => "audio/flac",
Self::AudioWav => "audio/wav",
Self::DecalPng => "image/png",
Self::DecalJpeg => "image/jpeg",
Self::DecalBmp => "image/bmp",
Self::DecalTga => "image/tga",
Self::ModelFbx => "model/fbx",
}
}
fn asset_type(&self) -> &'static str {
match self {
Self::AudioMp3 | Self::AudioOgg | Self::AudioFlac | Self::AudioWav => "Audio",
Self::DecalPng | Self::DecalJpeg | Self::DecalBmp | Self::DecalTga => "Decal",
Self::ModelFbx => "Model",
}
}
pub fn try_from_extension(extension: &str) -> Result<Self, crate::rbx::error::Error> {
match extension.to_lowercase().as_str() {
"mp3" => Ok(Self::AudioMp3),
"ogg" => Ok(Self::AudioOgg),
"flac" => Ok(Self::AudioFlac),
"wav" => Ok(Self::AudioWav),
"png" => Ok(Self::DecalPng),
"jpg" => Ok(Self::DecalJpeg),
"jpeg" => Ok(Self::DecalJpeg),
"bmp" => Ok(Self::DecalBmp),
"tga" => Ok(Self::DecalTga),
"fbx" => Ok(Self::ModelFbx),
_ => Err(crate::rbx::error::Error::InferAssetTypeError(
"Unknown extension".to_string(),
)),
}
}
}
impl Serialize for AssetType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.asset_type())
}
}
async fn handle_res<T: DeserializeOwned>(res: Response) -> Result<T, Error> {
let status = res.status();
match status.is_success() {
true => {
let body = res.json::<T>().await?;
Ok(body)
}
false => {
let text = res.text().await?;
Err(Error::HttpStatusError {
code: status.as_u16(),
msg: text,
})
}
}
}
fn build_url(asset_id: Option<u64>) -> String {
if let Some(asset_id) = asset_id {
format!("https://apis.roblox.com/assets/v1/assets/{asset_id}")
} else {
"https://apis.roblox.com/assets/v1/assets".to_string()
}
}
pub async fn create_asset(params: &CreateAssetParams) -> Result<AssetOperation, Error> {
let file_name = Path::new(¶ms.filepath)
.file_name()
.ok_or_else(|| Error::FileLoadError("Failed to parse file name from file path".into()))?
.to_os_string()
.into_string()
.map_err(|err| {
Error::FileLoadError(format!("Failed to convert file name into string: {err:?}"))
})?;
let asset_info = serde_json::to_string(¶ms.asset)?;
let file = multipart::Part::bytes(fs::read(¶ms.filepath)?)
.file_name(file_name)
.mime_str(params.asset.asset_type.content_type())?;
let form = multipart::Form::new()
.text("request", asset_info)
.part("fileContent", file);
let client = reqwest::Client::new();
let url = build_url(None);
let res = client
.post(url)
.header("x-api-key", ¶ms.api_key)
.multipart(form)
.send()
.await?;
handle_res::<AssetOperation>(res).await
}
pub async fn create_asset_with_contents<'a>(
params: &CreateAssetParamsWithContents<'a>,
) -> Result<AssetOperation, Error> {
let file = multipart::Part::bytes(params.contents.to_vec())
.file_name(params.asset.display_name.clone())
.mime_str(params.asset.asset_type.content_type())?;
let asset_info = serde_json::to_string(¶ms.asset)?;
let form = multipart::Form::new()
.text("request", asset_info)
.part("fileContent", file);
let client = reqwest::Client::new();
let url = build_url(None);
let res = client
.post(url)
.header("x-api-key", ¶ms.api_key)
.multipart(form)
.send()
.await?;
handle_res::<AssetOperation>(res).await
}
pub async fn update_asset(params: &UpdateAssetParams) -> Result<AssetOperation, Error> {
let file_name = Path::new(¶ms.filepath)
.file_name()
.ok_or_else(|| Error::FileLoadError("Failed to parse file name from file path".into()))?
.to_os_string()
.into_string()
.map_err(|err| {
Error::FileLoadError(format!("Failed to convert file name into string: {err:?}"))
})?;
let file = multipart::Part::bytes(fs::read(¶ms.filepath)?)
.file_name(file_name)
.mime_str(params.asset_type.content_type())?;
let request_json = json!({
"assetId": params.asset_id,
});
let request = serde_json::to_string(&request_json)?;
let form = multipart::Form::new()
.text("request", request)
.part("fileContent", file);
let client = reqwest::Client::new();
let url = build_url(Some(params.asset_id));
let res = client
.patch(url)
.header("x-api-key", ¶ms.api_key)
.multipart(form)
.send()
.await?;
handle_res::<AssetOperation>(res).await
}
pub async fn get_operation(params: &GetAssetOperationParams) -> Result<AssetGetOperation, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/assets/v1/operations/{operationId}",
operationId = params.operation_id
);
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.send()
.await?;
handle_res::<AssetGetOperation>(res).await
}
pub async fn get_asset(params: &GetAssetParams) -> Result<AssetInfo, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/assets/v1/assets/{assetId}",
assetId = params.asset_id
);
let mut query: QueryString = vec![];
if let Some(read_mask) = ¶ms.read_mask {
query.push(("readMask", read_mask.clone()));
}
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
handle_res::<AssetInfo>(res).await
}
pub async fn archive_asset(params: &ArchiveAssetParams) -> Result<AssetInfo, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/assets/v1/assets/{assetId}:archive",
assetId = params.asset_id
);
let res = client
.post(url)
.header("x-api-key", ¶ms.api_key)
.header("Content-Type", "application/json")
.send()
.await?;
handle_res::<AssetInfo>(res).await
}
pub async fn restore_asset(params: &ArchiveAssetParams) -> Result<AssetInfo, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/assets/v1/assets/{assetId}:restore",
assetId = params.asset_id
);
let res = client
.post(url)
.header("x-api-key", ¶ms.api_key)
.header("Content-Type", "application/json")
.send()
.await?;
handle_res::<AssetInfo>(res).await
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v2/user.rs | src/rbx/v2/user.rs | use serde::{Deserialize, Serialize};
use crate::rbx::{error::Error, types::RobloxUserId, util::QueryString};
use super::http_err::handle_http_err;
pub struct GetUserParams {
pub api_key: String,
pub user_id: RobloxUserId,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UserSocialNetworkVisibility {
SocialNetworkVisibilityUnspecified,
NoOne,
Friends,
FriendsAndFollowing,
FriendsFollowingAndFollowers,
Everyone,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UserSocialNetworkProfiles {
facebook: String,
twitter: String,
youtube: String,
twitch: String,
guilded: String,
visibility: String,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GetUserResponse {
pub path: String,
pub create_time: String,
pub id: String,
pub name: String,
pub display_name: String,
pub about: String,
pub locale: String,
pub premium: Option<bool>,
pub id_verified: Option<bool>,
pub social_network_profiles: Option<UserSocialNetworkProfiles>,
}
pub struct GenerateUserThumbnailParams {
pub api_key: String,
pub user_id: RobloxUserId,
pub size: Option<UserThumbnailSize>,
pub format: Option<UserThumbnailFormat>,
pub shape: Option<UserThumbnailShape>,
}
#[derive(Deserialize, Serialize, Debug, Clone, clap::ValueEnum)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UserThumbnailFormat {
Png,
Jpeg,
}
#[derive(Deserialize, Serialize, Debug, Clone, clap::ValueEnum)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UserThumbnailSize {
Size48x48,
Size50x50,
Size60x60,
Size75x75,
Size100x100,
Size110x110,
Size150x150,
Size180x180,
Size352x352,
Size420x420,
Size720x720,
}
#[derive(Deserialize, Serialize, Debug, Clone, clap::ValueEnum)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UserThumbnailShape {
Round,
Square,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GenerateUserThumbnailOperationResponse {
pub path: String,
pub done: bool,
pub response: GenerateUserThumbnailResponse,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GenerateUserThumbnailResponse {
pub image_uri: String,
}
impl std::fmt::Display for UserThumbnailSize {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(
f,
"{:?}",
match self {
Self::Size48x48 => "48",
Self::Size50x50 => "50",
Self::Size60x60 => "60",
Self::Size75x75 => "75",
Self::Size100x100 => "100",
Self::Size110x110 => "110",
Self::Size150x150 => "150",
Self::Size180x180 => "180",
Self::Size352x352 => "352",
Self::Size420x420 => "420",
Self::Size720x720 => "720",
}
)
}
}
impl std::fmt::Display for UserThumbnailFormat {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(
f,
"{:?}",
match self {
Self::Png => "PNG",
Self::Jpeg => "JPEG",
}
)
}
}
impl std::fmt::Display for UserThumbnailShape {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(
f,
"{:?}",
match self {
Self::Round => "ROUND",
Self::Square => "SQUARE",
}
)
}
}
pub async fn get_user(params: &GetUserParams) -> Result<GetUserResponse, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/users/{user}",
user = ¶ms.user_id,
);
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<GetUserResponse>().await?;
Ok(body)
}
pub async fn generate_thumbnail(
params: &GenerateUserThumbnailParams,
) -> Result<GenerateUserThumbnailOperationResponse, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/users/{user}:generateThumbnail",
user = ¶ms.user_id,
);
let mut query: QueryString = vec![];
if let Some(size) = ¶ms.size {
query.push(("size", size.to_string()))
}
if let Some(format) = ¶ms.format {
query.push(("format", format.to_string()))
}
if let Some(shape) = ¶ms.shape {
query.push(("shape", shape.to_string()))
}
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<GenerateUserThumbnailOperationResponse>().await?;
Ok(body)
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v2/inventory.rs | src/rbx/v2/inventory.rs | use serde::{Deserialize, Serialize};
use crate::rbx::{error::Error, types::RobloxUserId, util::QueryString};
use super::http_err::handle_http_err;
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ListInventoryItemsParams {
pub api_key: String,
pub user_id: RobloxUserId,
pub max_page_size: Option<u32>,
pub page_token: Option<String>,
pub filter: Option<String>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InventoryItems {
inventory_items: Vec<InventoryItem>,
next_page_token: String,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InventoryItem {
path: String,
#[serde(skip_serializing_if = "Option::is_none")]
asset_details: Option<InventoryItemAssetDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
badge_details: Option<InventoryItemBadgeDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
game_pass_details: Option<InventoryItemGamePassDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
private_server_details: Option<InventoryItemPrivateServerDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
add_time: Option<String>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InventoryItemAssetDetails {
asset_id: String,
instance_id: String,
inventory_item_asset_type: InventoryItemAssetType,
#[serde(skip_serializing_if = "Option::is_none")]
collectible_details: Option<InventoryItemCollectibleDetails>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InventoryItemBadgeDetails {
badge_id: String,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InventoryItemGamePassDetails {
game_pass_id: String,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InventoryItemPrivateServerDetails {
private_server_id: String,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InventoryItemCollectibleDetails {
item_id: String,
instance_id: String,
instance_state: InventoryItemInstanceState,
#[serde(skip_serializing_if = "Option::is_none")]
serial_number: Option<u64>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum InventoryItemInstanceState {
CollectibleItemInstanceStateUnspecified,
Available,
Hold,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum InventoryItemAssetType {
ClassicTshirt,
Audio,
Hat,
Model,
ClassicShirt,
ClassicPants,
Decal,
ClassicHead,
Face,
Gear,
Animation,
Torso,
RightArm,
LeftArm,
LeftLeg,
RightLeg,
Package,
Plugin,
MeshPart,
HairAccessory,
FaceAccessory,
NeckAccessory,
ShoulderAccessory,
FrontAccessory,
BackAccessory,
WaistAccessory,
ClimbAnimation,
DeathAnimation,
FallAnimation,
IdleAnimation,
JumpAnimation,
RunAnimation,
SwimAnimation,
WalkAnimation,
PoseAnimation,
EmoteAnimation,
Video,
TshirtAccessory,
ShirtAccessory,
PantsAccessory,
JacketAccessory,
SweaterAccessory,
ShortsAccessory,
LeftShoeAccessory,
RightShoeAccessory,
DressSkirtAccessory,
EyebrowAccessory,
EyelashAccessory,
MoodAnimation,
DynamicHead,
CreatedPlace,
PurchasedPlace,
}
pub async fn list_inventory_items(
params: &ListInventoryItemsParams,
) -> Result<InventoryItems, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/users/{userId}/inventory-items",
userId = params.user_id,
);
let mut query: QueryString = vec![];
if let Some(max_page_size) = params.max_page_size {
query.push(("maxPageSize", format!("{max_page_size}")));
}
if let Some(page_token) = ¶ms.page_token {
query.push(("pageToken", page_token.clone()));
}
if let Some(filter) = ¶ms.filter {
query.push(("filter", filter.clone()));
}
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<InventoryItems>().await?;
Ok(body)
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v2/place.rs | src/rbx/v2/place.rs | use super::http_err::handle_http_err;
use crate::rbx::{
error::Error,
types::{PlaceId, UniverseId},
util::QueryString,
};
use serde::{Deserialize, Serialize};
pub struct GetPlaceParams {
pub api_key: String,
pub universe_id: UniverseId,
pub place_id: PlaceId,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PlaceInfo {
pub path: String,
pub create_time: String,
pub update_time: String,
pub display_name: String,
pub description: String,
pub server_size: u32,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UpdatePlaceInfo {
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub create_time: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub update_time: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub server_size: Option<u32>,
}
pub struct UpdatePlaceParams {
pub api_key: String,
pub universe_id: UniverseId,
pub place_id: PlaceId,
pub update_mask: String,
pub info: UpdatePlaceInfo,
}
pub async fn get_place(params: &GetPlaceParams) -> Result<PlaceInfo, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/places/{placeId}",
universeId = ¶ms.universe_id,
placeId = ¶ms.place_id,
);
let res = client
.get(&url)
.header("x-api-key", ¶ms.api_key)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<PlaceInfo>().await?;
Ok(body)
}
pub async fn update_place(params: &UpdatePlaceParams) -> Result<PlaceInfo, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/places/{placeId}",
universeId = ¶ms.universe_id,
placeId = ¶ms.place_id,
);
let query: QueryString = vec![("updateMask", params.update_mask.clone())];
let body = serde_json::to_string(¶ms.info)?;
let res = client
.patch(url)
.header("x-api-key", ¶ms.api_key)
.header("Content-Type", "application/json")
.body(body)
.query(&query)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<PlaceInfo>().await?;
Ok(body)
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v2/group.rs | src/rbx/v2/group.rs | use serde::{Deserialize, Serialize};
use crate::rbx::{error::Error, types::GroupId, util::QueryString};
use super::http_err::handle_http_err;
impl std::fmt::Display for GroupId {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
pub struct GetGroupParams {
pub api_key: String,
pub group_id: GroupId,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GetGroupResponse {
pub path: String,
pub create_time: String,
pub update_time: String,
pub id: String,
pub display_name: String,
pub description: String,
pub owner: Option<String>,
pub member_count: u64,
pub public_entry_allowed: bool,
pub locked: bool,
pub verified: bool,
}
pub struct GetGroupShoutParams {
pub api_key: String,
pub group_id: GroupId,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GetGroupShoutResponse {
pub path: String,
pub create_time: String,
pub update_time: String,
pub content: String,
pub poster: Option<String>,
}
pub struct ListGroupRolesParams {
pub api_key: String,
pub group_id: GroupId,
pub max_page_size: Option<u32>,
pub page_token: Option<String>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GroupRolePermission {
pub view_wall_posts: bool,
pub create_wall_posts: bool,
pub delete_wall_posts: bool,
pub view_group_shout: bool,
pub create_group_shout: bool,
pub change_rank: bool,
pub accept_requests: bool,
pub exile_members: bool,
pub manage_relationships: bool,
pub view_audit_log: bool,
pub spend_group_funds: bool,
pub advertise_group: bool,
pub create_avatar_items: bool,
pub manage_avatar_items: bool,
pub manage_group_universes: bool,
pub view_universe_analytics: bool,
pub create_api_keys: bool,
pub manage_api_keys: bool,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GroupRole {
pub path: String,
pub create_time: Option<String>,
pub update_time: Option<String>,
pub id: String,
pub display_name: String,
pub description: Option<String>,
pub rank: u32,
pub member_count: Option<u64>,
pub permissions: Option<GroupRolePermission>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ListGroupRolesResponse {
pub group_roles: Vec<GroupRole>,
pub next_page_token: Option<String>,
}
pub struct ListGroupMembershipsParams {
pub api_key: String,
pub group_id: GroupId,
pub max_page_size: Option<u32>,
pub page_token: Option<String>,
pub filter: Option<String>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GroupMembership {
pub path: String,
pub create_time: String,
pub update_time: String,
pub user: String,
pub role: String,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ListGroupMembershipsResponse {
pub group_memberships: Vec<GroupMembership>,
pub next_page_token: Option<String>,
}
pub async fn get_group(params: &GetGroupParams) -> Result<GetGroupResponse, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/groups/{groupId}",
groupId = ¶ms.group_id,
);
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<GetGroupResponse>().await?;
Ok(body)
}
pub async fn get_group_shout(params: &GetGroupShoutParams) -> Result<GetGroupShoutResponse, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/groups/{groupId}/shout",
groupId = ¶ms.group_id,
);
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<GetGroupShoutResponse>().await?;
Ok(body)
}
pub async fn list_group_roles(
params: &ListGroupRolesParams,
) -> Result<ListGroupRolesResponse, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/groups/{groupId}/roles",
groupId = ¶ms.group_id,
);
let mut query: QueryString = vec![];
if let Some(max_page_size) = ¶ms.max_page_size {
query.push(("maxPageSize", max_page_size.to_string()))
}
if let Some(page_token) = ¶ms.page_token {
query.push(("pageToken", page_token.clone()));
}
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<ListGroupRolesResponse>().await?;
Ok(body)
}
pub async fn list_group_memberships(
params: &ListGroupMembershipsParams,
) -> Result<ListGroupMembershipsResponse, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/groups/{groupId}/memberships",
groupId = ¶ms.group_id,
);
let mut query: QueryString = vec![];
if let Some(max_page_size) = ¶ms.max_page_size {
query.push(("maxPageSize", max_page_size.to_string()))
}
if let Some(page_token) = ¶ms.page_token {
query.push(("pageToken", page_token.clone()));
}
if let Some(filter) = ¶ms.filter {
query.push(("filter", filter.clone()));
}
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<ListGroupMembershipsResponse>().await?;
Ok(body)
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v2/notification.rs | src/rbx/v2/notification.rs | use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::rbx::{error::Error, types::RobloxUserId};
use super::http_err::handle_http_err;
#[derive(Deserialize, Serialize, Debug)]
pub enum NotificationType {
TypeUnspecified,
Moment,
}
impl std::fmt::Display for NotificationType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{:?}",
match self {
Self::TypeUnspecified => "TYPE_UNSPECIFIED",
Self::Moment => "MOMENT",
}
)
}
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct JoinExperience {
pub launch_data: String,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Parameter {
pub string_value: Option<String>,
pub int64_value: Option<i64>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct NotificationSource {
pub universe: String,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct NotificationPayload {
pub message_id: String,
#[serde(rename(serialize = "type"))]
pub notification_type: NotificationType,
pub parameters: Option<HashMap<String, Parameter>>,
pub join_experience: Option<JoinExperience>,
pub analytics_data: Option<HashMap<String, String>>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Notification {
pub source: NotificationSource,
pub payload: NotificationPayload,
}
#[derive(Debug)]
pub struct NotificationParams {
pub api_key: String,
pub user_id: RobloxUserId,
pub notification: Notification,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct NotificationResponse {
pub path: String,
pub id: String,
}
pub async fn send_notification(params: &NotificationParams) -> Result<NotificationResponse, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/users/{user}/notifications",
user = ¶ms.user_id,
);
let body = serde_json::to_string(¶ms.notification)?;
let res = client
.post(url)
.header("x-api-key", ¶ms.api_key)
.body(body)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<NotificationResponse>().await?;
Ok(body)
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v2/user_restriction.rs | src/rbx/v2/user_restriction.rs | use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use crate::rbx::{
error::Error,
types::{PlaceId, RobloxUserId, UniverseId},
util::QueryString,
};
use super::http_err::handle_http_err;
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GameJoinRestriction {
pub active: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub start_time: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub duration: Option<String>,
pub private_reason: String,
pub display_reason: String,
pub exclude_alt_accounts: bool,
pub inherited: bool,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UserRestriction {
pub path: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub update_time: Option<DateTime<Utc>>,
pub user: String,
pub game_join_restriction: GameJoinRestriction,
}
pub struct UpdateUserRestrictionParams {
pub api_key: String,
pub universe_id: UniverseId,
pub place_id: Option<PlaceId>,
pub user_id: RobloxUserId,
pub idempotency_key: Option<String>,
pub active: Option<bool>,
pub duration: Option<String>,
pub private_reason: Option<String>,
pub display_reason: Option<String>,
pub exclude_alt_accounts: Option<bool>,
}
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct UpdateUserRestriction {
game_join_restriction: GameJoinRestriction,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UserRestrictionList {
pub user_restrictions: Vec<UserRestriction>,
pub next_page_token: Option<String>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GameServerScript {
// empty
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub enum UserRestrictionModerator {
RobloxUser(String),
GameServerScript(GameServerScript),
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UserRestrictionLog {
pub user: String,
pub place: String,
pub create_time: String,
pub active: bool,
pub start_time: String,
pub duration: String,
pub private_reason: String,
pub display_reason: String,
pub exclude_alt_accounts: bool,
pub moderator: UserRestrictionModerator,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UserRestrictionLogsList {
pub logs: Vec<UserRestrictionLog>,
pub next_page_token: Option<String>,
}
pub struct GetUserRestrictionParams {
pub api_key: String,
pub universe_id: UniverseId,
pub place_id: Option<PlaceId>,
pub user_id: RobloxUserId,
}
pub struct ListUserRestrictionsParams {
pub api_key: String,
pub universe_id: UniverseId,
pub place_id: Option<PlaceId>,
pub max_page_size: Option<u32>,
pub page_token: Option<String>,
pub filter: Option<String>,
}
pub struct ListUserRestrictionLogsParams {
pub api_key: String,
pub universe_id: UniverseId,
pub place_id: Option<PlaceId>,
pub max_page_size: Option<u32>,
pub page_token: Option<String>,
pub filter: Option<String>,
}
pub async fn get_user_restriction(
params: &GetUserRestrictionParams,
) -> Result<UserRestriction, Error> {
let client = reqwest::Client::new();
let url = if let Some(place_id) = params.place_id {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/places/{placeId}/user-restrictions/{user}",
universeId = ¶ms.universe_id,
placeId = &place_id,
user = ¶ms.user_id,
)
} else {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/user-restrictions/{user}",
universeId = ¶ms.universe_id,
user = ¶ms.user_id,
)
};
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<UserRestriction>().await?;
Ok(body)
}
pub async fn list_user_restrictions(
params: &ListUserRestrictionsParams,
) -> Result<UserRestrictionList, Error> {
let client = reqwest::Client::new();
let url = if let Some(place_id) = params.place_id {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/places/{placeId}/user-restrictions",
universeId = ¶ms.universe_id,
placeId = &place_id,
)
} else {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/user-restrictions",
universeId = ¶ms.universe_id,
)
};
let mut query: QueryString = vec![];
if let Some(max_page_size) = ¶ms.max_page_size {
query.push(("maxPageSize", max_page_size.to_string()));
}
if let Some(page_token) = ¶ms.page_token {
query.push(("pageToken", page_token.to_string()));
}
if let Some(filter) = ¶ms.filter {
query.push(("filter", filter.to_string()));
}
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<UserRestrictionList>().await?;
Ok(body)
}
pub async fn update_user_restriction(
params: &UpdateUserRestrictionParams,
) -> Result<UserRestriction, Error> {
let client = reqwest::Client::new();
let url = if let Some(place_id) = params.place_id {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/places/{placeId}/user-restrictions/{user}",
universeId = ¶ms.universe_id,
placeId = &place_id,
user = ¶ms.user_id,
)
} else {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/user-restrictions/{user}",
universeId = ¶ms.universe_id,
user = ¶ms.user_id,
)
};
let timestamp = Utc::now();
let mut query: QueryString = vec![("updateMask", "gameJoinRestriction".to_string())];
if let Some(idempotency_key) = ¶ms.idempotency_key {
query.push(("idempotencyKey.key", idempotency_key.to_string()));
query.push((
"idempotencyKey.firstSent",
timestamp.to_rfc3339_opts(SecondsFormat::Millis, true),
));
}
let body = serde_json::to_string(&UpdateUserRestriction {
game_join_restriction: GameJoinRestriction {
active: params.active.unwrap_or(false),
start_time: Some(timestamp),
duration: params.duration.clone(),
private_reason: params.private_reason.clone().unwrap_or("".into()),
display_reason: params.display_reason.clone().unwrap_or("".into()),
exclude_alt_accounts: params.exclude_alt_accounts.unwrap_or(false),
inherited: false,
},
})?;
let res = client
.patch(url)
.header("x-api-key", ¶ms.api_key)
.header("Content-Type", "application/json")
.query(&query)
.body(body)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<UserRestriction>().await?;
Ok(body)
}
pub async fn list_user_restriction_logs(
params: &ListUserRestrictionLogsParams,
) -> Result<UserRestrictionLogsList, Error> {
let client = reqwest::Client::new();
let url = if let Some(place_id) = params.place_id {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/places/{placeId}/user-restrictions:listLogs",
universeId = ¶ms.universe_id,
placeId = &place_id,
)
} else {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/user-restrictions:listLogs",
universeId = ¶ms.universe_id,
)
};
let mut query: QueryString = vec![];
if let Some(max_page_size) = ¶ms.max_page_size {
query.push(("maxPageSize", max_page_size.to_string()));
}
if let Some(page_token) = ¶ms.page_token {
query.push(("pageToken", page_token.to_string()));
}
if let Some(filter) = ¶ms.filter {
query.push(("filter", filter.to_string()));
}
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<UserRestrictionLogsList>().await?;
Ok(body)
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v2/subscription.rs | src/rbx/v2/subscription.rs | use serde::{Deserialize, Serialize};
use crate::rbx::{error::Error, types::UniverseId, util::QueryString};
use super::http_err::handle_http_err;
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum SubscriptionView {
Basic,
Full,
}
impl std::fmt::Display for SubscriptionView {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(
f,
"{:?}",
match self {
Self::Basic => "BASIC",
Self::Full => "FULL",
}
)
}
}
pub struct GetSubscriptionParams {
pub api_key: String,
pub universe_id: UniverseId,
pub subscription_product: String,
pub subscription: String,
pub view: Option<SubscriptionView>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GetSubscriptionResponse {
path: String,
create_time: String,
update_time: String,
active: bool,
will_renew: bool,
last_billing_time: String,
next_renew_time: String,
expire_time: String,
state: SubscriptionState,
expiration_details: SubscriptionExpirationDetails,
purchase_platform: SubscriptionPurchasePlatform,
payment_provider: SubscriptionPaymentProvider,
user: String,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SubscriptionExpirationDetails {
reason: SubscriptionExpirationReason,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SubscriptionState {
StateUnspecified,
SubscribedWillRenew,
SubscribedWillNotRenew,
SubscribedRenewalPaymentPending,
Expired,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SubscriptionExpirationReason {
ExpirationReasonUnspecified,
ProductInactive,
ProductDeleted,
SubscriberCancelled,
SubscriberRefunded,
Lapsed,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SubscriptionPurchasePlatform {
PurchasePlatformUnspecified,
Desktop,
Mobile,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SubscriptionPaymentProvider {
PaymentProviderUnspecified,
Stripe,
Apple,
Google,
RobloxCredit,
}
pub async fn get_subscription(
params: &GetSubscriptionParams,
) -> Result<GetSubscriptionResponse, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/subscription-products/{subscription}",
universeId = ¶ms.universe_id,
subscription = ¶ms.subscription_product,
);
let mut query: QueryString = vec![];
if let Some(view) = ¶ms.view {
query.push(("view", view.to_string()));
}
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<GetSubscriptionResponse>().await?;
Ok(body)
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v2/mod.rs | src/rbx/v2/mod.rs | //! Access into Roblox v2 APIs.
//!
//! Most usage should go through the `Client` struct.
use inventory::{InventoryItems, ListInventoryItemsParams};
use luau_execution::{
CreateLuauExecutionTaskParams, GetLuauExecutionSessionTaskLogsParams,
GetLuauExecutionSessionTaskParams, LuauExecutionSessionTask, LuauExecutionSessionTaskLogPage,
LuauExecutionTaskLogView, NewLuauExecutionSessionTask,
};
use place::{GetPlaceParams, PlaceInfo, UpdatePlaceInfo, UpdatePlaceParams};
use rand::{distr::Alphanumeric, Rng};
use universe::{
GetUniverseParams, RestartUniverseServersParams, UniverseInfo, UpdateUniverseInfo,
UpdateUniverseParams,
};
use user::{
GenerateUserThumbnailOperationResponse, GenerateUserThumbnailParams, GetUserParams,
GetUserResponse, UserThumbnailFormat, UserThumbnailShape, UserThumbnailSize,
};
use user_restriction::{
GetUserRestrictionParams, ListUserRestrictionLogsParams, ListUserRestrictionsParams,
UpdateUserRestrictionParams, UserRestriction, UserRestrictionList, UserRestrictionLogsList,
};
use self::{
group::{
GetGroupParams, GetGroupResponse, GetGroupShoutParams, GetGroupShoutResponse,
ListGroupMembershipsParams, ListGroupMembershipsResponse, ListGroupRolesParams,
ListGroupRolesResponse,
},
notification::{Notification, NotificationParams, NotificationResponse},
subscription::{GetSubscriptionParams, GetSubscriptionResponse, SubscriptionView},
};
pub mod group;
pub(crate) mod http_err;
pub mod inventory;
pub mod luau_execution;
pub mod notification;
pub mod place;
pub mod subscription;
pub mod universe;
pub mod user;
pub mod user_restriction;
use crate::rbx::error::Error;
use super::types::{GroupId, PlaceId, RobloxUserId, UniverseId};
/// Access into the Roblox Open Cloud APIs.
///
/// ```rust,no_run
/// use rbxcloud::rbx::v2::Client;
///
/// let client = Client::new("API_KEY");
/// ```
#[derive(Debug)]
pub struct Client {
/// Roblox API key.
pub api_key: String,
}
pub struct GroupClient {
pub api_key: String,
pub group_id: GroupId,
}
pub struct InventoryClient {
pub api_key: String,
}
pub struct LuauExecutionClient {
pub api_key: String,
pub universe_id: UniverseId,
pub place_id: PlaceId,
pub version_id: Option<String>,
}
pub struct SubscriptionClient {
pub api_key: String,
}
pub struct NotificationClient {
pub api_key: String,
pub universe_id: UniverseId,
}
pub struct PlaceClient {
pub api_key: String,
pub universe_id: UniverseId,
pub place_id: PlaceId,
}
pub struct UniverseClient {
pub api_key: String,
pub universe_id: UniverseId,
}
pub struct UserClient {
pub api_key: String,
}
pub struct UserRestrictionClient {
pub api_key: String,
pub universe_id: UniverseId,
}
pub struct UserRestrictionParams {
pub user_id: RobloxUserId,
pub place_id: Option<PlaceId>,
pub active: Option<bool>,
pub duration: Option<u64>,
pub private_reason: Option<String>,
pub display_reason: Option<String>,
pub exclude_alt_accounts: Option<bool>,
}
impl GroupClient {
pub async fn get_info(&self) -> Result<GetGroupResponse, Error> {
group::get_group(&GetGroupParams {
api_key: self.api_key.clone(),
group_id: self.group_id,
})
.await
}
pub async fn get_shout(&self) -> Result<GetGroupShoutResponse, Error> {
group::get_group_shout(&GetGroupShoutParams {
api_key: self.api_key.clone(),
group_id: self.group_id,
})
.await
}
pub async fn list_roles(
&self,
max_page_size: Option<u32>,
page_token: Option<String>,
) -> Result<ListGroupRolesResponse, Error> {
group::list_group_roles(&ListGroupRolesParams {
api_key: self.api_key.clone(),
group_id: self.group_id,
max_page_size,
page_token,
})
.await
}
pub async fn list_memberships(
&self,
max_page_size: Option<u32>,
filter: Option<String>,
page_token: Option<String>,
) -> Result<ListGroupMembershipsResponse, Error> {
group::list_group_memberships(&ListGroupMembershipsParams {
api_key: self.api_key.clone(),
group_id: self.group_id,
max_page_size,
page_token,
filter,
})
.await
}
}
impl InventoryClient {
pub async fn list_inventory_items(
&self,
user_id: RobloxUserId,
max_page_size: Option<u32>,
page_token: Option<String>,
filter: Option<String>,
) -> Result<InventoryItems, Error> {
inventory::list_inventory_items(&ListInventoryItemsParams {
api_key: self.api_key.clone(),
user_id,
max_page_size,
page_token,
filter,
})
.await
}
}
impl LuauExecutionClient {
pub async fn create_task(
&self,
script: String,
timeout: Option<String>,
) -> Result<NewLuauExecutionSessionTask, Error> {
luau_execution::create_luau_execution_task(&CreateLuauExecutionTaskParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
place_id: self.place_id,
version_id: self.version_id.clone(),
script,
timeout,
})
.await
}
pub async fn get_task(
&self,
session_id: String,
task_id: String,
) -> Result<LuauExecutionSessionTask, Error> {
luau_execution::get_luau_execution_task(&GetLuauExecutionSessionTaskParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
place_id: self.place_id,
version_id: self.version_id.clone(),
session_id,
task_id,
})
.await
}
pub async fn get_logs(
&self,
session_id: String,
task_id: String,
view: LuauExecutionTaskLogView,
max_page_size: Option<u32>,
page_token: Option<String>,
) -> Result<LuauExecutionSessionTaskLogPage, Error> {
luau_execution::get_luau_execution_task_logs(&GetLuauExecutionSessionTaskLogsParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
place_id: self.place_id,
version_id: self.version_id.clone(),
session_id,
task_id,
view,
max_page_size,
page_token,
})
.await
}
}
impl SubscriptionClient {
pub async fn get(
&self,
universe_id: UniverseId,
subscription_product: String,
subscription: String,
view: Option<SubscriptionView>,
) -> Result<GetSubscriptionResponse, Error> {
subscription::get_subscription(&GetSubscriptionParams {
api_key: self.api_key.clone(),
universe_id,
subscription,
subscription_product,
view,
})
.await
}
}
impl NotificationClient {
pub async fn send(
&self,
user_id: RobloxUserId,
notification: Notification,
) -> Result<NotificationResponse, Error> {
notification::send_notification(&NotificationParams {
api_key: self.api_key.clone(),
user_id,
notification,
})
.await
}
}
impl PlaceClient {
pub async fn get(&self) -> Result<PlaceInfo, Error> {
place::get_place(&GetPlaceParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
place_id: self.place_id,
})
.await
}
pub async fn update(
&self,
update_mask: String,
info: UpdatePlaceInfo,
) -> Result<PlaceInfo, Error> {
place::update_place(&UpdatePlaceParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
place_id: self.place_id,
update_mask,
info,
})
.await
}
}
impl UniverseClient {
pub async fn get(&self) -> Result<UniverseInfo, Error> {
universe::get_universe(&GetUniverseParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
})
.await
}
pub async fn update(
&self,
update_mask: String,
info: UpdateUniverseInfo,
) -> Result<UniverseInfo, Error> {
universe::update_universe(&UpdateUniverseParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
update_mask,
info,
})
.await
}
pub async fn restart_servers(&self) -> Result<(), Error> {
universe::restart_universe_servers(&RestartUniverseServersParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
})
.await
}
}
impl UserClient {
pub async fn get_user(&self, user_id: RobloxUserId) -> Result<GetUserResponse, Error> {
user::get_user(&GetUserParams {
api_key: self.api_key.clone(),
user_id,
})
.await
}
pub async fn generate_thumbnail(
&self,
user_id: RobloxUserId,
size: Option<UserThumbnailSize>,
format: Option<UserThumbnailFormat>,
shape: Option<UserThumbnailShape>,
) -> Result<GenerateUserThumbnailOperationResponse, Error> {
user::generate_thumbnail(&GenerateUserThumbnailParams {
api_key: self.api_key.clone(),
user_id,
size,
shape,
format,
})
.await
}
}
impl UserRestrictionClient {
pub async fn list_user_restrictions(
&self,
place_id: Option<PlaceId>,
max_page_size: Option<u32>,
filter: Option<String>,
page_token: Option<String>,
) -> Result<UserRestrictionList, Error> {
user_restriction::list_user_restrictions(&ListUserRestrictionsParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
place_id,
max_page_size,
page_token,
filter,
})
.await
}
pub async fn get_user_restriction(
&self,
user_id: RobloxUserId,
place_id: Option<PlaceId>,
) -> Result<UserRestriction, Error> {
user_restriction::get_user_restriction(&GetUserRestrictionParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
place_id,
user_id,
})
.await
}
pub async fn update_user_restriction(
&mut self,
params: &UserRestrictionParams,
) -> Result<UserRestriction, Error> {
let idempotency_key: String = rand::rng()
.sample_iter(&Alphanumeric)
.take(32)
.map(char::from)
.collect();
user_restriction::update_user_restriction(&UpdateUserRestrictionParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
place_id: params.place_id,
user_id: params.user_id,
idempotency_key: Some(idempotency_key),
active: params.active,
duration: params.duration.and_then(|d| Some(format!("{}s", d))),
private_reason: params.private_reason.clone(),
display_reason: params.display_reason.clone(),
exclude_alt_accounts: params.exclude_alt_accounts,
})
.await
}
pub async fn list_user_restriction_logs(
&self,
place_id: Option<PlaceId>,
max_page_size: Option<u32>,
page_token: Option<String>,
filter: Option<String>,
) -> Result<UserRestrictionLogsList, Error> {
user_restriction::list_user_restriction_logs(&ListUserRestrictionLogsParams {
api_key: self.api_key.clone(),
universe_id: self.universe_id,
place_id,
max_page_size,
page_token,
filter,
})
.await
}
}
impl Client {
pub fn new(api_key: &str) -> Client {
Client {
api_key: api_key.to_string(),
}
}
pub fn group(&self, group_id: GroupId) -> GroupClient {
GroupClient {
api_key: self.api_key.clone(),
group_id,
}
}
pub fn inventory(&self) -> InventoryClient {
InventoryClient {
api_key: self.api_key.clone(),
}
}
pub fn luau(
&self,
universe_id: UniverseId,
place_id: PlaceId,
version_id: Option<String>,
) -> LuauExecutionClient {
LuauExecutionClient {
api_key: self.api_key.clone(),
universe_id,
place_id,
version_id,
}
}
pub fn subscription(&self) -> SubscriptionClient {
SubscriptionClient {
api_key: self.api_key.clone(),
}
}
pub fn notification(&self, universe_id: UniverseId) -> NotificationClient {
NotificationClient {
api_key: self.api_key.clone(),
universe_id,
}
}
pub fn place(&self, universe_id: UniverseId, place_id: PlaceId) -> PlaceClient {
PlaceClient {
api_key: self.api_key.clone(),
universe_id,
place_id,
}
}
pub fn universe(&self, universe_id: UniverseId) -> UniverseClient {
UniverseClient {
api_key: self.api_key.clone(),
universe_id,
}
}
pub fn user(&self) -> UserClient {
UserClient {
api_key: self.api_key.clone(),
}
}
pub fn user_restriction(&self, universe_id: UniverseId) -> UserRestrictionClient {
UserRestrictionClient {
api_key: self.api_key.clone(),
universe_id,
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v2/universe.rs | src/rbx/v2/universe.rs | use serde::{Deserialize, Serialize};
use crate::rbx::{error::Error, types::UniverseId, util::QueryString};
use super::http_err::handle_http_err;
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UniverseVisibility {
VisibilityUnspecified,
Public,
Private,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UniverseAgeRating {
AgeRatingUnspecified,
AgeRatingAll,
AgeRating9Plus,
AgeRating13Plus,
AgeRating17Plus,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UniverseSocialLink {
pub title: String,
pub uri: String,
}
pub struct GetUniverseParams {
pub api_key: String,
pub universe_id: UniverseId,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UniverseInfo {
pub path: String,
pub create_time: String,
pub update_time: String,
pub display_name: String,
pub description: String,
pub user: Option<String>,
pub group: Option<String>,
pub visibility: UniverseVisibility,
pub facebook_social_link: Option<UniverseSocialLink>,
pub twitter_social_link: Option<UniverseSocialLink>,
pub youtube_social_link: Option<UniverseSocialLink>,
pub twitch_social_link: Option<UniverseSocialLink>,
pub discord_social_link: Option<UniverseSocialLink>,
pub roblox_group_social_link: Option<UniverseSocialLink>,
pub guilded_social_link: Option<UniverseSocialLink>,
pub voice_chat_enabled: bool,
pub age_rating: UniverseAgeRating,
pub private_server_price_robux: u32,
pub desktop_enabled: bool,
pub mobile_enabled: bool,
pub tablet_enabled: bool,
pub console_enabled: bool,
pub vr_enabled: bool,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UpdateUniverseInfo {
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub create_time: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub update_time: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub user: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub group: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub visibility: Option<UniverseVisibility>,
#[serde(skip_serializing_if = "Option::is_none")]
pub facebook_social_link: Option<UniverseSocialLink>,
#[serde(skip_serializing_if = "Option::is_none")]
pub twitter_social_link: Option<UniverseSocialLink>,
#[serde(skip_serializing_if = "Option::is_none")]
pub youtube_social_link: Option<UniverseSocialLink>,
#[serde(skip_serializing_if = "Option::is_none")]
pub twitch_social_link: Option<UniverseSocialLink>,
#[serde(skip_serializing_if = "Option::is_none")]
pub discord_social_link: Option<UniverseSocialLink>,
#[serde(skip_serializing_if = "Option::is_none")]
pub roblox_group_social_link: Option<UniverseSocialLink>,
#[serde(skip_serializing_if = "Option::is_none")]
pub guilded_social_link: Option<UniverseSocialLink>,
#[serde(skip_serializing_if = "Option::is_none")]
pub voice_chat_enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub age_rating: Option<UniverseAgeRating>,
#[serde(skip_serializing_if = "Option::is_none")]
pub private_server_price_robux: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub desktop_enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mobile_enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tablet_enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub console_enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub vr_enabled: Option<bool>,
}
pub struct UpdateUniverseParams {
pub api_key: String,
pub universe_id: UniverseId,
pub update_mask: String,
pub info: UpdateUniverseInfo,
}
pub struct RestartUniverseServersParams {
pub api_key: String,
pub universe_id: UniverseId,
}
pub async fn get_universe(params: &GetUniverseParams) -> Result<UniverseInfo, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}",
universeId = ¶ms.universe_id,
);
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<UniverseInfo>().await?;
Ok(body)
}
pub async fn update_universe(params: &UpdateUniverseParams) -> Result<UniverseInfo, Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}",
universeId = ¶ms.universe_id,
);
let query: QueryString = vec![("updateMask", params.update_mask.clone())];
let body = serde_json::to_string(¶ms.info)?;
println!("body: {}", body);
let res = client
.patch(url)
.header("x-api-key", ¶ms.api_key)
.header("Content-Type", "application/json")
.body(body)
.query(&query)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<UniverseInfo>().await?;
Ok(body)
}
pub async fn restart_universe_servers(params: &RestartUniverseServersParams) -> Result<(), Error> {
let client = reqwest::Client::new();
let url = format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}:restartServers",
universeId = ¶ms.universe_id,
);
let body = "{}";
let res = client
.post(url)
.header("x-api-key", ¶ms.api_key)
.header("Content-Type", "application/json")
.body(body)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
Ok(())
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v2/luau_execution.rs | src/rbx/v2/luau_execution.rs | use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::rbx::{
error::Error,
types::{PlaceId, UniverseId},
util::QueryString,
};
use super::http_err::handle_http_err;
#[derive(Debug)]
pub struct CreateLuauExecutionTaskParams {
pub api_key: String,
pub universe_id: UniverseId,
pub place_id: PlaceId,
pub version_id: Option<String>,
pub script: String,
pub timeout: Option<String>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct NewLuauExecutionSessionTask {
pub path: String,
pub user: String,
pub state: LuauExecutionState,
pub script: String,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GetLuauExecutionSessionTaskParams {
pub api_key: String,
pub universe_id: UniverseId,
pub place_id: PlaceId,
pub version_id: Option<String>,
pub session_id: String,
pub task_id: String,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GetLuauExecutionSessionTaskLogsParams {
pub api_key: String,
pub universe_id: UniverseId,
pub place_id: PlaceId,
pub version_id: Option<String>,
pub session_id: String,
pub task_id: String,
pub max_page_size: Option<u32>,
pub page_token: Option<String>,
pub view: LuauExecutionTaskLogView,
}
#[derive(Debug, Clone, Copy, clap::ValueEnum, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LuauExecutionTaskLogView {
Flat,
Structured,
}
impl std::fmt::Display for LuauExecutionTaskLogView {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(
f,
"{}",
match self {
Self::Flat => "FLAT",
Self::Structured => "STRUCTURED",
}
)
}
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct LuauExecutionSessionTaskLogPage {
pub luau_execution_session_task_logs: Vec<LuauExecutionSessionTaskLog>,
pub next_page_token: String,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct LuauExecutionSessionTaskLog {
pub path: String,
pub messages: Vec<String>,
pub structured_messages: Vec<StructuredMessage>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct StructuredMessage {
pub message: String,
pub create_time: String,
pub message_type: String,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct LuauExecutionSessionTask {
pub path: String,
pub create_time: String,
pub update_time: String,
pub user: String,
pub state: LuauExecutionState,
pub output: LuauExecutionOutput,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct LuauExecutionOutput {
pub results: Vec<Value>,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LuauExecutionState {
StateUnspecified,
Queued,
Processing,
Cancelled,
Complete,
Failed,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct LuauExecutionInput {
pub script: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout: Option<String>,
}
pub async fn create_luau_execution_task(
params: &CreateLuauExecutionTaskParams,
) -> Result<NewLuauExecutionSessionTask, Error> {
let client = reqwest::Client::new();
let url = if let Some(version_id) = ¶ms.version_id {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/places/{placeId}/versions/{versionId}/luau-execution-session-tasks",
universeId = ¶ms.universe_id,
placeId = ¶ms.place_id,
versionId = version_id,
)
} else {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/places/{placeId}/luau-execution-session-tasks",
universeId = ¶ms.universe_id,
placeId = ¶ms.place_id,
)
};
let input = LuauExecutionInput {
script: params.script.clone(),
timeout: params.timeout.clone(),
};
let req_body = serde_json::to_string(&input)?;
let res = client
.post(url)
.header("x-api-key", ¶ms.api_key)
.header("Content-Type", "application/json")
.body(req_body)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<NewLuauExecutionSessionTask>().await?;
Ok(body)
}
pub async fn get_luau_execution_task(
params: &GetLuauExecutionSessionTaskParams,
) -> Result<LuauExecutionSessionTask, Error> {
let client = reqwest::Client::new();
let url = if let Some(version_id) = ¶ms.version_id {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/places/{placeId}/versions/{versionId}/luau-execution-sessions/{sessionId}/tasks/{taskId}",
universeId = ¶ms.universe_id,
placeId = ¶ms.place_id,
versionId = version_id,
sessionId = ¶ms.session_id,
taskId = ¶ms.task_id,
)
} else {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/places/{placeId}/luau-execution-sessions/{sessionId}/tasks/{taskId}",
universeId = ¶ms.universe_id,
placeId = ¶ms.place_id,
sessionId = ¶ms.session_id,
taskId = ¶ms.task_id,
)
};
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<LuauExecutionSessionTask>().await?;
Ok(body)
}
pub async fn get_luau_execution_task_logs(
params: &GetLuauExecutionSessionTaskLogsParams,
) -> Result<LuauExecutionSessionTaskLogPage, Error> {
let client = reqwest::Client::new();
let url = if let Some(version_id) = ¶ms.version_id {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/places/{placeId}/versions/{versionId}/luau-execution-sessions/{sessionId}/tasks/{taskId}/logs",
universeId = ¶ms.universe_id,
placeId = ¶ms.place_id,
versionId = version_id,
sessionId = ¶ms.session_id,
taskId = ¶ms.task_id,
)
} else {
format!(
"https://apis.roblox.com/cloud/v2/universes/{universeId}/places/{placeId}/luau-execution-sessions/{sessionId}/tasks/{taskId}/logs",
universeId = ¶ms.universe_id,
placeId = ¶ms.place_id,
sessionId = ¶ms.session_id,
taskId = ¶ms.task_id,
)
};
let mut query: QueryString = vec![("view", params.view.to_string())];
if let Some(max_page_size) = params.max_page_size {
query.push(("maxPageSize", format!("{max_page_size}")));
}
if let Some(page_token) = ¶ms.page_token {
query.push(("pageToken", page_token.clone()));
}
let res = client
.get(url)
.header("x-api-key", ¶ms.api_key)
.query(&query)
.send()
.await?;
let status = res.status();
if !status.is_success() {
let code = status.as_u16();
return handle_http_err(code);
}
let body = res.json::<LuauExecutionSessionTaskLogPage>().await?;
Ok(body)
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/rbx/v2/http_err.rs | src/rbx/v2/http_err.rs | use crate::rbx::error::Error;
pub fn handle_http_err<T>(code: u16) -> Result<T, Error> {
match code {
400 => Err(Error::HttpStatusError {
code,
msg: "invalid argument".to_string(),
}),
403 => Err(Error::HttpStatusError {
code,
msg: "permission denied".to_string(),
}),
404 => Err(Error::HttpStatusError {
code,
msg: "not found".to_string(),
}),
409 => Err(Error::HttpStatusError {
code,
msg: "aborted".to_string(),
}),
429 => Err(Error::HttpStatusError {
code,
msg: "resource exhausted".to_string(),
}),
499 => Err(Error::HttpStatusError {
code,
msg: "cancelled".to_string(),
}),
500 => Err(Error::HttpStatusError {
code,
msg: "internal server error".to_string(),
}),
501 => Err(Error::HttpStatusError {
code,
msg: "not implemented".to_string(),
}),
503 => Err(Error::HttpStatusError {
code,
msg: "unavailable".to_string(),
}),
_ => Err(Error::HttpStatusError {
code,
msg: "unknown error".to_string(),
}),
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/notification_cli.rs | src/cli/notification_cli.rs | use clap::{Args, Subcommand};
use rbxcloud::rbx::{
types::{RobloxUserId, UniverseId},
v2::Client,
};
#[derive(Debug, Subcommand)]
pub enum NotificationCommands {
/// Send a notification to a user
Send {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// User ID
#[clap(short = 'U', long, value_parser)]
user_id: u64,
/// Payload
#[clap(short = 'P', long, value_parser)]
payload: String,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Args)]
pub struct Notification {
#[clap(subcommand)]
command: NotificationCommands,
}
impl Notification {
pub async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
NotificationCommands::Send {
universe_id,
user_id,
payload,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let notification_client = client.notification(UniverseId(universe_id));
let notification = serde_json::from_str::<
rbxcloud::rbx::v2::notification::Notification,
>(&payload)?;
let res = notification_client
.send(RobloxUserId(user_id), notification)
.await;
match res {
Ok(subscription_info) => {
let r = if pretty {
serde_json::to_string_pretty(&subscription_info)?
} else {
serde_json::to_string(&subscription_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/group_cli.rs | src/cli/group_cli.rs | use clap::{Args, Subcommand};
use rbxcloud::rbx::{types::GroupId, v2::Client};
#[derive(Debug, Subcommand)]
pub enum GroupCommands {
/// Get info about the group
Get {
/// Group ID
#[clap(short, long, value_parser)]
group_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Get the current shout and other metadata
Shout {
/// Group ID
#[clap(short, long, value_parser)]
group_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Only return the shout message string
#[clap(short, long, value_parser, default_value_t = false)]
only_message: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// List the roles of a group
Roles {
/// Group ID
#[clap(short, long, value_parser)]
group_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Max items returned per page
#[clap(short, long, value_parser)]
max_page_size: Option<u32>,
/// Next page token
#[clap(short, long, value_parser)]
next_page_token: Option<String>,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// List the memberships of a group
Memberships {
/// Group ID
#[clap(short, long, value_parser)]
group_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Max items returned per page
#[clap(short, long, value_parser)]
max_page_size: Option<u32>,
/// Filter
#[clap(short, long, value_parser)]
filter: Option<String>,
/// Next page token
#[clap(short, long, value_parser)]
next_page_token: Option<String>,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Args)]
pub struct Group {
#[clap(subcommand)]
command: GroupCommands,
}
impl Group {
pub async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
GroupCommands::Get {
group_id,
api_key,
pretty,
} => {
let client = Client::new(&api_key);
let group = client.group(GroupId(group_id));
let res = group.get_info().await;
match res {
Ok(group_info) => {
let r = if pretty {
serde_json::to_string_pretty(&group_info)?
} else {
serde_json::to_string(&group_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
GroupCommands::Shout {
group_id,
pretty,
only_message,
api_key,
} => {
let client = Client::new(&api_key);
let group = client.group(GroupId(group_id));
let res = group.get_shout().await;
match res {
Ok(group_info) => {
if only_message {
return Ok(Some(group_info.content));
}
let r = if pretty {
serde_json::to_string_pretty(&group_info)?
} else {
serde_json::to_string(&group_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
GroupCommands::Roles {
group_id,
api_key,
pretty,
max_page_size,
next_page_token,
} => {
let client = Client::new(&api_key);
let group = client.group(GroupId(group_id));
let res = group.list_roles(max_page_size, next_page_token).await;
match res {
Ok(group_info) => {
let r = if pretty {
serde_json::to_string_pretty(&group_info)?
} else {
serde_json::to_string(&group_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
GroupCommands::Memberships {
group_id,
api_key,
pretty,
max_page_size,
next_page_token,
filter,
} => {
let client = Client::new(&api_key);
let group = client.group(GroupId(group_id));
let res = group
.list_memberships(max_page_size, filter, next_page_token)
.await;
match res {
Ok(group_info) => {
let r = if pretty {
serde_json::to_string_pretty(&group_info)?
} else {
serde_json::to_string(&group_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/place_cli.rs | src/cli/place_cli.rs | use clap::{Args, Subcommand};
use rbxcloud::rbx::{
types::{PlaceId, UniverseId},
v2::{place::UpdatePlaceInfo, Client},
};
#[derive(Debug, Subcommand)]
pub enum PlaceCommands {
/// Get Place information
Get {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// Place ID
#[clap(short, long, value_parser)]
place_id: u64,
/// Pretty-print the JSON response
#[clap(long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Update Place name
UpdateName {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// Place ID
#[clap(short, long, value_parser)]
place_id: u64,
/// New Place name
#[clap(short, long, value_parser)]
name: String,
/// Pretty-print the JSON response
#[clap(long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Update Place description
UpdateDescription {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// Place ID
#[clap(short, long, value_parser)]
place_id: u64,
/// New Place description
#[clap(short, long, value_parser)]
description: String,
/// Pretty-print the JSON response
#[clap(long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Update Place server size
UpdateServerSize {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// Place ID
#[clap(short, long, value_parser)]
place_id: u64,
/// New Place server size
#[clap(short, long, value_parser)]
server_size: u32,
/// Pretty-print the JSON response
#[clap(long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Args)]
pub struct Place {
#[clap(subcommand)]
command: PlaceCommands,
}
impl Place {
pub async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
PlaceCommands::Get {
universe_id,
place_id,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let place_client = client.place(UniverseId(universe_id), PlaceId(place_id));
let res = place_client.get().await;
match res {
Ok(place_info) => {
let r = if pretty {
serde_json::to_string_pretty(&place_info)?
} else {
serde_json::to_string(&place_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
PlaceCommands::UpdateName {
universe_id,
place_id,
name,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let place_client = client.place(UniverseId(universe_id), PlaceId(place_id));
let res = place_client
.update(
"displayName".to_string(),
UpdatePlaceInfo {
path: None,
create_time: None,
update_time: None,
display_name: Some(name),
description: None,
server_size: None,
},
)
.await;
match res {
Ok(place_info) => {
let r = if pretty {
serde_json::to_string_pretty(&place_info)?
} else {
serde_json::to_string(&place_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
PlaceCommands::UpdateDescription {
universe_id,
place_id,
description,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let place_client = client.place(UniverseId(universe_id), PlaceId(place_id));
let res = place_client
.update(
"description".to_string(),
UpdatePlaceInfo {
path: None,
create_time: None,
update_time: None,
display_name: None,
description: Some(description),
server_size: None,
},
)
.await;
match res {
Ok(place_info) => {
let r = if pretty {
serde_json::to_string_pretty(&place_info)?
} else {
serde_json::to_string(&place_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
PlaceCommands::UpdateServerSize {
universe_id,
place_id,
server_size,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let place_client = client.place(UniverseId(universe_id), PlaceId(place_id));
let res = place_client
.update(
"serverSize".to_string(),
UpdatePlaceInfo {
path: None,
create_time: None,
update_time: None,
display_name: None,
description: None,
server_size: Some(server_size),
},
)
.await;
match res {
Ok(place_info) => {
let r = if pretty {
serde_json::to_string_pretty(&place_info)?
} else {
serde_json::to_string(&place_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/luau_execution_cli.rs | src/cli/luau_execution_cli.rs | use clap::{Args, Subcommand};
use rbxcloud::rbx::{
types::{PlaceId, UniverseId},
v2::{luau_execution::LuauExecutionTaskLogView, Client},
};
use tokio::fs;
#[derive(Debug, Subcommand)]
pub enum LuauExecutionCommands {
/// Executes Luau code on Roblox
Execute {
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Place ID of the experience
#[clap(short = 'i', long, value_parser)]
place_id: u64,
/// Version ID of the experience
#[clap(short = 'r', long, value_parser)]
version_id: Option<String>,
/// Script source code
#[clap(short, long, value_parser)]
script: Option<String>,
/// Script source code file
#[clap(short, long, value_parser)]
filepath: Option<String>,
/// Execution timeout
#[clap(short, long, value_parser)]
timeout: Option<String>,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Gets information on a previously executed task
GetTask {
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Place ID of the experience
#[clap(short = 'i', long, value_parser)]
place_id: u64,
/// Version ID of the experience
#[clap(short = 'r', long, value_parser)]
version_id: Option<String>,
/// Luau execution session ID
#[clap(short, long, value_parser)]
session_id: String,
/// Luau execution task ID
#[clap(short, long, value_parser)]
task_id: String,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Retrieves logs on a previously executed task
GetLogs {
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Place ID of the experience
#[clap(short = 'i', long, value_parser)]
place_id: u64,
/// Version ID of the experience
#[clap(short = 'r', long, value_parser)]
version_id: Option<String>,
/// Luau execution session ID
#[clap(short, long, value_parser)]
session_id: String,
/// Luau execution task ID
#[clap(short, long, value_parser)]
task_id: String,
/// Max page size
#[clap(short, long, value_parser)]
max_page_size: Option<u32>,
/// Next page token
#[clap(short = 'n', long, value_parser)]
page_token: Option<String>,
/// Log view type
#[clap(short = 'w', long, value_enum)]
view: Option<LuauExecutionTaskLogView>,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Args)]
pub struct Luau {
#[clap(subcommand)]
command: LuauExecutionCommands,
}
impl Luau {
pub async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
LuauExecutionCommands::Execute {
universe_id,
place_id,
version_id,
script,
filepath,
timeout,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let luau = client.luau(UniverseId(universe_id), PlaceId(place_id), version_id);
let mut script_source: Option<String> = None;
if script.is_some() {
script_source = script;
}
if script_source.is_none() {
if let Some(path) = filepath {
let src_bytes = fs::read(path).await?;
script_source = Some(String::from_utf8(src_bytes)?);
}
}
let src = script_source.expect("script or filepath must be set");
let res = luau.create_task(src, timeout).await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
LuauExecutionCommands::GetTask {
universe_id,
place_id,
version_id,
session_id,
task_id,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let luau = client.luau(UniverseId(universe_id), PlaceId(place_id), version_id);
let res = luau.get_task(session_id, task_id).await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
LuauExecutionCommands::GetLogs {
universe_id,
place_id,
version_id,
session_id,
task_id,
max_page_size,
page_token,
view,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let luau = client.luau(UniverseId(universe_id), PlaceId(place_id), version_id);
let res = luau
.get_logs(
session_id,
task_id,
view.unwrap_or(LuauExecutionTaskLogView::Flat),
max_page_size,
page_token,
)
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/ordered_datastore_cli.rs | src/cli/ordered_datastore_cli.rs | use clap::{Args, Subcommand};
use rbxcloud::rbx::{
types::UniverseId,
v1::{
OrderedDataStoreCreateEntry, OrderedDataStoreEntry, OrderedDataStoreIncrementEntry,
OrderedDataStoreListEntries, OrderedDataStoreUpdateEntry, RbxCloud,
},
};
#[derive(Debug, Subcommand)]
pub enum OrderedDataStoreCommands {
/// List entries
List {
/// DataStore name
#[clap(short, long, value_parser)]
datastore_name: String,
/// DataStore scope
#[clap(short, long, value_parser)]
scope: Option<String>,
/// Maximum number of items to return per page
#[clap(short, long, value_parser)]
max_page_size: Option<u64>,
/// Cursor for the next set of data
#[clap(short = 't', long, value_parser)]
page_token: Option<String>,
/// The enumeration direction (Use 'desc' for descending)
#[clap(short, long, value_parser)]
order_by: Option<String>,
/// A range of qualifying values of entries to return
#[clap(short, long, value_parser)]
filter: Option<String>,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Create or overwrite an entry
Create {
/// DataStore name
#[clap(short, long, value_parser)]
datastore_name: String,
/// DataStore scope
#[clap(short, long, value_parser)]
scope: Option<String>,
/// The ID of the entry
#[clap(short, long, value_parser)]
id: String,
/// The value of the entry
#[clap(short, long, value_parser)]
value: i64,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Get an entry
Get {
/// DataStore name
#[clap(short, long, value_parser)]
datastore_name: String,
/// DataStore scope
#[clap(short, long, value_parser)]
scope: Option<String>,
/// The ID of the entry
#[clap(short, long, value_parser)]
id: String,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Delete an entry
Delete {
/// DataStore name
#[clap(short, long, value_parser)]
datastore_name: String,
/// DataStore scope
#[clap(short, long, value_parser)]
scope: Option<String>,
/// The ID of the entry
#[clap(short, long, value_parser)]
id: String,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Update an entry
Update {
/// DataStore name
#[clap(short, long, value_parser)]
datastore_name: String,
/// DataStore scope
#[clap(short, long, value_parser)]
scope: Option<String>,
/// The ID of the entry
#[clap(short, long, value_parser)]
id: String,
/// The value of the entry
#[clap(short, long, value_parser)]
value: i64,
/// Create if missing
#[clap(short = 'm', long, value_parser)]
allow_missing: Option<bool>,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Increment an entry
Increment {
/// DataStore name
#[clap(short, long, value_parser)]
datastore_name: String,
/// DataStore scope
#[clap(short, long, value_parser)]
scope: Option<String>,
/// The ID of the entry
#[clap(short, long, value_parser)]
id: String,
/// The incremented value of the entry
#[clap(short = 'n', long, value_parser)]
increment: i64,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Args)]
pub struct OrderedDataStore {
#[clap(subcommand)]
command: OrderedDataStoreCommands,
}
impl OrderedDataStore {
pub async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
OrderedDataStoreCommands::List {
datastore_name,
scope,
max_page_size,
page_token,
order_by,
filter,
universe_id,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let ordered_datastore = rbx_cloud.ordered_datastore(UniverseId(universe_id));
let res = ordered_datastore
.list_entries(&OrderedDataStoreListEntries {
name: datastore_name,
scope,
max_page_size: max_page_size.map(|p| p.into()),
page_token,
order_by,
filter,
})
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(err.into()),
}
}
OrderedDataStoreCommands::Create {
datastore_name,
scope,
id,
value,
universe_id,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let ordered_datastore = rbx_cloud.ordered_datastore(UniverseId(universe_id));
let res = ordered_datastore
.create_entry(&OrderedDataStoreCreateEntry {
name: datastore_name,
scope,
id,
value,
})
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(err.into()),
}
}
OrderedDataStoreCommands::Get {
datastore_name,
scope,
id,
universe_id,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let ordered_datastore = rbx_cloud.ordered_datastore(UniverseId(universe_id));
let res = ordered_datastore
.get_entry(&OrderedDataStoreEntry {
name: datastore_name,
scope,
id,
})
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(err.into()),
}
}
OrderedDataStoreCommands::Delete {
datastore_name,
scope,
id,
universe_id,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let ordered_datastore = rbx_cloud.ordered_datastore(UniverseId(universe_id));
let res = ordered_datastore
.delete_entry(&OrderedDataStoreEntry {
name: datastore_name,
scope,
id,
})
.await;
match res {
Ok(_) => Ok(None),
Err(err) => Err(err.into()),
}
}
OrderedDataStoreCommands::Update {
datastore_name,
scope,
id,
value,
allow_missing,
universe_id,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let ordered_datastore = rbx_cloud.ordered_datastore(UniverseId(universe_id));
let res = ordered_datastore
.update_entry(&OrderedDataStoreUpdateEntry {
name: datastore_name,
scope,
id,
value,
allow_missing,
})
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(err.into()),
}
}
OrderedDataStoreCommands::Increment {
datastore_name,
scope,
id,
increment,
universe_id,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let ordered_datastore = rbx_cloud.ordered_datastore(UniverseId(universe_id));
let res = ordered_datastore
.increment_entry(&OrderedDataStoreIncrementEntry {
name: datastore_name,
scope,
id,
increment,
})
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(err.into()),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/user_restriction_cli.rs | src/cli/user_restriction_cli.rs | use clap::{Args, Subcommand};
use rbxcloud::rbx::{
types::{PlaceId, RobloxUserId, UniverseId},
v2::{Client, UserRestrictionParams},
};
#[derive(Debug, Subcommand)]
pub(crate) enum UserRestrictionCommands {
/// Get user restriction information
Get {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// User ID
#[clap(short = 'U', long, value_parser)]
user_id: u64,
/// Place ID
#[clap(short = 'P', long, value_parser)]
place_id: Option<u64>,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Update user restriction information
Update {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// User ID
#[clap(short = 'U', long, value_parser)]
user_id: u64,
/// Place ID
#[clap(short = 'P', long, value_parser)]
place_id: Option<u64>,
/// Restriction active
#[clap(short = 'A', long, value_parser)]
active: Option<bool>,
/// Restriction duration (seconds)
#[clap(short, long, value_parser)]
duration: Option<u64>,
/// Private reason
#[clap(short = 'r', long, value_parser)]
private_reason: Option<String>,
/// Display reason
#[clap(short = 'D', long, value_parser)]
display_reason: Option<String>,
/// Exclude alternate accounts
#[clap(short, long, value_parser)]
exclude_alts: Option<bool>,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// List user restrictions
List {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// Place ID
#[clap(short = 'P', long, value_parser)]
place_id: Option<u64>,
/// Max page size
#[clap(short = 's', long, value_parser)]
page_size: Option<u32>,
/// Next page token
#[clap(short, long, value_parser)]
token: Option<String>,
/// Filter
#[clap(short, long, value_parser)]
filter: Option<String>,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// List user restriction logs
Logs {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// Place ID
#[clap(short = 'P', long, value_parser)]
place_id: Option<u64>,
/// Max page size
#[clap(short = 's', long, value_parser)]
page_size: Option<u32>,
/// Next page token
#[clap(short, long, value_parser)]
token: Option<String>,
/// Filter
#[clap(short, long, value_parser)]
filter: Option<String>,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Args)]
pub(crate) struct UserRestriction {
#[clap(subcommand)]
command: UserRestrictionCommands,
}
impl UserRestriction {
pub(crate) async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
UserRestrictionCommands::Get {
universe_id,
user_id,
place_id,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let user_restriction_client = client.user_restriction(UniverseId(universe_id));
let res = user_restriction_client
.get_user_restriction(
RobloxUserId(user_id),
place_id.and_then(|id| Some(PlaceId(id))),
)
.await;
match res {
Ok(info) => {
let r = if pretty {
serde_json::to_string_pretty(&info)?
} else {
serde_json::to_string(&info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
UserRestrictionCommands::Update {
universe_id,
user_id,
place_id,
active,
duration,
private_reason,
display_reason,
exclude_alts,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let mut user_restriction_client = client.user_restriction(UniverseId(universe_id));
let res = user_restriction_client
.update_user_restriction(&UserRestrictionParams {
user_id: RobloxUserId(user_id),
place_id: place_id.and_then(|id| Some(PlaceId(id))),
active,
duration,
private_reason,
display_reason,
exclude_alt_accounts: exclude_alts,
})
.await;
match res {
Ok(info) => {
let r = if pretty {
serde_json::to_string_pretty(&info)?
} else {
serde_json::to_string(&info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
UserRestrictionCommands::List {
universe_id,
place_id,
page_size,
token,
filter,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let user_restriction_client = client.user_restriction(UniverseId(universe_id));
let res = user_restriction_client
.list_user_restrictions(
place_id.and_then(|id| Some(PlaceId(id))),
page_size,
filter,
token,
)
.await;
match res {
Ok(info) => {
let r = if pretty {
serde_json::to_string_pretty(&info)?
} else {
serde_json::to_string(&info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
UserRestrictionCommands::Logs {
universe_id,
place_id,
page_size,
token,
filter,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let user_restriction_client = client.user_restriction(UniverseId(universe_id));
let res = user_restriction_client
.list_user_restriction_logs(
place_id.and_then(|id| Some(PlaceId(id))),
page_size,
filter,
token,
)
.await;
match res {
Ok(info) => {
let r = if pretty {
serde_json::to_string_pretty(&info)?
} else {
serde_json::to_string(&info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/messaging_cli.rs | src/cli/messaging_cli.rs | use clap::{Args, Subcommand};
use rbxcloud::rbx::{types::UniverseId, v1::RbxCloud};
#[derive(Debug, Subcommand)]
pub enum MessagingCommands {
/// Publish a message
Publish {
/// Message topic
#[clap(short, long, value_parser)]
topic: String,
/// Message to send
#[clap(short, long, value_parser)]
message: String,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Args)]
pub struct Messaging {
#[clap(subcommand)]
command: MessagingCommands,
}
impl Messaging {
pub async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
MessagingCommands::Publish {
topic,
message,
universe_id,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let messaging = rbx_cloud.messaging(UniverseId(universe_id), &topic);
let res = messaging.publish(&message).await;
match res {
Ok(()) => Ok(Some(format!("published message to topic {topic}"))),
Err(err) => Err(anyhow::anyhow!(err)),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/user_cli.rs | src/cli/user_cli.rs | use clap::{Args, Subcommand};
use rbxcloud::rbx::{
types::RobloxUserId,
v2::{
user::{UserThumbnailFormat, UserThumbnailShape, UserThumbnailSize},
Client,
},
};
#[derive(Debug, Subcommand)]
pub enum UserCommands {
/// Get user information
Get {
/// User ID
#[clap(short, long, value_parser)]
user_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Generate user thumbnail
Thumbnail {
/// User ID
#[clap(short, long, value_parser)]
user_id: u64,
/// Thumbnail size
#[clap(short, long, value_enum)]
size: Option<UserThumbnailSize>,
/// Thumbnail format
#[clap(short, long, value_enum)]
format: Option<UserThumbnailFormat>,
/// Thumbnail shape
#[clap(short = 'S', long, value_enum)]
shape: Option<UserThumbnailShape>,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Args)]
pub struct User {
#[clap(subcommand)]
command: UserCommands,
}
impl User {
pub async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
UserCommands::Get {
user_id,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let user_client = client.user();
let res = user_client.get_user(RobloxUserId(user_id)).await;
match res {
Ok(universe_info) => {
let r = if pretty {
serde_json::to_string_pretty(&universe_info)?
} else {
serde_json::to_string(&universe_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
UserCommands::Thumbnail {
user_id,
size,
format,
shape,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let user_client = client.user();
let res = user_client
.generate_thumbnail(RobloxUserId(user_id), size, format, shape)
.await;
match res {
Ok(universe_info) => {
let r = if pretty {
serde_json::to_string_pretty(&universe_info)?
} else {
serde_json::to_string(&universe_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/assets_cli.rs | src/cli/assets_cli.rs | use std::path::Path;
use clap::{Args, Subcommand};
use rbxcloud::rbx::{
error::Error,
v1::{
assets::{
AssetCreation, AssetCreationContext, AssetCreator, AssetGroupCreator, AssetType,
AssetUserCreator,
},
ArchiveAsset, CreateAsset, GetAsset, GetAssetOperation, RbxCloud, UpdateAsset,
},
};
#[derive(Debug, Clone, clap::ValueEnum)]
pub enum CreatorType {
User,
Group,
}
#[derive(Debug, Subcommand)]
pub enum AssetsCommands {
/// Create an asset
Create {
/// Asset type
#[clap(short = 't', long, value_enum)]
asset_type: Option<AssetType>,
/// Display name
#[clap(short = 'n', long, value_parser)]
display_name: String,
/// Description
#[clap(short, long, value_parser)]
description: String,
/// Expected Robux price
#[clap(short, long, value_parser)]
expected_price: Option<u64>,
/// Creator ID
#[clap(short = 'i', long, value_parser)]
creator_id: u64,
/// Creator type
#[clap(short, long, value_enum)]
creator_type: CreatorType,
/// File (full or relative path)
#[clap(short, long, value_parser)]
filepath: String,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Update an asset
Update {
/// Asset type
#[clap(short = 't', long, value_enum)]
asset_type: Option<AssetType>,
/// Asset ID
#[clap(short = 'i', long, value_parser)]
asset_id: u64,
/// File (full or relative path)
#[clap(short, long, value_parser)]
filepath: String,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Get asset operation information
GetOperation {
/// Operation ID
#[clap(short = 'i', long, value_parser)]
operation_id: String,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Get asset information
Get {
/// Asset ID
#[clap(short = 'i', long, value_parser)]
asset_id: u64,
#[clap(short = 'm', long, value_parser)]
read_mask: Option<String>,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Archive an asset
Archive {
/// Asset ID
#[clap(short = 'i', long, value_parser)]
asset_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Restore an archived asset
Restore {
/// Asset ID
#[clap(short = 'i', long, value_parser)]
asset_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Args)]
pub struct Assets {
#[clap(subcommand)]
command: AssetsCommands,
}
fn create_context_from_creator_type(
creator_type: CreatorType,
creator_id: u64,
expected_price: Option<u64>,
) -> AssetCreationContext {
let expected_price = expected_price.unwrap_or(0);
match creator_type {
CreatorType::User => AssetCreationContext {
expected_price: Some(expected_price),
creator: AssetCreator::User(AssetUserCreator {
user_id: creator_id.to_string(),
}),
},
CreatorType::Group => AssetCreationContext {
expected_price: Some(expected_price),
creator: AssetCreator::Group(AssetGroupCreator {
group_id: creator_id.to_string(),
}),
},
}
}
fn infer_asset_type_from_filepath(filepath: &String) -> Result<AssetType, Error> {
let path = Path::new(filepath);
match path.extension() {
Some(ext) => {
let ext = ext
.to_str()
.ok_or_else(|| Error::InferAssetTypeError(filepath.into()))?;
AssetType::try_from_extension(ext)
}
None => Err(Error::InferAssetTypeError(filepath.into())),
}
}
impl Assets {
pub async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
AssetsCommands::Create {
asset_type,
display_name,
description,
expected_price,
creator_id,
creator_type,
filepath,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let assets = rbx_cloud.assets();
let creation_context =
create_context_from_creator_type(creator_type, creator_id, expected_price);
let asset_type = match asset_type {
Some(t) => Ok(t),
None => infer_asset_type_from_filepath(&filepath),
}?;
let res = assets
.create(&CreateAsset {
asset: AssetCreation {
asset_type,
display_name,
description,
creation_context,
},
filepath: filepath.clone(),
})
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
AssetsCommands::Update {
asset_type,
asset_id,
filepath,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let assets = rbx_cloud.assets();
let asset_type = match asset_type {
Some(t) => Ok(t),
None => infer_asset_type_from_filepath(&filepath),
}?;
let res = assets
.update(&UpdateAsset {
asset_id,
asset_type,
filepath,
})
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
AssetsCommands::GetOperation {
operation_id,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let assets = rbx_cloud.assets();
let res = assets
.get_operation(&GetAssetOperation { operation_id })
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
AssetsCommands::Get {
asset_id,
read_mask,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let assets = rbx_cloud.assets();
let res = assets
.get(&GetAsset {
asset_id,
read_mask,
})
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
AssetsCommands::Archive {
asset_id,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let assets = rbx_cloud.assets();
let res = assets.archive(&ArchiveAsset { asset_id }).await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
AssetsCommands::Restore {
asset_id,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let assets = rbx_cloud.assets();
let res = assets.restore(&ArchiveAsset { asset_id }).await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/universe_cli.rs | src/cli/universe_cli.rs | use clap::{Args, Subcommand};
use rbxcloud::rbx::{
types::UniverseId,
v2::{universe::UpdateUniverseInfo, Client},
};
#[derive(Debug, Subcommand)]
pub enum UniverseCommands {
/// Get universe information
Get {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Restart servers
Restart {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Update Universe name
UpdateName {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// New Universe name
#[clap(short, long, value_parser)]
name: String,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Update Universe description
UpdateDescription {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// New Universe description
#[clap(short, long, value_parser)]
description: String,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Args)]
pub struct Universe {
#[clap(subcommand)]
command: UniverseCommands,
}
impl Universe {
pub async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
UniverseCommands::Get {
universe_id,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let universe_client = client.universe(UniverseId(universe_id));
let res = universe_client.get().await;
match res {
Ok(universe_info) => {
let r = if pretty {
serde_json::to_string_pretty(&universe_info)?
} else {
serde_json::to_string(&universe_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
UniverseCommands::Restart {
universe_id,
api_key,
} => {
let client = Client::new(&api_key);
let universe_client = client.universe(UniverseId(universe_id));
let res = universe_client.restart_servers().await;
match res {
Ok(()) => Ok(Some("servers restarted".to_string())),
Err(err) => Err(anyhow::anyhow!(err)),
}
}
UniverseCommands::UpdateName {
universe_id,
name,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let universe_client = client.universe(UniverseId(universe_id));
let res = universe_client
.update(
"displayName".to_string(),
UpdateUniverseInfo {
path: None,
create_time: None,
update_time: None,
display_name: Some(name),
description: None,
user: None,
group: None,
visibility: None,
facebook_social_link: None,
twitter_social_link: None,
youtube_social_link: None,
twitch_social_link: None,
discord_social_link: None,
roblox_group_social_link: None,
guilded_social_link: None,
voice_chat_enabled: None,
age_rating: None,
private_server_price_robux: None,
desktop_enabled: None,
mobile_enabled: None,
tablet_enabled: None,
console_enabled: None,
vr_enabled: None,
},
)
.await;
match res {
Ok(universe_info) => {
let r = if pretty {
serde_json::to_string_pretty(&universe_info)?
} else {
serde_json::to_string(&universe_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
UniverseCommands::UpdateDescription {
universe_id,
description,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let universe_client = client.universe(UniverseId(universe_id));
let res = universe_client
.update(
"description".to_string(),
UpdateUniverseInfo {
path: None,
create_time: None,
update_time: None,
display_name: None,
description: Some(description),
user: None,
group: None,
visibility: None,
facebook_social_link: None,
twitter_social_link: None,
youtube_social_link: None,
twitch_social_link: None,
discord_social_link: None,
roblox_group_social_link: None,
guilded_social_link: None,
voice_chat_enabled: None,
age_rating: None,
private_server_price_robux: None,
desktop_enabled: None,
mobile_enabled: None,
tablet_enabled: None,
console_enabled: None,
vr_enabled: None,
},
)
.await;
match res {
Ok(universe_info) => {
let r = if pretty {
serde_json::to_string_pretty(&universe_info)?
} else {
serde_json::to_string(&universe_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/mod.rs | src/cli/mod.rs | mod assets_cli;
mod datastore_cli;
mod experience_cli;
mod group_cli;
mod inventory_cli;
mod luau_execution_cli;
mod messaging_cli;
mod notification_cli;
mod ordered_datastore_cli;
mod place_cli;
mod subscription_cli;
mod universe_cli;
mod user_cli;
mod user_restriction_cli;
use clap::{Parser, Subcommand};
use inventory_cli::Inventory;
use luau_execution_cli::Luau;
use universe_cli::Universe;
use user_cli::User;
use user_restriction_cli::UserRestriction;
use self::{
assets_cli::Assets, datastore_cli::DataStore, experience_cli::Experience, group_cli::Group,
messaging_cli::Messaging, notification_cli::Notification,
ordered_datastore_cli::OrderedDataStore, place_cli::Place, subscription_cli::Subscription,
};
#[derive(Debug, Parser)]
#[clap(name = "rbxcloud", version)]
pub(crate) struct Cli {
#[clap(subcommand)]
pub command: Command,
}
#[derive(Debug, Subcommand)]
pub(crate) enum Command {
/// Access the Roblox Assets API
Assets(Assets),
/// Access the Roblox Experience API
Experience(Experience),
/// Access the Roblox Messaging API
Messaging(Messaging),
/// Access the Roblox DataStore API
Datastore(DataStore),
/// Access the Roblox OrderedDataStore API
OrderedDatastore(OrderedDataStore),
/// Access the Roblox user inventory API
Inventory(Inventory),
/// Access the Roblox Group API
Group(Group),
Luau(Luau),
/// Access the Roblox Subscription API
Subscription(Subscription),
/// Access the Roblox Notification API
Notification(Notification),
/// Access the Roblox Place API
Place(Place),
/// Access the Roblox Universe API
Universe(Universe),
/// Access the Roblox User API
User(User),
/// Access to the Roblox User Restriction API
UserRestriction(UserRestriction),
}
impl Cli {
pub(crate) async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
Command::Assets(command) => command.run().await,
Command::Experience(command) => command.run().await,
Command::Messaging(command) => command.run().await,
Command::Datastore(command) => command.run().await,
Command::OrderedDatastore(command) => command.run().await,
Command::Group(command) => command.run().await,
Command::Inventory(command) => command.run().await,
Command::Luau(command) => command.run().await,
Command::Subscription(command) => command.run().await,
Command::Notification(command) => command.run().await,
Command::Place(command) => command.run().await,
Command::Universe(command) => command.run().await,
Command::User(command) => command.run().await,
Command::UserRestriction(command) => command.run().await,
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/experience_cli.rs | src/cli/experience_cli.rs | use clap::{Args, Subcommand, ValueEnum};
use rbxcloud::rbx::{
types::{PlaceId, UniverseId},
v1::{PublishVersionType, RbxCloud},
};
#[derive(Debug, Subcommand)]
pub enum ExperienceCommands {
/// Publish an experience
Publish {
/// Filename (full or relative) of the RBXL file
#[clap(short, long, value_parser)]
filename: String,
/// Place ID of the experience
#[clap(short = 'i', long, value_parser)]
place_id: u64,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Version type
#[clap(short = 't', long, value_enum)]
version_type: VersionType,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Args)]
pub struct Experience {
#[clap(subcommand)]
command: ExperienceCommands,
}
#[derive(Debug, Clone, ValueEnum)]
pub enum VersionType {
Saved,
Published,
}
impl Experience {
pub async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
ExperienceCommands::Publish {
filename,
place_id,
universe_id,
version_type,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let publish_version_type = match version_type {
VersionType::Published => PublishVersionType::Published,
VersionType::Saved => PublishVersionType::Saved,
};
let res = rbx_cloud
.experience(UniverseId(universe_id), PlaceId(place_id))
.publish(&filename, publish_version_type)
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(err.into()),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/inventory_cli.rs | src/cli/inventory_cli.rs | use clap::{Args, Subcommand};
use rbxcloud::rbx::{types::RobloxUserId, v2::Client};
#[derive(Debug, Subcommand)]
pub enum InventoryCommands {
/// List inventory items for a given user
List {
/// Roblox user ID
#[clap(short, long, value_parser)]
user_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Max page size
#[clap(short, long, value_parser)]
max_page_size: Option<u32>,
/// Next page token
#[clap(short = 'n', long, value_parser)]
page_token: Option<String>,
/// Filter string
#[clap(short, long, value_parser)]
filter: Option<String>,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Args)]
pub struct Inventory {
#[clap(subcommand)]
command: InventoryCommands,
}
impl Inventory {
pub async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
InventoryCommands::List {
user_id,
pretty,
max_page_size,
page_token,
filter,
api_key,
} => {
let client = Client::new(&api_key);
let inventory = client.inventory();
let res = inventory
.list_inventory_items(RobloxUserId(user_id), max_page_size, page_token, filter)
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/datastore_cli.rs | src/cli/datastore_cli.rs | use clap::{Args, Subcommand, ValueEnum};
use rbxcloud::rbx::{
types::{ReturnLimit, RobloxUserId, UniverseId},
v1::{
DataStoreDeleteEntry, DataStoreGetEntry, DataStoreGetEntryVersion, DataStoreIncrementEntry,
DataStoreListEntries, DataStoreListEntryVersions, DataStoreListStores, DataStoreSetEntry,
RbxCloud,
},
};
#[derive(Debug, Subcommand)]
pub enum DataStoreCommands {
/// List all DataStores in a given universe
ListStores {
/// Return only DataStores with this prefix
#[clap(short = 'r', long, value_parser)]
prefix: Option<String>,
/// Maximum number of items to return
#[clap(short, long, value_parser)]
limit: u64,
/// Cursor for the next set of data
#[clap(short, long, value_parser)]
cursor: Option<String>,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// List all entries in a DataStore
List {
/// DataStore name
#[clap(short, long, value_parser)]
datastore_name: String,
/// DataStore scope
#[clap(short, long, value_parser)]
scope: Option<String>,
/// If true, return keys from all scopes
#[clap(short = 'o', long, value_parser)]
all_scopes: bool,
/// Return only DataStores with this prefix
#[clap(short = 'r', long, value_parser)]
prefix: Option<String>,
/// Maximum number of items to return
#[clap(short, long, value_parser)]
limit: u64,
/// Cursor for the next set of data
#[clap(short, long, value_parser)]
cursor: Option<String>,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Get a DataStore entry
Get {
/// DataStore name
#[clap(short, long, value_parser)]
datastore_name: String,
/// DataStore scope
#[clap(short, long, value_parser)]
scope: Option<String>,
/// The key of the entry
#[clap(short, long, value_parser)]
key: String,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Set or create the value of a DataStore entry
Set {
/// DataStore name
#[clap(short, long, value_parser)]
datastore_name: String,
/// DataStore scope
#[clap(short, long, value_parser)]
scope: Option<String>,
/// The key of the entry
#[clap(short, long, value_parser)]
key: String,
/// Only update if the current version matches this
#[clap(short = 'i', long, value_parser)]
match_version: Option<String>,
/// Only create the entry if it does not exist
#[clap(short, long, value_parser)]
exclusive_create: Option<bool>,
/// JSON-stringified data (up to 4MB)
#[clap(short = 'D', long, value_parser)]
data: String,
/// Associated UserID (can be multiple)
#[clap(short = 'U', long, value_parser)]
user_ids: Option<Vec<u64>>,
/// JSON-stringified attributes data
#[clap(short = 't', long, value_parser)]
attributes: Option<String>,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Increment or create the value of a DataStore entry
Increment {
/// DataStore name
#[clap(short, long, value_parser)]
datastore_name: String,
/// DataStore scope
#[clap(short, long, value_parser)]
scope: Option<String>,
/// The key of the entry
#[clap(short, long, value_parser)]
key: String,
/// The amount by which the entry should be incremented
#[clap(short, long, value_parser)]
increment_by: f64,
/// Comma-separated list of Roblox user IDs
#[clap(short = 'U', long, value_parser)]
user_ids: Option<Vec<u64>>,
/// JSON-stringified attributes data
#[clap(short = 't', long, value_parser)]
attributes: Option<String>,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Delete a DataStore entry
Delete {
/// DataStore name
#[clap(short, long, value_parser)]
datastore_name: String,
/// DataStore scope
#[clap(short, long, value_parser)]
scope: Option<String>,
/// The key of the entry
#[clap(short, long, value_parser)]
key: String,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// List all versions of a DataStore entry
ListVersions {
/// DataStore name
#[clap(short, long, value_parser)]
datastore_name: String,
/// DataStore scope
#[clap(short, long, value_parser)]
scope: Option<String>,
/// The key of the entry
#[clap(short, long, value_parser)]
key: String,
/// Start time constraint (ISO UTC Datetime)
#[clap(short = 't', long, value_parser)]
start_time: Option<String>,
/// End time constraint (ISO UTC Datetime)
#[clap(short = 'e', long, value_parser)]
end_time: Option<String>,
/// Sort order
#[clap(short = 'o', long, value_enum)]
sort_order: ListEntrySortOrder,
/// Maximum number of items to return
#[clap(short, long, value_parser)]
limit: u64,
/// Cursor for the next set of data
#[clap(short, long, value_parser)]
cursor: Option<String>,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
/// Get the value of a specific entry version
GetVersion {
/// DataStore name
#[clap(short, long, value_parser)]
datastore_name: String,
/// DataStore scope
#[clap(short, long, value_parser)]
scope: Option<String>,
/// The key of the entry
#[clap(short, long, value_parser)]
key: String,
/// The version of the key
#[clap(short = 'i', long, value_parser)]
version_id: String,
/// Universe ID of the experience
#[clap(short, long, value_parser)]
universe_id: u64,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Clone, ValueEnum)]
pub enum ListEntrySortOrder {
Ascending,
Descending,
}
#[derive(Debug, Args)]
pub struct DataStore {
#[clap(subcommand)]
command: DataStoreCommands,
}
#[inline]
fn u64_ids_to_roblox_ids(user_ids: Option<Vec<u64>>) -> Option<Vec<RobloxUserId>> {
user_ids.map(|ids| {
ids.into_iter()
.map(RobloxUserId)
.collect::<Vec<RobloxUserId>>()
})
}
impl DataStore {
pub async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
DataStoreCommands::ListStores {
prefix,
limit,
cursor,
universe_id,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let datastore = rbx_cloud.datastore(UniverseId(universe_id));
let res = datastore
.list_stores(&DataStoreListStores {
cursor,
limit: ReturnLimit(limit),
prefix,
})
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(err.into()),
}
}
DataStoreCommands::List {
prefix,
limit,
cursor,
universe_id,
api_key,
datastore_name,
scope,
pretty,
all_scopes,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let datastore = rbx_cloud.datastore(UniverseId(universe_id));
let res = datastore
.list_entries(&DataStoreListEntries {
name: datastore_name,
scope,
all_scopes,
prefix,
limit: ReturnLimit(limit),
cursor,
})
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(err.into()),
}
}
DataStoreCommands::Get {
datastore_name,
scope,
key,
universe_id,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let datastore = rbx_cloud.datastore(UniverseId(universe_id));
let res = datastore
.get_entry_string(&DataStoreGetEntry {
name: datastore_name,
scope,
key,
})
.await;
match res {
Ok(data) => Ok(Some(data)),
Err(err) => Err(err.into()),
}
}
DataStoreCommands::Set {
datastore_name,
scope,
key,
match_version,
exclusive_create,
data,
user_ids,
attributes,
universe_id,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let datastore = rbx_cloud.datastore(UniverseId(universe_id));
let ids = u64_ids_to_roblox_ids(user_ids);
let res = datastore
.set_entry(&DataStoreSetEntry {
name: datastore_name,
scope,
key,
match_version,
exclusive_create,
roblox_entry_user_ids: ids,
roblox_entry_attributes: attributes,
data,
})
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(err.into()),
}
}
DataStoreCommands::Increment {
datastore_name,
scope,
key,
increment_by,
user_ids,
attributes,
universe_id,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let datastore = rbx_cloud.datastore(UniverseId(universe_id));
let ids = u64_ids_to_roblox_ids(user_ids);
let res = datastore
.increment_entry(&DataStoreIncrementEntry {
name: datastore_name,
scope,
key,
roblox_entry_user_ids: ids,
roblox_entry_attributes: attributes,
increment_by,
})
.await;
match res {
Ok(data) => Ok(Some(format!("{data}"))),
Err(err) => Err(err.into()),
}
}
DataStoreCommands::Delete {
datastore_name,
scope,
key,
universe_id,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let datastore = rbx_cloud.datastore(UniverseId(universe_id));
let res = datastore
.delete_entry(&DataStoreDeleteEntry {
name: datastore_name,
scope,
key,
})
.await;
match res {
Ok(_) => Ok(None),
Err(err) => Err(err.into()),
}
}
DataStoreCommands::ListVersions {
datastore_name,
scope,
key,
start_time,
end_time,
sort_order,
limit,
cursor,
universe_id,
pretty,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let datastore = rbx_cloud.datastore(UniverseId(universe_id));
let res = datastore
.list_entry_versions(&DataStoreListEntryVersions {
name: datastore_name,
scope,
key,
start_time,
end_time,
sort_order: format!("{sort_order:?}"),
limit: ReturnLimit(limit),
cursor,
})
.await;
match res {
Ok(data) => {
let r = if pretty {
serde_json::to_string_pretty(&data)?
} else {
serde_json::to_string(&data)?
};
Ok(Some(r))
}
Err(err) => Err(err.into()),
}
}
DataStoreCommands::GetVersion {
datastore_name,
scope,
key,
version_id,
universe_id,
api_key,
} => {
let rbx_cloud = RbxCloud::new(&api_key);
let datastore = rbx_cloud.datastore(UniverseId(universe_id));
let res = datastore
.get_entry_version(&DataStoreGetEntryVersion {
name: datastore_name,
scope,
key,
version_id,
})
.await;
match res {
Ok(data) => Ok(Some(data)),
Err(err) => Err(err.into()),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/src/cli/subscription_cli.rs | src/cli/subscription_cli.rs | use clap::{Args, Subcommand};
use rbxcloud::rbx::{
types::UniverseId,
v2::{subscription::SubscriptionView, Client},
};
#[derive(Debug, Subcommand)]
pub enum SubscriptionCommands {
/// Get information about a subscription
Get {
/// Universe ID
#[clap(short, long, value_parser)]
universe_id: u64,
/// Subscription product ID
#[clap(short = 'S', long, value_parser)]
product: String,
/// Subscription ID
#[clap(short, long, value_parser)]
subscription: String,
/// View type
#[clap(short, long, value_enum)]
view: Option<SubscriptionView>,
/// Pretty-print the JSON response
#[clap(short, long, value_parser, default_value_t = false)]
pretty: bool,
/// Roblox Open Cloud API Key
#[clap(short, long, value_parser, env = "RBXCLOUD_API_KEY")]
api_key: String,
},
}
#[derive(Debug, Args)]
pub struct Subscription {
#[clap(subcommand)]
command: SubscriptionCommands,
}
impl Subscription {
pub async fn run(self) -> anyhow::Result<Option<String>> {
match self.command {
SubscriptionCommands::Get {
universe_id,
product,
subscription,
view,
pretty,
api_key,
} => {
let client = Client::new(&api_key);
let subscription_client = client.subscription();
let res = subscription_client
.get(UniverseId(universe_id), product, subscription, view)
.await;
match res {
Ok(subscription_info) => {
let r = if pretty {
serde_json::to_string_pretty(&subscription_info)?
} else {
serde_json::to_string(&subscription_info)?
};
Ok(Some(r))
}
Err(err) => Err(anyhow::anyhow!(err)),
}
}
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/examples/publish-message.rs | examples/publish-message.rs | use rbxcloud::rbx::{error::Error, types::UniverseId, v1::RbxCloud};
async fn publish_message() -> Result<(), Error> {
// Inputs:
let api_key = "MY_API_KEY";
let universe_id = 9876543210;
let topic = "MyTopic";
let message = "Hello, this is my message";
// Define RbxCloud Messaging instance:
let cloud = RbxCloud::new(api_key);
let messaging = cloud.messaging(UniverseId(universe_id), topic);
// Publish a message:
messaging.publish(message).await
}
#[tokio::main]
async fn main() {
// Publish a message:
let message_result = publish_message().await;
match message_result {
Ok(()) => {
println!("Message successfully published");
}
Err(e) => {
eprintln!("{e:?}");
}
}
/*
From a Lua script within a Roblox experience:
local MessagingService = game:GetService("MessagingService")
MessagingService:SubscribeAsync("MyTopic"):Connect(function(message)
print(message)
--> {"message": "Hello, this is my message"}
end)
*/
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/examples/group-get-shout.rs | examples/group-get-shout.rs | use rbxcloud::rbx::{error::Error, types::GroupId, v2::Client};
async fn get_group_shout() -> Result<String, Error> {
// Inputs:
let api_key = "MY_API_KEY";
let group_id = 9876543210;
let client = Client::new(api_key);
let group = client.group(GroupId(group_id));
// Get the shout's content:
group.get_shout().await.map(|r| r.content)
}
#[tokio::main]
async fn main() {
let shout_res = get_group_shout().await;
match shout_res {
Ok(shout) => println!("{shout}"),
Err(e) => eprintln!("{e:?}"),
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/examples/publish-place.rs | examples/publish-place.rs | use rbxcloud::rbx::{
types::{PlaceId, UniverseId},
v1::{PublishVersionType, RbxCloud},
};
#[tokio::main]
async fn main() {
// Inputs:
let api_key = "MY_API_KEY";
let universe_id = 9876543210;
let place_id = 1234567890;
let filename = "my_experience.rbxl";
let publish_version_type = PublishVersionType::Published;
// Define RbxCloud instance:
let cloud = RbxCloud::new(api_key);
let experience = cloud.experience(UniverseId(universe_id), PlaceId(place_id));
// Publish place:
let publish_result = experience.publish(filename, publish_version_type).await;
match publish_result {
Ok(result) => {
println!("Published place! New version: {}", result.version_number);
}
Err(e) => {
eprintln!("{e:?}");
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/examples/user-info.rs | examples/user-info.rs | use rbxcloud::rbx::{
error::Error,
types::RobloxUserId,
v2::{user::GetUserResponse, Client},
};
async fn user_info() -> Result<GetUserResponse, Error> {
// Inputs:
let api_key = "MY_API_KEY";
let user_id = 308165;
let client = Client::new(api_key);
let user_client = client.user();
user_client.get_user(RobloxUserId(user_id)).await
}
#[tokio::main]
async fn main() {
let user_info_res = user_info().await;
match user_info_res {
Ok(user_info) => {
println!("{:?}", user_info);
}
Err(e) => {
eprintln!("{e:?}");
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/examples/datastore-get-entry.rs | examples/datastore-get-entry.rs | use rbxcloud::rbx::{
types::UniverseId,
v1::{DataStoreGetEntry, RbxCloud},
};
#[tokio::main]
async fn main() {
// Inputs:
let api_key = "MY_API_KEY";
let universe_id = 9876543210;
let datastore_name = String::from("my_datastore");
let key = String::from("my_key");
// Define RbxCloud DataStore instance:
let cloud = RbxCloud::new(api_key);
let datastore = cloud.datastore(UniverseId(universe_id));
// Get entry:
let entry_result = datastore
.get_entry_string(&DataStoreGetEntry {
name: datastore_name,
scope: None,
key,
})
.await;
// Print entry result or error:
match entry_result {
Ok(result) => {
println!("{result}");
}
Err(e) => {
eprintln!("{e:?}");
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/examples/restart-servers.rs | examples/restart-servers.rs | use rbxcloud::rbx::{error::Error, types::UniverseId, v2::Client};
async fn restart_servers() -> Result<(), Error> {
// Inputs:
let api_key = "MY_API_KEY";
let universe_id = 9876543210;
let client = Client::new(api_key);
let universe_client = client.universe(UniverseId(universe_id));
universe_client.restart_servers().await
}
#[tokio::main]
async fn main() {
let restart_result = restart_servers().await;
match restart_result {
Ok(()) => {
println!("Servers restarted");
}
Err(e) => {
eprintln!("{e:?}");
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
Sleitnick/rbxcloud | https://github.com/Sleitnick/rbxcloud/blob/251d8c40f6267f49217af3034eb91718a90c3c4c/examples/send-notification.rs | examples/send-notification.rs | use std::collections::HashMap;
use rbxcloud::rbx::{
error::Error,
types::{RobloxUserId, UniverseId},
v2::{
notification::{
JoinExperience, Notification, NotificationPayload, NotificationResponse,
NotificationSource, NotificationType, Parameter,
},
Client,
},
};
async fn send_notification() -> Result<NotificationResponse, Error> {
// Inputs:
let api_key = "MY_API_KEY";
let message_id = "MY_MESSAGE_ID";
let universe_id = 9876543210;
let user_id = 308165;
let client = Client::new(api_key);
let notification_client = client.notification(UniverseId(universe_id));
let notification = Notification {
source: NotificationSource {
universe: format!("universe/{}", universe_id),
},
payload: NotificationPayload {
message_id: message_id.to_string(),
notification_type: NotificationType::TypeUnspecified,
join_experience: Some(JoinExperience {
launch_data: "Some launch data here".to_string(),
}),
analytics_data: Some(HashMap::from([(
"category".to_string(),
"Bronze egg hatched".to_string(),
)])),
parameters: Some(HashMap::from([(
"key".to_string(),
Parameter {
string_value: Some("bronze egg".to_string()),
int64_value: None,
},
)])),
},
};
notification_client
.send(RobloxUserId(user_id), notification)
.await
}
#[tokio::main]
async fn main() {
let send_result = send_notification().await;
match send_result {
Ok(result) => {
println!("Notification sent: {:?}", result);
}
Err(e) => {
eprintln!("{e:?}");
}
}
}
| rust | MIT | 251d8c40f6267f49217af3034eb91718a90c3c4c | 2026-01-04T20:19:38.803139Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app.rs | src/app.rs | use crate::{
app::{
components::{AboutSection, TinyWaveFormIcon},
routes::{
admin::{self, AdminWrapper},
custom,
index::Home,
issue,
},
},
error_template::{AppError, ErrorTemplate},
Username,
};
use leptos::{either::Either, logging::log, prelude::*};
use leptos_meta::*;
use leptos_router::{components::*, path};
mod components;
mod routes;
pub fn shell(options: LeptosOptions) -> impl IntoView {
// in --release, these must be provided
#[cfg(not(debug_assertions))]
let pkg_path: &'static str = std::env!("CDN_PKG_PATH");
#[cfg(not(debug_assertions))]
let cdn_path: &'static str = std::env!("CDN_PATH");
// in debug, we can use the defaults or the env
// vars
#[cfg(debug_assertions)]
let pkg_path: &'static str =
std::option_env!("CDN_PKG_PATH").unwrap_or("/pkg");
#[cfg(debug_assertions)]
let cdn_path: &'static str =
std::option_env!("CDN_PATH").unwrap_or("/");
view! {
<!DOCTYPE html>
<html
lang="en"
class="h-full bg-ctp-base antialiased"
>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="preconnect" href="https://cdn.thisweekinbevy.com"/>
<style>
r#"@font-face {
font-family: "PP Neue Montreal";
src: url("https://cdn.thisweekinbevy.com/pp-neue-montreal/PPNeueMontreal-Variable.woff2")
format("woff2");
font-weight: 100 900;
font-display: swap;
font-style: normal;
}"#
</style>
<link
rel="preload"
as_="font"
type_="font/woff2"
crossorigin="anonymous"
href="https://cdn.thisweekinbevy.com/pp-neue-montreal/PPNeueMontreal-Variable.woff2"
/>
<meta name="og:site_name" content="This Week in Bevy"/>
<AutoReload options=options.clone() />
<HydrationScripts options=options.clone() root=cdn_path islands=true/>
<HashedStylesheet options=options root=cdn_path/>
// <link rel="stylesheet" id="leptos" href=format!("{pkg_path}/this-week-in-bevy.css")/>
// <link rel="shortcut icon" type="image/ico" href="/favicon.ico"/>
<link
rel="apple-touch-icon"
sizes="180x180"
href=format!("{cdn_path}/apple-touch-icon.png")
/>
<link
rel="icon"
type="image/png"
sizes="32x32"
href=format!("{cdn_path}/favicon-32x32.png")
/>
<link
rel="icon"
type="image/png"
sizes="16x16"
href=format!("{cdn_path}/favicon-16x16.png")
/>
<link rel="manifest" href=format!("{cdn_path}/site.webmanifest")/>
<meta name="msapplication-TileColor" content="#cdd6f4"/>
<meta name="theme-color" content="#cdd6f4"/>
<MetaTags/>
</head>
<body class="flex min-h-full">
<App/>
</body>
</html>
}
}
#[component]
pub fn App() -> impl IntoView {
// Provides context that manages stylesheets,
// titles, meta tags, etc.
provide_meta_context();
view! {
<Router>
<Wrapper>
<Routes fallback=|| {
let mut outside_errors = Errors::default();
outside_errors.
insert_with_default_key(AppError::NotFound);
view! { <ErrorTemplate outside_errors/>
}.into_view() }>
<Route path=path!("") view=Home/>
<Route path=path!("/issue/:slug") view=issue::Issue/>
<Route path=path!("/custom/:slug") view=custom::Issue/>
<Route path=path!("/login") view=Login/>
<ProtectedParentRoute
path=path!("/admin")
redirect_path=|| "/login"
condition=move || {
let logged_in_user = use_context::<Option<Username>>().flatten();
Some(logged_in_user == Some(Username("ChristopherBiscardi".to_string())))
}
view=AdminWrapper
>
<Route path=path!("") view=admin::AdminHomepage/>
<Route path=path!("/issue") view=admin::issues::Issues/>
<Route path=path!("/issue/:id") view=admin::issue::Issue/>
<Route path=path!("/showcase") view=admin::showcase::Showcase/>
<Route path=path!("/showcase/:id") view=admin::showcase::id::Showcase/>
<Route path=path!("/crate_release") view=admin::crate_release::CrateRelease/>
<Route
path=path!("/crate_release/:id")
view=admin::crate_release::id::CrateRelease
/>
<Route path=path!("/devlog") view=admin::devlog::Devlog/>
<Route path=path!("/devlog/:id") view=admin::devlog::id::Devlog/>
<Route path=path!("/educational") view=admin::educational::Educational/>
<Route path=path!("/educational/:id") view=admin::educational::id::Educational/>
<Route path=path!("/images") view=admin::image::Image/>
<Route path=path!("/github") view=admin::github::GitHub/>
</ProtectedParentRoute>
</Routes>
</Wrapper>
</Router>
}
}
#[component]
fn Login(// Query(NextUrl { next }): Query<NextUrl>,
) -> impl IntoView {
let message = Some("hello!");
view! {
<div>
{message
.map(|msg| {
view! {
<span>
<strong>{msg}</strong>
</span>
}
})}
<form method="post">
<input type="submit" value="GitHub Login"/>
// {% if let Some(next) = next %}
// <input type="hidden" name="next" value="{{next}}" />
// {% endif %}
</form>
</div>
}
}
#[component]
fn PersonIcon(
#[prop(into)] class: String,
) -> impl IntoView {
view! {
<svg aria-hidden="true" viewBox="0 0 11 12" class=class>
<path d="M5.019 5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Zm3.29 7c1.175 0 2.12-1.046 1.567-2.083A5.5 5.5 0 0 0 5.019 7 5.5 5.5 0 0 0 .162 9.917C-.39 10.954.554 12 1.73 12h6.578Z"></path>
</svg>
}
}
#[component]
fn YouTubeIcon(
#[prop(into, default = "".to_string())] class: String,
) -> impl IntoView {
view! {
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 28.57 20" class=class>
<path
fill="#FF0000"
d="M27.973 3.123A3.578 3.578 0 0 0 25.447.597C23.22 0 14.285 0 14.285 0S5.35 0 3.123.597A3.578 3.578 0 0 0 .597 3.123C0 5.35 0 10 0 10s0 4.65.597 6.877a3.578 3.578 0 0 0 2.526 2.526C5.35 20 14.285 20 14.285 20s8.935 0 11.162-.597a3.578 3.578 0 0 0 2.526-2.526C28.57 14.65 28.57 10 28.57 10s-.002-4.65-.597-6.877Z"
></path>
<path fill="#fff" d="M11.425 14.285 18.848 10l-7.423-4.285v8.57Z"></path>
</svg>
}
}
#[component]
fn GitHubIcon(
#[prop(into, default = "".to_string())] class: String,
) -> impl IntoView {
view! {
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" class=class fill="none">
<path
fill="var(--brand-github)"
fill-rule="evenodd"
d="M512 0C229.12 0 0 229.12 0 512c0 226.56 146.56 417.92 350.08 485.76 25.6 4.48 35.2-10.88 35.2-24.32 0-12.16-.64-52.48-.64-95.36-128.64 23.68-161.92-31.36-172.16-60.16-5.76-14.72-30.72-60.16-52.48-72.32-17.92-9.6-43.52-33.28-.64-33.92 40.32-.64 69.12 37.12 78.72 52.48 46.08 77.44 119.68 55.68 149.12 42.24 4.48-33.28 17.92-55.68 32.64-68.48-113.92-12.8-232.96-56.96-232.96-252.8 0-55.68 19.84-101.76 52.48-137.6-5.12-12.8-23.04-65.28 5.12-135.68 0 0 42.88-13.44 140.8 52.48 40.96-11.52 84.48-17.28 128-17.28 43.52 0 87.04 5.76 128 17.28 97.92-66.56 140.8-52.48 140.8-52.48 28.16 70.4 10.24 122.88 5.12 135.68 32.64 35.84 52.48 81.28 52.48 137.6 0 196.48-119.68 240-233.6 252.8 18.56 16 34.56 46.72 34.56 94.72 0 68.48-.64 123.52-.64 140.8 0 13.44 9.6 29.44 35.2 24.32C877.44 929.92 1024 737.92 1024 512 1024 229.12 794.88 0 512 0Z"
clip-rule="evenodd"
></path>
</svg>
}
}
#[component]
fn RSSIcon(
#[prop(into, default = "".to_string())] class: String,
) -> impl IntoView {
view! {
<svg
xmlns="http://www.w3.org/2000/svg"
class=class
width="256"
height="256"
viewBox="0 0 8 8"
>
<rect width="8" height="8" rx="1.5" style="stroke:none;fill:orange"></rect>
<circle cx="2" cy="6" r="1" class="symbol"></circle>
<path d="M1 4a3 3 0 0 1 3 3h1a4 4 0 0 0-4-4z" class="symbol"></path>
<path d="M1 2a5 5 0 0 1 5 5h1a6 6 0 0 0-6-6z" class="symbol"></path>
</svg>
}
}
/// Renders the home page of your application.
#[component]
fn Wrapper(children: Children) -> impl IntoView {
let maintainers =
["chris biscardi", "The Bevy Community"];
let mntnrs = maintainers.iter().enumerate().map(|(i, cite)| {
if i == 0 {
Either::Left(view! {
<>
<span>{cite.to_string()}</span>
</>
})
} else {
Either::Right(view! {
<>
<span aria-hidden="true" class="text-ctp-text">
"/"
</span>
<span>{cite.to_string()}</span>
</>
})
}
}).collect_view();
view! {
<div class="w-full">
<header class="bg-ctp-mantle lg:fixed lg:inset-y-0 lg:left-0 lg:flex lg:w-112 lg:items-start lg:overflow-y-auto xl:w-120">
<div class="hidden lg:sticky lg:top-0 lg:flex lg:w-16 lg:flex-none lg:items-center lg:whitespace-nowrap lg:py-12 lg:text-sm lg:leading-7 lg:[writing-mode:vertical-rl]">
<span class="font-mono text-ctp-text">Curated by</span>
<span class="mt-6 flex gap-6 font-bold text-ctp-text">{mntnrs.clone()}</span>
</div>
<div class="relative z-10 mx-auto px-4 pb-4 pt-10 sm:px-6 md:max-w-2xl md:px-4 lg:min-h-full lg:flex-auto lg:border-x lg:border-ctp-crust lg:px-8 lg:py-12 xl:px-12">
<a
href="/"
class="relative mx-auto block w-48 overflow-hidden rounded-lg bg-ctp-crust shadow-xl shadow-ctp-crust sm:w-64 sm:rounded-xl lg:w-auto lg:rounded-2xl"
aria-label="Homepage"
>
<picture>
<source
srcset="https://res.cloudinary.com/dilgcuzda/image/upload/v1708481576/thisweekinbevy/this-week-in-bevydark_wdnm2d.avif"
media="(prefers-color-scheme: dark)"
/>
<img
class="w-full aspect-square"
src="https://res.cloudinary.com/dilgcuzda/image/upload/v1708481576/thisweekinbevy/this-week-in-bevylight_uddwes.avif"
alt=""
/>
</picture>
<div class="absolute inset-0 rounded-lg ring-1 ring-inset ring-black/10 sm:rounded-xl lg:rounded-2xl"></div>
</a>
<div class="mt-10 text-center lg:mt-12 lg:text-left">
<p class="text-xl font-bold text-ctp-text">
<a href="/">This Week in Bevy</a>
</p>
<p class="mt-3 text-lg font-medium leading-8 text-ctp-text">
What happened this week in the Bevy Engine ecosystem
</p>
</div>
<AboutSection class="mt-12 hidden lg:block"/>
<section class="mt-10 lg:mt-12">
<h2 class="sr-only flex items-center font-mono text-sm font-medium leading-7 text-ctp-text lg:not-sr-only">
<TinyWaveFormIcon
start_color="fill-pink-300"
end_color="fill-rose-300"
class="h-2.5 w-2.5"
/>
<span class="ml-2.5">Links</span>
</h2>
<div class="h-px bg-gradient-to-r from-slate-200/0 via-slate-200 to-slate-200/0 lg:hidden"></div>
<ul
role="list"
class="mt-4 flex justify-center gap-10 text-base font-medium leading-7 text-ctp-text sm:gap-8 lg:flex-col lg:gap-4"
>
<li class="flex">
<a
href="https://www.youtube.com/playlist?list=PLWtPciJ1UMuAyAER9ASVEDRIz0DUspOeZ"
class="group flex items-center"
aria-label="YouTube Playlist"
>
<YouTubeIcon class="h-8 w-8 fill-slate-400 group-hover:fill-slate-600"/>
<span class="hidden sm:ml-3 sm:block">YouTube Playlist</span>
</a>
</li>
<li class="flex">
<a
href="https://github.com/rust-adventure/thisweekinbevy"
class="group flex items-center"
aria-label="GitHub Repo"
>
<GitHubIcon class="h-8 w-8 fill-slate-400 group-hover:fill-slate-600"/>
<span class="hidden sm:ml-3 sm:block">GitHub Repo</span>
</a>
</li>
<li class="flex">
<a
href="https://thisweekinbevy.com/feed.xml"
class="group flex items-center"
aria-label="Atom Feed"
>
<RSSIcon class="h-8 w-8 fill-white group-hover:fill-white"/>
<span class="hidden sm:ml-3 sm:block">Atom Feed</span>
</a>
</li>
</ul>
</section>
</div>
</header>
<main class="border-t border-ctp-crust lg:relative lg:mb-28 lg:ml-112 lg:border-t-0 xl:ml-120">
// <Waveform class="absolute left-0 top-0 h-20 w-full" />
<div class="relative">{children()}</div>
</main>
<footer class="border-t border-ctp-crust bg-ctp-mantle py-10 pb-40 sm:py-16 sm:pb-32 lg:hidden">
<div class="mx-auto px-4 sm:px-6 md:max-w-2xl md:px-4">
<AboutSection/>
<h2 class="mt-8 flex items-center font-mono text-sm font-medium leading-7 text-ctp-text">
<PersonIcon class="h-3 w-auto fill-slate-300"/>
<span class="ml-2.5">Curated by</span>
</h2>
<div class="mt-2 flex gap-6 text-sm font-bold leading-7 text-ctp-text">
{mntnrs}
</div>
</div>
</footer>
// <AudioPlayer />
<div class="fixed inset-x-0 bottom-0 z-10 lg:left-112 xl:left-120"></div>
</div>
}
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/session_store.rs | src/session_store.rs | use async_trait::async_trait;
use sqlx::MySqlPool;
use time::OffsetDateTime;
use tower_sessions_core::{
session::{Id, Record},
session_store, ExpiredDeletion, SessionStore,
};
/// A MySQL session store.
#[derive(Clone, Debug)]
pub struct MySqlStore {
pool: MySqlPool,
}
impl MySqlStore {
pub fn new(pool: MySqlPool) -> Self {
Self { pool }
}
}
#[async_trait]
impl ExpiredDeletion for MySqlStore {
async fn delete_expired(
&self,
) -> session_store::Result<()> {
sqlx::query("DELETE FROM session WHERE expiry_date < utc_timestamp()")
.execute(&self.pool)
.await
.map_err(SqlxStoreError::Sqlx)?;
Ok(())
}
}
#[async_trait]
impl SessionStore for MySqlStore {
async fn save(
&self,
record: &Record,
) -> session_store::Result<()> {
let query = r#"
INSERT INTO session
(id, data, expiry_date) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
data = VALUES(data),
expiry_date = VALUES(expiry_date)
"#;
sqlx::query(query)
.bind(&record.id.to_string())
.bind(
rmp_serde::to_vec(&record)
.map_err(SqlxStoreError::Encode)?,
)
.bind(record.expiry_date)
.execute(&self.pool)
.await
.map_err(SqlxStoreError::Sqlx)?;
Ok(())
}
async fn load(
&self,
session_id: &Id,
) -> session_store::Result<Option<Record>> {
let data: Option<(Vec<u8>,)> = sqlx::query_as(
r#"SELECT data FROM session WHERE id = ? AND expiry_date > ?"#
)
.bind(session_id.to_string())
.bind(OffsetDateTime::now_utc())
.fetch_optional(&self.pool)
.await
.map_err(SqlxStoreError::Sqlx)?;
if let Some((data,)) = data {
Ok(Some(
rmp_serde::from_slice(&data)
.map_err(SqlxStoreError::Decode)?,
))
} else {
Ok(None)
}
}
async fn delete(
&self,
session_id: &Id,
) -> session_store::Result<()> {
sqlx::query(r#"delete from session where id = ?"#)
.bind(&session_id.to_string())
.execute(&self.pool)
.await
.map_err(SqlxStoreError::Sqlx)?;
Ok(())
}
}
// sqlx store error
/// An error type for SQLx stores.
#[derive(thiserror::Error, Debug)]
pub enum SqlxStoreError {
/// A variant to map `sqlx` errors.
#[error(transparent)]
Sqlx(#[from] sqlx::Error),
/// A variant to map `rmp_serde` encode
/// errors.
#[error(transparent)]
Encode(#[from] rmp_serde::encode::Error),
/// A variant to map `rmp_serde` decode
/// errors.
#[error(transparent)]
Decode(#[from] rmp_serde::decode::Error),
}
impl From<SqlxStoreError> for session_store::Error {
fn from(err: SqlxStoreError) -> Self {
match err {
SqlxStoreError::Sqlx(inner) => {
session_store::Error::Backend(
inner.to_string(),
)
}
SqlxStoreError::Decode(inner) => {
session_store::Error::Decode(
inner.to_string(),
)
}
SqlxStoreError::Encode(inner) => {
session_store::Error::Encode(
inner.to_string(),
)
}
}
}
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/lib.rs | src/lib.rs | #![recursion_limit = "256"]
pub mod app;
#[cfg(feature = "ssr")]
pub mod atom_feed;
#[cfg(feature = "ssr")]
pub mod auth;
pub mod error_template;
pub mod issue_date;
#[cfg(feature = "ssr")]
pub mod markdown;
#[cfg(feature = "ssr")]
pub mod oauth;
#[cfg(feature = "ssr")]
pub mod session_store;
pub mod sql;
#[cfg(feature = "ssr")]
pub mod state;
#[cfg(feature = "ssr")]
pub mod users;
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Username(pub String);
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
// use crate::app::*;
console_error_panic_hook::set_once();
// leptos::mount_to_body(App);
leptos::mount::hydrate_islands();
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/atom_feed.rs | src/atom_feed.rs | use crate::state::AppState;
use atom_syndication::*;
use axum::{
extract::State, http::header, response::IntoResponse,
};
use serde::{Deserialize, Serialize};
pub async fn atom_feed(
State(app_state): State<AppState>,
) -> impl IntoResponse {
use atom_syndication::Feed;
let issues: Vec<SqlIssueShort> = sqlx::query_as!(
SqlIssueShort,
r#"
SELECT
id,
slug,
issue_date,
display_name,
description,
youtube_id
FROM issue
WHERE status = "publish"
ORDER BY status, issue_date DESC
LIMIT 5"#
)
.fetch_all(&app_state.pool)
.await
.unwrap();
let issues: Vec<IssueShort> =
issues.into_iter().map(IssueShort::from).collect();
let mut newest_issue_date = None;
let entries: Vec<Entry> = issues.into_iter().filter_map(|issue| {
let date = issue.issue_date.and_then(|v| {
use atom_syndication::FixedDateTime;
use std::str::FromStr;
FixedDateTime::from_str(&format!("{v}T12:30:00Z")).ok()
})?;
if Some(date) > newest_issue_date {
newest_issue_date = Some(date);
};
Some( EntryBuilder::default()
.title(issue.display_name.clone())
.id(format!("https://thisweekinbevy.com/issue/{}", issue.slug))
.updated(date)
.author(
Person {
name: "Chris Biscardi".to_string(),
email: None,
uri: Some("https://www.christopherbiscardi.com/".to_string())
})
.link( Link {
href: format!("https://thisweekinbevy.com/issue/{}", issue.slug),
rel: "alternate".to_string(),
hreflang: Some("en".to_string()),
mime_type: Some("text/html".to_string()),
title: Some(issue.display_name),
length: None,
})
.published(date)
.summary(Some(Text{
value: issue.description,
base: None,
lang: None,
r#type: TextType::Html,
}))
.content(Some(Content {
base: None,
lang: Some("en".to_string()),
value: None,
src: Some(format!("https://thisweekinbevy.com/issue/{}", issue.slug)),
content_type: Some("text/html".to_string()),
})).build())
}).collect();
let mut feed = Feed::default();
feed.set_id("https://thisweekinbevy.com/".to_string());
feed.set_updated(newest_issue_date.expect("having an issue should mean there is a most recent date"));
feed.set_title("This Week in Bevy");
feed
.set_logo("https://res.cloudinary.com/dilgcuzda/image/upload/v1708481576/thisweekinbevy/this-week-in-bevylight_uddwes.avif".to_string());
feed.set_icon(
"https://cdn.thisweekinbevy.com/favicon-32x32.png"
.to_string(),
);
feed.set_authors(vec![Person {
name: "Chris Biscardi".to_string(),
email: None,
uri: Some(
"https://www.christopherbiscardi.com/"
.to_string(),
),
}]);
feed.set_links(vec![Link {
href: "https://thisweekinbevy.com".to_string(),
rel: "alternate".to_string(),
hreflang: Some("en".to_string()),
mime_type: Some("text/html".to_string()),
title: Some("This Week in Bevy".to_string()),
length: None,
}]);
feed
.set_subtitle(Text::from("What happened this week in the Bevy Engine ecosystem"));
feed.set_entries(entries);
let headers = [(
header::CONTENT_TYPE,
"application/atom+xml; charset=utf-8".to_string(),
)];
(headers, feed.to_string())
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlIssueShort {
pub id: Vec<u8>,
pub slug: String,
pub issue_date: Option<time::Date>,
pub display_name: String,
pub description: String,
pub youtube_id: String,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct IssueShort {
pub id: String,
pub slug: String,
pub issue_date: Option<time::Date>,
pub display_name: String,
pub description: String,
pub youtube_id: String,
}
#[cfg(feature = "ssr")]
impl From<SqlIssueShort> for IssueShort {
fn from(value: SqlIssueShort) -> Self {
use crate::markdown::compile;
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
IssueShort {
id: id_str.to_string(),
slug: value.slug,
issue_date: value.issue_date,
display_name: value.display_name,
description: compile(&value.description),
youtube_id: value.youtube_id,
}
}
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/state.rs | src/state.rs | use axum::extract::FromRef;
use leptos::prelude::LeptosOptions;
use leptos_axum::AxumRouteListing;
// use leptos_router::RouteListing;
use sqlx::MySqlPool;
/// This takes advantage of Axum's SubStates
/// feature by deriving FromRef. This is the only
/// way to have more than one item in Axum's
/// State. Leptos requires you to have
/// leptosOptions in your State struct for the
/// leptos route handlers
#[derive(FromRef, Debug, Clone)]
pub struct AppState {
pub leptos_options: LeptosOptions,
pub pool: MySqlPool,
pub routes: Vec<AxumRouteListing>,
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/sql.rs | src/sql.rs | use leptos::prelude::*;
use serde::{Deserialize, Serialize};
#[cfg(feature = "ssr")]
use sqlx::MySqlPool;
#[cfg(feature = "ssr")]
use std::time::Duration;
#[cfg(feature = "ssr")]
use crate::Username;
#[cfg(feature = "ssr")]
pub fn pool() -> Result<MySqlPool, ServerFnError> {
use_context::<MySqlPool>().ok_or_else(|| {
ServerFnError::ServerError("Pool missing.".into())
})
}
#[cfg(feature = "ssr")]
pub fn with_admin_access() -> Result<Username, ServerFnError>
{
let Some(Username(username)) =
use_context::<Option<crate::Username>>().flatten()
else {
return Err(ServerFnError::ServerError(
"not allowed to submit via admin panel"
.to_string(),
));
};
if username != "ChristopherBiscardi" {
return Err(ServerFnError::ServerError(
"not allowed to submit via admin panel"
.to_string(),
));
}
Ok(Username(username))
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlPullRequestInfo {
github_id: String,
url: String,
title: String,
author: String,
author_url: String,
labels: serde_json::Value,
merged_at_date: Option<time::Date>,
}
#[derive(Debug, Deserialize)]
struct LabelInfo {
name: String,
color: String,
}
#[server]
pub async fn get_merged_pull_requests(
date: time::Date,
) -> Result<Vec<ClientPullRequestInfo>, ServerFnError> {
let pool = pool()?;
// one week
let start_date =
date - Duration::from_secs(60 * 60 * 24 * 7);
let results: Vec<SqlPullRequestInfo> = sqlx::query_as!(
SqlPullRequestInfo,
"SELECT
github_id,
url,
title,
author,
author_url,
labels,
merged_at_date
FROM merged_pull_request
WHERE merged_at_date BETWEEN ? AND ?
ORDER BY merged_at_date DESC",
Some(start_date),
Some(date),
)
.fetch_all(&pool)
.await?;
// dbg!(results);
Ok(results
.into_iter()
.map(ClientPullRequestInfo::from)
.collect())
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ClientPullRequestInfo {
pub github_id: String,
pub url: String,
pub title: String,
pub author: String,
pub author_url: String,
pub labels: serde_json::Value,
pub merged_at_date: String,
}
#[cfg(feature = "ssr")]
impl From<SqlPullRequestInfo> for ClientPullRequestInfo {
fn from(value: SqlPullRequestInfo) -> Self {
ClientPullRequestInfo {
github_id: value.github_id,
url: value.url,
title: value.title,
author: value.author,
author_url: value.author_url,
labels: value.labels,
merged_at_date: value
.merged_at_date
.expect("a date, because the query was for valid date ranges")
.format(&crate::issue_date::ISSUE_DATE_FORMAT)
.expect("a valid format"),
}
}
}
// OpenedPullRequests
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlOpenedPullRequestInfo {
github_id: String,
url: String,
title: String,
author: String,
author_url: String,
labels: serde_json::Value,
gh_created_at: Option<time::Date>,
}
#[server]
pub async fn get_opened_pull_requests(
date: time::Date,
) -> Result<Vec<ClientOpenedPullRequestInfo>, ServerFnError>
{
let pool = pool()?;
// one week
let start_date =
date - Duration::from_secs(60 * 60 * 24 * 7);
let results: Vec<SqlOpenedPullRequestInfo> =
sqlx::query_as!(
SqlOpenedPullRequestInfo,
"SELECT
github_id,
url,
title,
author,
author_url,
labels,
gh_created_at
FROM new_pull_request
WHERE gh_created_at BETWEEN ? AND ?
ORDER BY gh_created_at DESC",
Some(start_date),
Some(date),
)
.fetch_all(&pool)
.await?;
Ok(results
.into_iter()
.map(ClientOpenedPullRequestInfo::from)
.collect())
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ClientOpenedPullRequestInfo {
pub github_id: String,
pub url: String,
pub title: String,
pub author: String,
pub author_url: String,
pub labels: serde_json::Value,
pub gh_created_at: String,
}
#[cfg(feature = "ssr")]
impl From<SqlOpenedPullRequestInfo>
for ClientOpenedPullRequestInfo
{
fn from(value: SqlOpenedPullRequestInfo) -> Self {
ClientOpenedPullRequestInfo {
github_id: value.github_id,
url: value.url,
title: value.title,
author: value.author,
author_url: value.author_url,
labels: value.labels,
gh_created_at: value
.gh_created_at
.expect("a date, because the query was for valid date ranges")
.format(&crate::issue_date::ISSUE_DATE_FORMAT)
.expect("a valid format"),
}
}
}
// Opened Issues
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlOpenedIssueInfo {
github_id: String,
url: String,
title: String,
author: String,
author_url: String,
labels: serde_json::Value,
gh_created_at: Option<time::Date>,
}
#[server]
pub async fn get_opened_issues(
date: time::Date,
) -> Result<Vec<ClientOpenedIssueInfo>, ServerFnError> {
let pool = pool()?;
// one week
let start_date =
date - Duration::from_secs(60 * 60 * 24 * 7);
let results: Vec<SqlOpenedIssueInfo> = sqlx::query_as!(
SqlOpenedIssueInfo,
"SELECT
github_id,
url,
title,
author,
author_url,
labels,
gh_created_at
FROM new_github_issue
WHERE gh_created_at BETWEEN ? AND ?
ORDER BY gh_created_at DESC",
Some(start_date),
Some(date),
)
.fetch_all(&pool)
.await?;
Ok(results
.into_iter()
.map(ClientOpenedIssueInfo::from)
.collect())
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ClientOpenedIssueInfo {
pub github_id: String,
pub url: String,
pub title: String,
pub author: String,
pub author_url: String,
pub labels: serde_json::Value,
pub gh_created_at: String,
}
#[cfg(feature = "ssr")]
impl From<SqlOpenedIssueInfo> for ClientOpenedIssueInfo {
fn from(value: SqlOpenedIssueInfo) -> Self {
ClientOpenedIssueInfo {
github_id: value.github_id,
url: value.url,
title: value.title,
author: value.author,
author_url: value.author_url,
labels: value.labels,
gh_created_at: value
.gh_created_at
.expect("a date, because the query was for valid date ranges")
.format(&crate::issue_date::ISSUE_DATE_FORMAT)
.expect("a valid format"),
}
}
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/oauth.rs | src/oauth.rs | use axum::{
extract::Query,
http::StatusCode,
response::{IntoResponse, Redirect},
routing::get,
Router,
};
use axum_login::tower_sessions::Session;
use oauth2::CsrfToken;
use serde::Deserialize;
use crate::{
auth::NEXT_URL_KEY,
state::AppState,
users::{AuthSession, Credentials},
};
pub const CSRF_STATE_KEY: &str = "oauth.csrf-state";
#[derive(Debug, Clone, Deserialize)]
pub struct AuthzResp {
code: String,
state: CsrfToken,
}
pub fn router() -> Router<AppState> {
Router::<AppState>::new().route(
"/oauth/callback",
get(self::get::callback),
)
}
mod get {
use tracing::instrument;
use super::*;
#[instrument(skip(auth_session, session))]
pub async fn callback(
mut auth_session: AuthSession,
session: Session,
Query(AuthzResp {
code,
state: new_state,
}): Query<AuthzResp>,
) -> impl IntoResponse {
let Ok(Some(old_state)) =
session.get(CSRF_STATE_KEY).await
else {
return StatusCode::BAD_REQUEST.into_response();
};
let creds = Credentials {
code,
old_state,
new_state,
};
let user = match auth_session
.authenticate(creds)
.await
{
Ok(Some(user)) => user,
Ok(None) => {
return (
StatusCode::UNAUTHORIZED,
"Invalid CSRF state", /* LoginTemplate {
* message: Some(
* "Invalid CSRF state."
*
* .to_string(),
*
* ),
* next: None,
* }, */
)
.into_response();
}
Err(_) => {
return StatusCode::INTERNAL_SERVER_ERROR
.into_response()
}
};
if auth_session.login(&user).await.is_err() {
return StatusCode::INTERNAL_SERVER_ERROR
.into_response();
}
if let Ok(Some(next)) =
session.remove::<String>(NEXT_URL_KEY).await
{
Redirect::to(&next).into_response()
} else {
Redirect::to("/").into_response()
}
}
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/users.rs | src/users.rs | use async_trait::async_trait;
use axum::http::header::{AUTHORIZATION, USER_AGENT};
use axum_login::{AuthUser, AuthnBackend, UserId};
use oauth2::{
basic::{BasicClient, BasicRequestTokenError},
reqwest::{async_http_client, AsyncHttpClientError},
url::Url,
AuthorizationCode, CsrfToken, TokenResponse,
};
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, MySqlPool};
use tracing::{error, instrument};
#[derive(Clone, Serialize, Deserialize, FromRow)]
pub struct User {
pub github_id: String,
pub username: String,
pub access_token: String,
}
// Here we've implemented `Debug` manually to
// avoid accidentally logging the access token.
impl std::fmt::Debug for User {
fn fmt(
&self,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
f.debug_struct("User")
// .field("github_id", &self.github_id)
.field("username", &self.username)
.field("access_token", &"[redacted]")
.finish()
}
}
impl AuthUser for User {
type Id = String;
fn id(&self) -> Self::Id {
self.github_id.to_string()
}
fn session_auth_hash(&self) -> &[u8] {
self.access_token.as_bytes()
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Credentials {
pub code: String,
pub old_state: CsrfToken,
pub new_state: CsrfToken,
}
#[derive(Debug, Deserialize)]
struct UserInfo {
id: u64,
login: String,
}
#[derive(Debug, thiserror::Error)]
pub enum BackendError {
#[error(transparent)]
Sqlx(sqlx::Error),
#[error(transparent)]
Reqwest(reqwest::Error),
#[error(transparent)]
OAuth2(BasicRequestTokenError<AsyncHttpClientError>),
}
#[derive(Debug, Clone)]
pub struct Backend {
db: MySqlPool,
client: BasicClient,
}
impl Backend {
#[instrument(skip(db, client))]
pub fn new(db: MySqlPool, client: BasicClient) -> Self {
Self { db, client }
}
#[instrument(skip(self))]
pub fn authorize_url(&self) -> (Url, CsrfToken) {
self.client
.authorize_url(CsrfToken::new_random)
.url()
}
}
#[async_trait]
impl AuthnBackend for Backend {
type User = User;
type Credentials = Credentials;
type Error = BackendError;
#[instrument(skip(self, creds), err)]
async fn authenticate(
&self,
creds: Self::Credentials,
) -> Result<Option<Self::User>, Self::Error> {
// Ensure the CSRF state has not been tampered
// with.
if creds.old_state.secret()
!= creds.new_state.secret()
{
return Ok(None);
};
// Process authorization code, expecting a token
// response back.
let token_res = self
.client
.exchange_code(AuthorizationCode::new(
creds.code,
))
.request_async(async_http_client)
.await
.inspect_err(|v| {
error!(?v);
})
.map_err(Self::Error::OAuth2)?;
// Use access token to request user info.
let user_info = reqwest::Client::new()
.get("https://api.github.com/user")
.header(
USER_AGENT.as_str(),
"this-week-in-bevy",
) // See: https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#user-agent-required
.header(
AUTHORIZATION.as_str(),
format!(
"Bearer {}",
token_res.access_token().secret()
),
)
.send()
.await
.map_err(Self::Error::Reqwest)?
.json::<UserInfo>()
.await
.map_err(Self::Error::Reqwest)?;
// Persist user in our database so we can use
// `get_user`.
let _num_rows_affected = sqlx::query(
r#"
insert into github_users (github_id, username, access_token)
values (?, ?, ?)
ON DUPLICATE KEY
UPDATE access_token = ?;
"#,
)
.bind(&user_info.id.to_string())
.bind(&user_info.login)
.bind(token_res.access_token().secret())
.bind(token_res.access_token().secret())
.execute(&self.db)
.await
.map_err(Self::Error::Sqlx)?;
let user = sqlx::query_as(
r#"
SELECT * FROM github_users
WHERE username = ?;"#,
)
.bind(user_info.login)
.fetch_one(&self.db)
.await
.map_err(Self::Error::Sqlx)?;
Ok(Some(user))
}
#[instrument(skip(self))]
async fn get_user(
&self,
user_id: &UserId<Self>,
) -> Result<Option<Self::User>, Self::Error> {
Ok(sqlx::query_as(
"select * from github_users where github_id = ?",
)
.bind(user_id)
.fetch_optional(&self.db)
.await
.map_err(Self::Error::Sqlx)?)
}
}
// We use a type alias for convenience.
//
// Note that we've supplied our concrete backend
// here.
pub type AuthSession = axum_login::AuthSession<Backend>;
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/auth.rs | src/auth.rs | use axum::{
http::StatusCode,
response::{IntoResponse, Redirect},
routing::{get, post},
Form, Router,
};
use axum_login::tower_sessions::Session;
use serde::Deserialize;
use crate::{
oauth::CSRF_STATE_KEY, state::AppState,
users::AuthSession,
};
pub const NEXT_URL_KEY: &str = "auth.next-url";
// This allows us to extract the "next" field from
// the query string. We use this to redirect after
// log in.
#[derive(Debug, Deserialize)]
pub struct NextUrl {
next: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Credentials {
pub client_id: String,
pub client_secret: String,
}
pub fn router() -> Router<AppState> {
Router::<AppState>::new()
.route("/login", post(self::post::login))
.route("/logout", get(self::get::logout))
}
mod post {
use tracing::instrument;
use super::*;
#[instrument]
pub async fn login(
auth_session: AuthSession,
session: Session,
Form(NextUrl { next }): Form<NextUrl>,
) -> impl IntoResponse {
let (auth_url, csrf_state) =
auth_session.backend.authorize_url();
session
.insert(CSRF_STATE_KEY, csrf_state.secret())
.await
.expect("Serialization should not fail.");
session
.insert(NEXT_URL_KEY, next)
.await
.expect("Serialization should not fail.");
Redirect::to(auth_url.as_str()).into_response()
}
}
mod get {
use tracing::instrument;
use super::*;
#[instrument]
pub async fn logout(
mut auth_session: AuthSession,
) -> impl IntoResponse {
match auth_session.logout().await {
Ok(_) => Redirect::to("/login").into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR
.into_response(),
}
}
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/markdown.rs | src/markdown.rs | #[cfg(feature = "ssr")]
use comrak::plugins::syntect::SyntectAdapterBuilder;
#[cfg(feature = "ssr")]
use comrak::{
markdown_to_html_with_plugins, ComrakPlugins, Options,
};
use leptos::prelude::*;
#[cfg(feature = "ssr")]
use std::io::Cursor;
#[cfg(feature = "ssr")]
use syntect::highlighting::ThemeSet;
#[cfg(feature = "ssr")]
const NIGHT_OWL: &[u8; 27913] =
include_bytes!("../night-owlish.tmtheme");
#[cfg(feature = "ssr")]
pub fn compile(input: &str) -> String {
// let adapter = SyntectAdapter::new("Solarized
// (dark)");
let mut cursor = Cursor::new(NIGHT_OWL);
let theme_night_owl =
ThemeSet::load_from_reader(&mut cursor)
.expect("expect markdown theme to be loadable");
let mut theme_set = ThemeSet::new();
theme_set
.themes
.entry("Night Owl".to_string())
.or_insert(theme_night_owl);
// let theme_set = ;
let adapter = SyntectAdapterBuilder::new()
.theme_set(theme_set)
.theme("Night Owl")
.build();
let mut plugins = ComrakPlugins::default();
plugins.render.codefence_syntax_highlighter =
Some(&adapter);
let mut options = Options::default();
// UNSAFE HTML TAGS!
options.render.unsafe_ = true;
// extensions, like those on github
options.extension.strikethrough = true;
options.extension.tagfilter = true;
options.extension.table = true;
options.extension.autolink = false;
options.extension.tasklist = true;
options.extension.superscript = true;
options.extension.header_ids = Some("".to_string());
options.extension.footnotes = true;
options.extension.description_lists = false;
options.extension.front_matter_delimiter = None;
options.extension.multiline_block_quotes = true;
markdown_to_html_with_plugins(input, &options, &plugins)
}
#[server(MarkdownCompileServer, "/api")]
pub async fn markdown_compile_server(
code: String,
) -> Result<String, ServerFnError> {
Ok(compile(&code))
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/error_template.rs | src/error_template.rs | use http::status::StatusCode;
use leptos::prelude::*;
use thiserror::Error;
#[derive(Clone, Debug, Error)]
pub enum AppError {
#[error("Not Found")]
NotFound,
}
impl AppError {
pub fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound => StatusCode::NOT_FOUND,
}
}
}
// A basic function to display errors served by
// the error boundaries. Feel free to do more
// complicated things here than just displaying
// the error.
#[component]
pub fn ErrorTemplate(
#[prop(optional)] outside_errors: Option<Errors>,
#[prop(optional)] errors: Option<RwSignal<Errors>>,
) -> impl IntoView {
let errors = match outside_errors {
Some(e) => create_rw_signal(e),
None => match errors {
Some(e) => e,
None => panic!(
"No Errors found and we expected errors!"
),
},
};
// Get Errors from Signal
let errors = errors.get_untracked();
// Downcast lets us take a type that implements
// `std::error::Error`
let errors: Vec<AppError> = errors
.into_iter()
.filter_map(|(_k, v)| {
v.downcast_ref::<AppError>().cloned()
})
.collect();
println!("Errors: {errors:#?}");
// Only the response code for the first error is
// actually sent from the server this may be
// customized by the specific application
#[cfg(feature = "ssr")]
{
use leptos_axum::ResponseOptions;
let response = use_context::<ResponseOptions>();
if let Some(response) = response {
response.set_status(errors[0].status_code());
}
}
view! {
<h1>{if errors.len() > 1 { "Errors" } else { "Error" }}</h1>
<For
// a function that returns the items we're iterating over; a signal is fine
each=move || { errors.clone().into_iter().enumerate() }
// a unique key for each item as a reference
key=|(index, _error)| *index
// renders each item to a view
children=move |error| {
let error_string = error.1.to_string();
let error_code = error.1.status_code();
view! {
<h2>{error_code.to_string()}</h2>
<p>"Error: " {error_string}</p>
}
}
/>
}
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/main.rs | src/main.rs | #![recursion_limit = "512"]
use axum::{
body::Body as AxumBody,
extract::{Path, State},
http::Request,
response::{IntoResponse, Response},
routing::get,
};
use axum_login::{
tower_sessions::{
cookie::SameSite, Expiry, SessionManagerLayer,
},
AuthManagerLayerBuilder,
};
use leptos::prelude::provide_context;
use leptos_axum::handle_server_fns_with_context;
use oauth2::{
basic::BasicClient, AuthUrl, ClientId, ClientSecret,
TokenUrl,
};
use sqlx::mysql::MySqlPoolOptions;
use std::env;
use this_week_in_bevy::{
app::{shell, App},
auth, oauth,
state::AppState,
users::Backend,
};
use this_week_in_bevy::{
session_store, users::AuthSession, Username,
};
use time::Duration;
#[tracing::instrument(skip(
app_state,
auth_session,
request
))]
async fn server_fn_handler(
State(app_state): State<AppState>,
path: Path<String>,
auth_session: AuthSession,
request: Request<AxumBody>,
) -> impl IntoResponse {
handle_server_fns_with_context(
move || {
provide_context(app_state.pool.clone());
provide_context(
auth_session.user.as_ref().map(|user| {
Username(user.username.clone())
}),
);
},
request,
)
.await
}
async fn leptos_routes_handler(
State(app_state): State<AppState>,
auth_session: AuthSession,
req: Request<AxumBody>,
) -> Response {
let state = app_state.clone();
let handler = leptos_axum::render_route_with_context(
app_state.routes.clone(),
move || {
provide_context(app_state.pool.clone());
provide_context(
auth_session.user.as_ref().map(|user| {
Username(user.username.clone())
}),
);
},
move || shell(app_state.leptos_options.clone()),
);
handler(State(state), req).await.into_response()
}
#[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::Router;
use config::get_configuration;
use leptos::*;
use leptos_axum::{
file_and_error_handler, generate_route_list,
LeptosRoutes,
};
use this_week_in_bevy::app::*;
// use this_week_in_bevy::fileserv::file_and_error_handler;
use tracing::warn;
tracing_subscriber::fmt::init();
let pool = MySqlPoolOptions::new()
.connect(
&env::var("DATABASE_URL")
.expect("DATABASE_URL must be set"),
)
.await
.expect("Could not make pool.");
let client_id = env::var("GITHUB_CLIENT_ID")
.map(ClientId::new)
.expect("GITHUB_CLIENT_ID should be provided.");
if client_id.starts_with("op://") {
warn!("GITHUB_CLIENT_ID starts with one password prefix. Did you use `op run`?")
}
let client_secret = env::var("GITHUB_CLIENT_SECRET")
.map(ClientSecret::new)
.expect("GITHUB_CLIENT_SECRET should be provided");
if client_id.starts_with("op://") {
warn!("GITHUB_CLIENT_SECRET starts with one password prefix. Did you use `op run`?")
}
let auth_url = AuthUrl::new(
"https://github.com/login/oauth/authorize"
.to_string(),
)
.expect("it to have worked :: authorize");
let token_url = TokenUrl::new(
"https://github.com/login/oauth/access_token"
.to_string(),
)
.expect("it to have worked :: access_token");
let client = BasicClient::new(
client_id,
Some(client_secret),
auth_url,
Some(token_url),
);
// Session layer.
//
// This uses `tower-sessions` to establish a layer
// that will provide the session as a request
// extension.
let session_store =
session_store::MySqlStore::new(pool.clone());
// a memory store would be instantiated like this
// let session_store = MemoryStore::default();
// migrations happen in `bin/migrate-sessions` as
// we don't do "live migrations".
// session_store.migrate().await?;
let session_layer =
SessionManagerLayer::new(session_store)
.with_secure(false)
.with_same_site(SameSite::Lax) // Ensure we send the cookie from the OAuth
// redirect.
.with_expiry(Expiry::OnInactivity(
Duration::days(1),
));
// Auth service.
//
// This combines the session layer with our
// backend to establish the auth service which
// will provide the auth session as a request
// extension.
let backend = Backend::new(pool.clone(), client);
let auth_layer = AuthManagerLayerBuilder::new(
backend,
session_layer,
)
.build();
// Setting get_configuration(None) means we'll be
// using cargo-leptos's env values
// For deployment these variables are:
// <https://github.com/leptos-rs/start-axum#executing-a-server-on-a-remote-machine-without-the-toolchain>
// Alternately a file can be specified such as
// Some("Cargo.toml") The file would need to
// be included with the executable when moved to
// deployment
let conf = get_configuration(None).unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
let routes = generate_route_list(App);
let app_state = AppState {
leptos_options,
pool: pool.clone(),
routes: routes.clone(),
};
// build our application with a route
let app = Router::new()
.route(
"/feed.xml",
get(this_week_in_bevy::atom_feed::atom_feed),
)
.route(
"/api/*fn_name",
get(server_fn_handler).post(server_fn_handler),
)
.leptos_routes_with_handler(
routes,
get(leptos_routes_handler),
)
// .leptos_routes(&leptos_options, routes, App)
.fallback(leptos_axum::file_and_error_handler::<
AppState,
_,
>(shell))
.merge(auth::router())
.merge(oauth::router())
.layer(auth_layer)
.with_state(app_state);
let listener =
tokio::net::TcpListener::bind(&addr).await.unwrap();
logging::log!("listening on http://{}", &addr);
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g.,
// Trunk for a purely client-side app
// see lib.rs for hydration function instead
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/issue_date.rs | src/issue_date.rs | use time::format_description::FormatItem;
use time::macros::format_description;
use time::Date;
pub const ISSUE_DATE_FORMAT: &[FormatItem<'_>] =
format_description!("[year]-[month]-[day]");
/// takes a "2024-02-12-some-slug" and returns the
/// date portion
pub fn parse_issue_date_from_slug(
input: &str,
) -> Option<time::Date> {
input.get(0..10).and_then(parse_issue_date)
}
/// takes a "2024-02-12" and returns the date
/// portion
pub fn parse_issue_date(input: &str) -> Option<time::Date> {
Date::parse(input, &ISSUE_DATE_FORMAT).ok()
}
#[cfg(test)]
mod tests {
use super::*;
use time::macros::date;
#[test]
fn can_parse_date_from_slug() {
let slug = "2024-02-12-some-slug";
assert_eq!(
Some(date!(2024 - 02 - 12)),
parse_issue_date_from_slug(slug)
);
}
#[test]
fn invalid_slug_does_not_parse() {
let slug = "2024-some-slug";
assert_eq!(None, parse_issue_date_from_slug(slug));
}
#[test]
fn can_parse_date() {
let slug = "2024-02-12";
assert_eq!(
Some(date!(2024 - 02 - 12)),
parse_issue_date(slug)
);
}
#[test]
fn invalid_date_does_not_parse() {
let slug = "2024";
assert_eq!(None, parse_issue_date(slug));
}
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/components.rs | src/app/components.rs | use leptos::prelude::*;
#[component]
pub fn AboutSection(
#[prop(into, default = "".to_string())] class: String,
) -> impl IntoView {
let (is_expanded, set_is_expanded) = signal(false);
view! {
<section class=class>
<h2 class="flex items-center font-mono text-sm font-medium leading-7 text-ctp-text">
<TinyWaveFormIcon
start_color="fill-violet-300"
end_color="fill-pink-300"
class="h-2.5 w-2.5"
/>
<span class="ml-2.5">About</span>
</h2>
<p class=move || {
format!(
"mt-2 text-base leading-7 text-ctp-text {}",
if is_expanded.get() { "lg:line-clamp-4" } else { "" },
)
}>
This Week in Bevy is a curated roundup covering week-to-week activity in the Bevy ecosystem
</p>
{move || {
is_expanded
.get()
.then_some(
view! {
<button
type="button"
class="mt-2 hidden text-sm font-bold leading-6 text-ctp-pink hover:text-pink-700 active:text-pink-900 lg:inline-block"
on:click=move |_| set_is_expanded(true)
>
Show more
</button>
},
)
}}
</section>
}
}
#[component]
pub fn Container(
#[prop(into, default = "".to_string())] class: String,
#[prop(optional, default = false)] center: bool,
children: Children,
) -> impl IntoView {
view! {
<div class=format!("lg:px-8 {class}")>
<div class=format!("lg:max-w-4xl {}", if center { "mx-auto" } else { "" })>
<div class="mx-auto px-4 sm:px-6 md:max-w-2xl md:px-4 lg:px-0">{children()}</div>
</div>
</div>
}
}
#[component]
pub fn TinyWaveFormIcon(
#[prop(into, default = "".to_string())]
start_color: String,
#[prop(into, default = "".to_string())]
end_color: String,
#[prop(into, default = "".to_string())] class: String,
) -> impl IntoView {
view! {
<svg aria-hidden="true" viewBox="0 0 10 10" class=class>
<path
d="M0 5a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v4a1 1 0 0 1-1 1H1a1 1 0 0 1-1-1V5Z"
class=start_color
></path>
<path
d="M6 1a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V1Z"
class=end_color
></path>
</svg>
}
}
#[component]
pub fn Divider(
#[prop(into)] title: String,
) -> impl IntoView {
view! {
<div class="relative mt-12 mb-6">
<div class="absolute inset-0 flex items-center" aria-hidden="true">
<div class="w-full border-t border-ctp-surface1"></div>
</div>
<div class="relative flex justify-center">
<span class="bg-ctp-base px-3 text-base font-semibold leading-6 text-ctp-text">
{title}
</span>
</div>
</div>
}
}
pub enum DescriptionColor {
Blue,
Pink,
Lavender,
Teal,
}
impl DescriptionColor {
fn border_y(&self) -> &str {
match self {
DescriptionColor::Blue => "border-y-ctp-blue",
DescriptionColor::Pink => "border-y-ctp-pink",
DescriptionColor::Lavender => {
"border-y-ctp-lavender"
}
DescriptionColor::Teal => "border-y-ctp-teal",
}
}
fn border_t(&self) -> &str {
match self {
DescriptionColor::Blue => "border-t-ctp-blue",
DescriptionColor::Pink => "border-t-ctp-pink",
DescriptionColor::Lavender => {
"border-t-ctp-lavender"
}
DescriptionColor::Teal => "border-t-ctp-teal",
}
}
}
#[component]
pub fn DividerWithDescription(
#[prop(into)] color: DescriptionColor,
#[prop(into)] title: String,
#[prop(into)] description: String,
) -> impl IntoView {
view! {
<div class=format!(
"mt-8 relative isolate overflow-hidden bg-ctp-base px-6 py-24 sm:py-32 lg:px-8 border-y-8 {}",
color.border_y(),
)>
<img
src="https://res.cloudinary.com/dilgcuzda/image/upload/c_scale,w_600/thisweekinbevy/01HTAXBQ8H38BYVD3VEXCKVDS4.avif"
loading="lazy"
alt=""
class="absolute inset-0 -z-10 w-full aspect-h-7 aspect-w-10 object-cover opacity-30 blur"
/>
<div class="mx-auto max-w-2xl text-center">
<h2 class="text-4xl py-4 font-black tracking-tight text-ctp-text sm:text-6xl rounded-t-xl bg-gradient-to-bl from-50% from-ctp-base to-ctp-crust -skew-y-3 border border-t-ctp-surface0 border-r-ctp-surface0 border-b-ctp-crust border-l-ctp-crust">
{title}
</h2>
<p class=format!(
"-mt-[20px] p-4 text-lg leading-8 text-ctp-text bg-gradient-to-bl from-50% from-ctp-base to-ctp-crust border-t-[40px] {}",
color.border_t(),
)>{description}</p>
</div>
</div>
}
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes.rs | src/app/routes.rs | use leptos::prelude::*;
pub mod admin;
pub mod custom;
pub mod index;
pub mod issue;
#[component]
fn PauseIcon(
#[prop(into, default = "".to_string())] class: String,
) -> impl IntoView {
view! {
<svg aria-hidden="true" viewBox="0 0 10 10" class=class>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M1.496 0a.5.5 0 0 0-.5.5v9a.5.5 0 0 0 .5.5H2.68a.5.5 0 0 0 .5-.5v-9a.5.5 0 0 0-.5-.5H1.496Zm5.82 0a.5.5 0 0 0-.5.5v9a.5.5 0 0 0 .5.5H8.5a.5.5 0 0 0 .5-.5v-9a.5.5 0 0 0-.5-.5H7.316Z"
></path>
</svg>
}
}
#[component]
fn PlayIcon(
#[prop(into, default = "".to_string())] class: String,
) -> impl IntoView {
view! {
<svg aria-hidden="true" viewBox="0 0 10 10" class=class>
<path d="M8.25 4.567a.5.5 0 0 1 0 .866l-7.5 4.33A.5.5 0 0 1 0 9.33V.67A.5.5 0 0 1 .75.237l7.5 4.33Z"></path>
</svg>
}
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/index.rs | src/app/routes/index.rs | use crate::app::components::Container;
use crate::app::issue::PROSE;
use leptos::{either::Either, prelude::*};
use leptos_meta::*;
use serde::{Deserialize, Serialize};
use std::ops::Not;
#[component]
fn PauseIcon(
#[prop(into, default = "".to_string())] class: String,
) -> impl IntoView {
view! {
<svg aria-hidden="true" viewBox="0 0 10 10" class=class>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M1.496 0a.5.5 0 0 0-.5.5v9a.5.5 0 0 0 .5.5H2.68a.5.5 0 0 0 .5-.5v-9a.5.5 0 0 0-.5-.5H1.496Zm5.82 0a.5.5 0 0 0-.5.5v9a.5.5 0 0 0 .5.5H8.5a.5.5 0 0 0 .5-.5v-9a.5.5 0 0 0-.5-.5H7.316Z"
></path>
</svg>
}
}
#[component]
fn PlayIcon(
#[prop(into, default = "".to_string())] class: String,
) -> impl IntoView {
view! {
<svg aria-hidden="true" viewBox="0 0 10 10" class=class>
<path d="M8.25 4.567a.5.5 0 0 1 0 .866l-7.5 4.33A.5.5 0 0 1 0 9.33V.67A.5.5 0 0 1 .75.237l7.5 4.33Z"></path>
</svg>
}
}
#[component]
fn IssueEntry(issue: IssueShort) -> impl IntoView {
let aria_labelledby =
format!("issue-{}-title", issue.id.clone());
let aria_labelledby2 = aria_labelledby.clone();
view! {
<article aria-labelledby=aria_labelledby2 class="py-10 sm:py-12">
<Container>
<div class="flex flex-col items-start">
<h2
id=aria_labelledby.clone()
class="mt-2 text-lg font-bold text-ctp-text"
>
<a href=format!("/issue/{}", issue.slug)>{issue.display_name.clone()}</a>
</h2>
<p class="order-first font-mono text-sm leading-7 text-ctp-text">
{issue.issue_date.map(|date| date.to_string()).unwrap_or("".to_string())}
</p>
<div
class=format!("mt-1 text-base leading-7 text-ctp-text {}", PROSE)
inner_html=issue.description.clone()
></div>
<div class="mt-4 flex items-center gap-4">
{issue
.youtube_id
.trim()
.is_empty()
.not()
.then_some(
view! {
<a
href=format!(
"https://youtube.com/watch?v={}",
issue.youtube_id,
)
class="flex items-center gap-x-3 text-sm font-bold leading-6 text-ctp-pink hover:text-pink-700 active:text-pink-900"
>
<PlayIcon class="h-2.5 w-2.5 fill-current"/>
<span aria-hidden="true">Watch</span>
</a>
<span
aria-hidden="true"
class="text-sm font-bold text-ctp-text"
>
/
</span>
},
)}
<a
href=format!("/issue/{}", issue.slug)
class="flex items-center text-sm font-bold leading-6 text-ctp-pink hover:text-pink-700 active:text-pink-900"
aria-label=format!("full issue for {}", issue.display_name)
>
Read issue...
</a>
</div>
</div>
</Container>
</article>
}
}
#[component]
pub fn Home() -> impl IntoView {
let issues = Resource::new_blocking(
move || {},
|_| fetch_issues(),
);
view! {
<div class="pb-12 sm:pb-4">
<Title text="This Week in the Bevy Game Engine"/>
<Meta
name="description"
content="What happened this week in the Bevy Game Engine ecosystem"
/>
<Link rel="canonical" href="https://thisweekinbevy.com"/>
<Meta property="og:type" content="website"/>
<Meta property="og:url" content="https://thisweekinbevy.com"/>
<Meta
property="og:image"
content="https://res.cloudinary.com/dilgcuzda/image/upload/v1708310121/thisweekinbevy/this-week-in-bevyopengraph-light_zwqzqz.png"
/>
<Meta name="twitter:card" content="summary_large_image"/>
<Meta name="twitter:creator" content="@chrisbiscardi"/>
<Meta name="twitter:title" content="This Week in the Bevy Game Engine"/>
<Meta
name="twitter:description"
content="What happened this week in the Bevy Game Engine ecosystem"
/>
<Meta
name="twitter:image"
content="https://res.cloudinary.com/dilgcuzda/image/upload/v1708310121/thisweekinbevy/this-week-in-bevyopengraph-light_zwqzqz.png"
/>
<div class="pt-16 lg:pt-12 pb-4 lg:pb-8 bg-gradient-to-r from-ctp-mantle to-ctp-base">
<Container>
<h1 class="text-2xl font-bold leading-7 text-ctp-text">Issues</h1>
</Container>
</div>
<Suspense fallback=move || {
view! { <p>"Loading..."</p> }
}>
{move || {
issues
.get()
.map(|data| match data {
Err(_e) => Either::Left(view! { <div></div> }),
Ok(issues) => {
Either::Right(view! {
<div class="divide-y-4 divide-ctp-mantle lg:border-y-4 lg:border-ctp-mantle">
{issues
.into_iter()
.map(|issue| view! { <IssueEntry issue=issue/> })
.collect::<Vec<_>>()}
</div>
})
}
})
}}
</Suspense>
</div>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlIssueShort {
pub id: Vec<u8>,
pub slug: String,
pub issue_date: Option<time::Date>,
pub display_name: String,
pub description: String,
pub youtube_id: String,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct IssueShort {
pub id: String,
pub slug: String,
pub issue_date: Option<time::Date>,
pub display_name: String,
pub description: String,
pub youtube_id: String,
}
#[cfg(feature = "ssr")]
fn markdown_trim(input: &str) -> nom::IResult<&str, &str> {
use nom::{
character::complete::{anychar, line_ending},
combinator::consumed,
multi::many_till,
sequence::{pair, tuple},
};
let (input, (intro, _)) = consumed(tuple((
many_till(anychar, pair(line_ending, line_ending)),
many_till(anychar, pair(line_ending, line_ending)),
many_till(anychar, pair(line_ending, line_ending)),
)))(input)?;
Ok((input, intro))
}
#[cfg(feature = "ssr")]
impl From<SqlIssueShort> for IssueShort {
fn from(value: SqlIssueShort) -> Self {
use crate::markdown::compile;
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
let summary = markdown_trim(&value.description)
.map(|(_, output)| output)
.unwrap_or(&value.description);
IssueShort {
id: id_str.to_string(),
slug: value.slug,
issue_date: value.issue_date,
display_name: value.display_name,
description: compile(summary),
youtube_id: value.youtube_id,
}
}
}
#[server]
pub async fn fetch_issues(
) -> Result<Vec<IssueShort>, ServerFnError> {
let pool = crate::sql::pool()?;
let issues: Vec<SqlIssueShort> =
match crate::sql::with_admin_access() {
Ok(_) => {
// logged in as admin, serve all issues
sqlx::query_as!(
SqlIssueShort,
"
SELECT
id,
slug,
issue_date,
display_name,
description,
youtube_id
FROM issue
ORDER BY status, issue_date DESC"
)
.fetch_all(&pool)
.await?
}
Err(_) => {
// not logged in, serve issues that
sqlx::query_as!(
SqlIssueShort,
r#"
SELECT
id,
slug,
issue_date,
display_name,
description,
youtube_id
FROM issue
WHERE status = "publish"
ORDER BY status, issue_date DESC"#
)
.fetch_all(&pool)
.await?
}
};
Ok(issues.into_iter().map(IssueShort::from).collect())
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/admin.rs | src/app/routes/admin.rs | use leptos::prelude::*;
use leptos_router::components::{Outlet, A};
pub mod crate_release;
pub mod devlog;
pub mod educational;
pub mod github;
pub mod image;
pub mod issue;
pub mod issues;
pub mod showcase;
#[component]
pub fn AdminHomepage() -> impl IntoView {
view! {
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<h2 class="text-base font-semibold leading-6 text-gray-900">Admin Home</h2>
<p class="mt-1 text-sm text-gray-500">"Create an object for the newsletter."</p>
<ul
role="list"
class="mt-6 grid grid-cols-1 gap-6 border-b border-t border-gray-200 py-6 sm:grid-cols-2"
>
<li class="flow-root">
<div class="relative -m-2 flex items-center space-x-4 rounded-xl p-2 focus-within:ring-2 focus-within:ring-indigo-500 hover:bg-gray-50">
<div class="flex h-16 w-16 flex-shrink-0 items-center justify-center rounded-lg bg-yellow-500">
<svg
class="h-6 w-6 text-white"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5"
></path>
</svg>
</div>
<div>
<h3 class="text-sm font-medium text-gray-900">
<a href="/admin/showcase" class="focus:outline-none">
<span class="absolute inset-0" aria-hidden="true"></span>
<span>Create a Showcase</span>
<span aria-hidden="true">" →"</span>
</a>
</h3>
<p class="mt-1 text-sm text-gray-500">
"Showcases show off what the community is doing with Bevy."
</p>
</div>
</div>
</li>
<li class="flow-root">
<div class="relative -m-2 flex items-center space-x-4 rounded-xl p-2 focus-within:ring-2 focus-within:ring-indigo-500 hover:bg-gray-50">
<div class="flex h-16 w-16 flex-shrink-0 items-center justify-center rounded-lg bg-green-500">
<svg
class="h-6 w-6 text-white"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V8.25zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z"
></path>
</svg>
</div>
<div>
<h3 class="text-sm font-medium text-gray-900">
<a href="/admin/crate_release" class="focus:outline-none">
<span class="absolute inset-0" aria-hidden="true"></span>
<span>Create a Crate Release</span>
<span aria-hidden="true">" →"</span>
</a>
</h3>
<p class="mt-1 text-sm text-gray-500">
"Crate Releases can be automated, but sometimes there's new updates."
</p>
</div>
</div>
</li>
<li class="flow-root">
<div class="relative -m-2 flex items-center space-x-4 rounded-xl p-2 focus-within:ring-2 focus-within:ring-indigo-500 hover:bg-gray-50">
<div class="flex h-16 w-16 flex-shrink-0 items-center justify-center rounded-lg bg-blue-500">
<svg
class="h-6 w-6 text-white"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M9 4.5v15m6-15v15m-10.875 0h15.75c.621 0 1.125-.504 1.125-1.125V5.625c0-.621-.504-1.125-1.125-1.125H4.125C3.504 4.5 3 5.004 3 5.625v12.75c0 .621.504 1.125 1.125 1.125z"
></path>
</svg>
</div>
<div>
<h3 class="text-sm font-medium text-gray-900">
<a href="/admin/devlog" class="focus:outline-none">
<span class="absolute inset-0" aria-hidden="true"></span>
<span>Create a Devlog</span>
<span aria-hidden="true">" →"</span>
</a>
</h3>
<p class="mt-1 text-sm text-gray-500">
"Devlogs track what the community is building over a longer series of time."
</p>
</div>
</div>
</li>
<li class="flow-root">
<div class="relative -m-2 flex items-center space-x-4 rounded-xl p-2 focus-within:ring-2 focus-within:ring-indigo-500 hover:bg-gray-50">
<div class="flex h-16 w-16 flex-shrink-0 items-center justify-center rounded-lg bg-indigo-500">
<svg
class="h-6 w-6 text-white"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M3.375 19.5h17.25m-17.25 0a1.125 1.125 0 01-1.125-1.125M3.375 19.5h7.5c.621 0 1.125-.504 1.125-1.125m-9.75 0V5.625m0 12.75v-1.5c0-.621.504-1.125 1.125-1.125m18.375 2.625V5.625m0 12.75c0 .621-.504 1.125-1.125 1.125m1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125m0 3.75h-7.5A1.125 1.125 0 0112 18.375m9.75-12.75c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125m19.5 0v1.5c0 .621-.504 1.125-1.125 1.125M2.25 5.625v1.5c0 .621.504 1.125 1.125 1.125m0 0h17.25m-17.25 0h7.5c.621 0 1.125.504 1.125 1.125M3.375 8.25c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125m17.25-3.75h-7.5c-.621 0-1.125.504-1.125 1.125m8.625-1.125c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125m-17.25 0h7.5m-7.5 0c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125M12 10.875v-1.5m0 1.5c0 .621-.504 1.125-1.125 1.125M12 10.875c0 .621.504 1.125 1.125 1.125m-2.25 0c.621 0 1.125.504 1.125 1.125M13.125 12h7.5m-7.5 0c-.621 0-1.125.504-1.125 1.125M20.625 12c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125m-17.25 0h7.5M12 14.625v-1.5m0 1.5c0 .621-.504 1.125-1.125 1.125M12 14.625c0 .621.504 1.125 1.125 1.125m-2.25 0c.621 0 1.125.504 1.125 1.125m0 1.5v-1.5m0 0c0-.621.504-1.125 1.125-1.125m0 0h7.5"
></path>
</svg>
</div>
<div>
<h3 class="text-sm font-medium text-gray-900">
<a href="/admin/educational" class="focus:outline-none">
<span class="absolute inset-0" aria-hidden="true"></span>
<span>Create an Educational</span>
<span aria-hidden="true">" →"</span>
</a>
</h3>
<p class="mt-1 text-sm text-gray-500">
"Educationals teach people how to do things with Bevy."
</p>
</div>
</div>
</li>
</ul>
<div class="mt-4 flex">
<a
href="/admin/issue"
class="text-sm font-medium text-indigo-600 hover:text-indigo-500"
>
Or create a new draft issue
<span aria-hidden="true">" →"</span>
</a>
</div>
</div>
}
}
#[component]
pub fn AdminWrapper() -> impl IntoView {
view! {
<div>
<header>
<nav class="flex overflow-x-auto border-b border-white/10 py-4">
<ul
role="list"
class="flex min-w-full flex-none gap-x-6 px-4 text-sm font-semibold leading-6 text-gray-600 sm:px-6 lg:px-8"
>
<li>
<A href="/admin" exact=true attr:class="active:text-blue-600">
Home
</A>
</li>
<li>
<A href="/admin/issue" exact=true attr:class="active:text-blue-600">
Issue
</A>
</li>
<li>
<A href="/admin/showcase" exact=true attr:class="active:text-blue-600">
Showcase
</A>
</li>
<li>
<A href="/admin/crate_release" exact=true attr:class="active:text-blue-600">
Crate Release
</A>
</li>
<li>
<A href="/admin/devlog" exact=true attr:class="active:text-blue-600">
Devlog
</A>
</li>
<li>
<A href="/admin/educational" attr:class="active:text-blue-600">
Educational
</A>
</li>
<li>
<A href="/admin/images" attr:class="active:text-blue-600">
Images
</A>
</li>
<li>
<A href="/admin/github" attr:class="active:text-blue-600">
GitHub
</A>
</li>
</ul>
</nav>
</header>
<Outlet/>
</div>
}
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/issue.rs | src/app/routes/issue.rs | use crate::app::components::{
Container, DescriptionColor, Divider,
DividerWithDescription,
};
use itertools::Itertools;
use leptos::{either::{Either, EitherOf4}, prelude::*};
use leptos_meta::*;
use leptos_router::hooks::use_params_map;
use serde::{Deserialize, Serialize};
#[cfg(feature = "ssr")]
use sqlx::types::Json;
use std::ops::Not;
mod cards;
use cards::*;
pub const PROSE: &str = r#"prose text-ctp-text dark:prose-strong:text-white prose-code:text-ctp-text prose-a:text-ctp-sky hover:prose-a:text-ctp-blue prose-blockquote:text-ctp-text [&>h2]:leading-7 [&>h2]:text-ctp-text [&>h3]:text-ctp-text [&>h2]:pl-4 [&>ul]:mt-6 [&>ul]:list-['⮡\20'] [&>ul]:pl-5"#;
#[derive(Clone, Serialize, Deserialize)]
pub struct Issue {
/// The title of the issue is technically the
/// date in yyyy-mm-dd format, but this field
/// is a human-readable string that goes in
/// the email subject line and slug url
title: String,
slug: String,
opengraph_image: String,
header_image: String,
youtube_id: String,
issue_date: time::Date,
/// What is this issue about? Is there
/// anything notable worth mentioning or
/// making sure people are aware of?
description: String,
/// Showcase what people are doing with Bevy
/// this week. Often these are in-progress
/// games, experimental rendering approaches,
/// or other in-progress bevy work
showcases: Vec<Showcase>,
/// Crates that have been released in the last
/// week. This includes updates and new
/// releases
crate_releases: Vec<CrateRelease>,
/// merged pull requests
/// Meant to convey what is being added to
/// Bevy
merged_pull_requests: Vec<MergedPullRequest>,
/// educational resources published this week.
/// videos and blog posts
educationals: Vec<Educational>,
/// devlogs published this week.
/// videos and blog posts
devlogs: Vec<Devlog>,
/// newsletter contributors
/// (not a list of people that contribute to
/// the bevy repo itself, that exists in the
/// Bevy release announcements already)
contributors: Vec<Contributor>,
/// Want to contribute? check out these
/// pull requests that need review
new_pull_requests: Vec<NewPullRequest>,
/// Want to contribute? check out these
/// issues that just got opened
new_github_issues: Vec<NewIssue>,
}
/// `NewPullRequest` is calculated just before
/// publishing each issue. It is a stateful
/// representation of new pull requests that were
/// opened this week (and still open when the
/// issue is published), with the intent of
/// providing This Week in Bevy readers the
/// opportunity to discover pull requests that
/// could benefit from review this week.
#[derive(Clone, Serialize, Deserialize)]
struct NewPullRequest {
github_id: String,
title: String,
url: String,
gh_created_at: String,
author: String,
author_url: String,
}
/// `NewIssue` is calculated just before
/// publishing each issue. It is a stateful
/// representation of new issues that were
/// opened this week (and still open when the
/// issue is published), with the intent of
/// providing This Week in Bevy readers the
/// opportunity to discover issues that
/// could benefit from reproduction cases and
/// other fixes.
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct NewIssue {
title: String,
url: String,
github_created_at: String,
author: String,
author_url: String,
}
#[cfg(feature = "ssr")]
#[derive(
Debug,
serde::Deserialize,
serde::Serialize,
sqlx::FromRow,
)]
struct SqlNewGhIssue {
title: String,
url: String,
gh_created_at: String,
author: String,
author_url: String,
}
#[cfg(feature = "ssr")]
#[derive(
Debug,
serde::Deserialize,
serde::Serialize,
sqlx::FromRow,
)]
struct SqlNewPr {
github_id: String,
title: String,
url: String,
gh_created_at: String,
author: String,
author_url: String,
}
#[derive(Clone, Serialize, Deserialize)]
struct CrateRelease {
title: String,
url: String,
discord_url: String,
description: String,
posted_date: Option<String>,
images: Vec<ImgDataTransformed>,
}
#[cfg(feature = "ssr")]
#[derive(
Debug,
serde::Deserialize,
serde::Serialize,
sqlx::FromRow,
)]
struct SqlCrateRelease {
title: String,
url: String,
discord_url: String,
description: String,
posted_date: Option<String>,
images: Option<Vec<ImgData>>,
}
#[derive(Clone, Serialize, Deserialize)]
struct Devlog {
title: String,
post_url: String,
video_url: String,
discord_url: String,
description: String,
images: Vec<ImgDataTransformed>,
}
#[cfg(feature = "ssr")]
#[derive(
Debug,
serde::Deserialize,
serde::Serialize,
sqlx::FromRow,
)]
struct SqlDevlog {
title: String,
post_url: String,
video_url: String,
discord_url: String,
description: String,
images: Option<Vec<ImgData>>,
}
#[derive(Clone, Serialize, Deserialize)]
struct Educational {
title: String,
post_url: String,
video_url: String,
discord_url: String,
description: String,
images: Vec<ImgDataTransformed>,
}
#[cfg(feature = "ssr")]
#[derive(
Debug,
serde::Deserialize,
serde::Serialize,
sqlx::FromRow,
)]
struct SqlEducational {
title: String,
post_url: String,
video_url: String,
discord_url: String,
description: String,
images: Option<Vec<ImgData>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Showcase {
title: String,
url: String,
discord_url: String,
description: String,
images: Vec<ImgDataTransformed>,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct MergedPullRequest {
github_id: String,
title: String,
url: String,
merged_at_date: String,
author: String,
author_url: String,
}
#[cfg(feature = "ssr")]
#[derive(
Debug,
serde::Deserialize,
serde::Serialize,
sqlx::FromRow,
)]
struct SqlMergedPullRequest {
github_id: String,
title: String,
url: String,
merged_at_date: String,
author: String,
author_url: String,
}
#[derive(Clone, Serialize, Deserialize)]
struct Contributor;
#[cfg(feature = "ssr")]
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
struct SqlIssue {
issue_date: time::Date,
slug: String,
cloudinary_public_id: String,
display_name: String,
description: String,
youtube_id: String,
showcases: Option<sqlx::types::Json<Vec<ShowcaseData>>>,
crate_releases:
Option<sqlx::types::Json<Vec<SqlCrateRelease>>>,
devlogs: Option<sqlx::types::Json<Vec<SqlDevlog>>>,
educationals:
Option<sqlx::types::Json<Vec<SqlEducational>>>,
new_github_issues:
Option<sqlx::types::Json<Vec<SqlNewGhIssue>>>,
new_pull_requests:
Option<sqlx::types::Json<Vec<SqlNewPr>>>,
merged_pull_requests: Option<
sqlx::types::Json<Vec<SqlMergedPullRequest>>,
>,
}
#[cfg(feature = "ssr")]
#[derive(
Debug,
serde::Deserialize,
serde::Serialize,
sqlx::FromRow,
)]
struct ShowcaseData {
title: String,
url: String,
discord_url: String,
description: String,
images: Option<Vec<ImgData>>,
}
#[cfg(feature = "ssr")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
struct ImgData {
id: String,
description: String,
cloudinary_public_id: String,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
struct ImgDataTransformed {
id: String,
description: String,
url: String,
}
#[server]
async fn fetch_issue(
date: time::Date,
) -> Result<Option<Issue>, leptos::prelude::ServerFnError> {
use crate::markdown::compile;
use cloudinary::transformation::{
resize_mode::ResizeMode::ScaleByWidth,
Image as CImage, Transformations::Resize,
};
use data_encoding::BASE64;
let pool = crate::sql::pool()?;
let showcase_issue = sqlx::query_file_as!(
SqlIssue,
"src/app/routes/issue__showcase.sql",
date
)
.fetch_optional(&pool)
.await
// .inspect(|v| {tracing::info!(?v);})
.inspect_err(|e| {
tracing::error!(?e);
})?;
Ok(showcase_issue.map(|issue| {
let showcases = issue.showcases
.map(|json| json.0)
.unwrap_or_default()
.into_iter().map(|showcase_data_2| {
Showcase {
title: showcase_data_2.title,
url: showcase_data_2.url,
discord_url: showcase_data_2.discord_url,
description: compile(&showcase_data_2.description),
images: showcase_data_2.images.unwrap_or_default().into_iter()
.map(|img_data| {
let base_id = BASE64.decode(img_data.id.as_bytes()).expect("a valid id in base64 format");
let img_ulid = rusty_ulid::Ulid::try_from(base_id.as_slice())
.expect(
"expect valid ids from the database",
);
let image = CImage::new("dilgcuzda".into(), img_data.cloudinary_public_id.into())
.add_transformation(Resize(ScaleByWidth{ width:600, ar: None, liquid:None }));
ImgDataTransformed {
id: img_ulid.to_string(),
description: img_data.description,
url: image.to_string()
}
})
.collect()
}
}).collect::<Vec<Showcase>>();
let crate_releases = issue.crate_releases
.map(|json| json.0)
.unwrap_or_default()
.into_iter().map(|value| {
CrateRelease {
title: value.title,
url: value.url,
discord_url: value.discord_url,
description: compile(&value.description),
posted_date: value.posted_date,
images: value.images.unwrap_or_default().into_iter()
.map(|img_data| {
let base_id = BASE64.decode(img_data.id.as_bytes()).expect("a valid id in base64 format");
let img_ulid = rusty_ulid::Ulid::try_from(base_id.as_slice())
.expect(
"expect valid ids from the database",
);
let image = CImage::new("dilgcuzda".into(), img_data.cloudinary_public_id.into())
.add_transformation(Resize(ScaleByWidth{ width:600, ar: None, liquid:None }));
ImgDataTransformed {
id: img_ulid.to_string(),
description: img_data.description,
url: image.to_string()
}
})
.collect()
}
}).collect::<Vec<CrateRelease>>();
let devlogs = issue.devlogs
.map(|json| json.0)
.unwrap_or_default()
.into_iter().map(|value| {
Devlog {
title: value.title,
post_url: value.post_url,
video_url: value.video_url,
discord_url: value.discord_url,
description: compile(&value.description),
images: value.images.unwrap_or_default().into_iter()
.map(|img_data| {
let base_id = BASE64.decode(img_data.id.as_bytes()).expect("a valid id in base64 format");
let img_ulid = rusty_ulid::Ulid::try_from(base_id.as_slice())
.expect(
"expect valid ids from the database",
);
let image = CImage::new("dilgcuzda".into(), img_data.cloudinary_public_id.into())
.add_transformation(Resize(ScaleByWidth{ width:600, ar: None, liquid:None }));
ImgDataTransformed {
id: img_ulid.to_string(),
description: img_data.description,
url: image.to_string()
}
})
.collect()
}
}).collect::<Vec<Devlog>>();
let educationals = issue.educationals
.map(|json| json.0)
.unwrap_or_default()
.into_iter().map(|value| {
Educational {
title: value.title,
post_url: value.post_url,
video_url: value.video_url,
discord_url: value.discord_url,
description: compile(&value.description),
images: value.images.unwrap_or_default().into_iter()
.map(|img_data| {
let base_id = BASE64.decode(img_data.id.as_bytes()).expect("a valid id in base64 format");
let img_ulid = rusty_ulid::Ulid::try_from(base_id.as_slice())
.expect(
"expect valid ids from the database",
);
let image = CImage::new("dilgcuzda".into(), img_data.cloudinary_public_id.into())
.add_transformation(Resize(ScaleByWidth{ width:600, ar: None, liquid:None }));
ImgDataTransformed {
id: img_ulid.to_string(),
description: img_data.description,
url: image.to_string()
}
})
.collect()
}
}).collect::<Vec<Educational>>();
let new_github_issues = issue.new_github_issues
.map(|json| json.0)
.unwrap_or_default()
.into_iter().map(|SqlNewGhIssue{
title,
url,
gh_created_at,
author,
author_url}| NewIssue{
title,
url,
github_created_at: gh_created_at,
author,
author_url
}).collect();
let new_pull_requests: Vec<NewPullRequest> = issue.new_pull_requests
.map(|json| json.0)
.unwrap_or_default()
.into_iter().map(|SqlNewPr{
github_id,
title,
url,
gh_created_at,
author,
author_url}| NewPullRequest{
github_id,
title,
url,
gh_created_at,
author,
author_url
}).collect();
let merged_pull_requests: Vec<MergedPullRequest> = issue.merged_pull_requests
.map(|json| json.0)
.unwrap_or_default()
.into_iter().map(|SqlMergedPullRequest{
github_id,
title,
url,
merged_at_date,
author,
author_url}| MergedPullRequest{
github_id,
title,
url,
merged_at_date,
author,
author_url
}).collect();
let opengraph_image = CImage::new("dilgcuzda".into(), (*issue.cloudinary_public_id).into());
let header_image = CImage::new("dilgcuzda".into(), issue.cloudinary_public_id.into());
Issue {
title: issue.display_name,
issue_date: issue.issue_date,
slug: issue.slug,
youtube_id: issue.youtube_id,
opengraph_image: opengraph_image.to_string().replace(".avif", ".png"),
header_image: header_image.to_string(),
description: compile(&issue.description),
showcases,
crate_releases,
devlogs,
merged_pull_requests,
contributors: vec![],
educationals,
new_pull_requests,
new_github_issues,
}
}))
}
#[component]
pub fn Issue() -> impl IntoView {
let params = use_params_map();
// slug id only cares about the date, which is the
// unique id. the rest of the slug can be
// changed any time.
// 2024-02-11-the-one-before-bevy-0-13
let issue = Resource::new_blocking(
move || {
params.with(|p| {
p.get("slug").and_then(|slug|
crate::issue_date::parse_issue_date_from_slug(&slug)
)
})
},
|date| async move {
let date = date?;
fetch_issue(date).await.ok().flatten()
},
);
view! {
<Suspense fallback=move || {
view! { <p>"Loading..."</p> }
}>
{move || match issue.get() {
None | Some(None) => Either::Left(view! { <article>"404"</article> }),
Some(Some(issue)) => {
Either::Right(view! {
<article class="py-16 lg:py-16">
<Title text=issue.title.clone()/>
<Meta
name="description"
content=format!(
"What happened in the week of {} the Bevy Game Engine ecosystem",
&issue.issue_date,
)
/>
<Meta property="og:type" content="article"/>
<Meta
property="og:url"
content=format!("https://thisweekinbevy.com/issue/{}", issue.slug)
/>
<Link
rel="canonical"
href=format!("https://thisweekinbevy.com/issue/{}", issue.slug)
/>
<Meta property="og:image" content=issue.opengraph_image.clone()/>
<Meta name="twitter:card" content="summary_large_image"/>
<Meta name="twitter:creator" content="@chrisbiscardi"/>
<Meta name="twitter:title" content=issue.title.clone()/>
<Meta
name="twitter:description"
content=format!(
"What happened in the week of {} the Bevy Game Engine ecosystem",
&issue.issue_date,
)
/>
<Meta name="twitter:image" content=issue.opengraph_image/>
<Container center=true>
<img
loading="lazy"
class="w-full"
src=issue.header_image
alt=""
/>
<header class="flex flex-col pt-16">
<div class="flex items-center gap-6">
// <EpisodePlayButton
// episode={episode}
// class="group relative flex h-18 w-18 flex-shrink-0 items-center justify-center rounded-full bg-slate-700 hover:bg-slate-900 focus:outline-none focus:ring focus:ring-slate-700 focus:ring-offset-4"
// playing={
// <PauseIcon class="h-9 w-9 fill-white group-active:fill-white/80" />
// }
// paused={
// <PlayIcon class="h-9 w-9 fill-white group-active:fill-white/80" />
// }
// />
<div class="flex flex-col">
<h1 class="mt-2 text-4xl font-bold text-ctp-text">
{issue.title.clone()}
</h1>
<p class="order-first font-mono text-sm leading-7 text-ctp-text">
{issue.issue_date.to_string()}
</p>
</div>
</div>
// <p class="ml-24 mt-3 text-lg font-medium leading-8 text-ctp-text">
// {issue.as_ref().unwrap().description.clone()}
// </p>
<div
class=format!("mt-3 leading-8 {}", PROSE)
inner_html=issue.description.clone()
></div>
</header>
</Container>
<DividerWithDescription
color=DescriptionColor::Pink
title="Showcase"
description="Bevy work from the #showcase channel in Discord and around the internet. Use hashtag #bevyengine."
/>
// image=issue.showcases.iter().last().map(|i|i.images.)
// <h2 class="mt-2 text-2xl font-bold text-ctp-text">Showcase</h2>
<div class="divide-y-8 divide-ctp-pink">
{issue
.showcases
.into_iter()
.map(|showcase| {
view! {
<SideBySide
title=showcase.title
type_name="showcase".to_string()
posted_date=None
images=showcase.images
description=showcase.description
primary_url=showcase.url
discord_url=showcase.discord_url
/>
}
})
.collect_view()}
</div>
// // <h2 class="mt-2 text-2xl font-bold text-ctp-text">Crates</h2>
// // <Divider title="Crates"/>
<DividerWithDescription
color=DescriptionColor::Lavender
title="Crates"
description="New releases to crates.io and substantial updates to existing projects"
/>
<div class="divide-y-8 divide-ctp-lavender">
{issue
.crate_releases
.into_iter()
.sorted_by_key(|cr| cr.posted_date.clone())
.rev()
.map(|crate_release| {
view! {
<SideBySide
title=crate_release.title
type_name="crate_release".to_string()
posted_date=crate_release.posted_date
images=crate_release.images
description=crate_release.description
primary_url=crate_release.url
discord_url=crate_release.discord_url
/>
}
})
.collect_view()}
</div>
{if issue.devlogs.is_empty() {
Either::Left(view! {
<div class="border-y-8 border-y-ctp-teal text-center text-ctp-text">
No devlogs this week
</div>
})
} else {
Either::Right(view! {
<DividerWithDescription
color=DescriptionColor::Teal
title="Devlogs"
description="vlog style updates from long-term projects"
/>
})
}}
<div class="divide-y-8 divide-ctp-teal">
{issue
.devlogs
.into_iter()
.map(|devlog| {
view! {
<SideBySide
title=devlog.title
type_name="devlog".to_string()
posted_date=None
images=devlog.images
description=devlog.description
primary_url=devlog.post_url
discord_url=devlog.discord_url
video_url=devlog.video_url
/>
}
})
.collect_view()}
</div>
{if issue.educationals.is_empty() {
Either::Left(view! {
<div class="border-y-8 border-y-ctp-blue text-center text-ctp-text">
No Educational this week
</div>
})
} else {
Either::Right(view! {
<DividerWithDescription
color=DescriptionColor::Blue
title="Educational"
description="Tutorials, deep dives, and other information on developing Bevy applications, games, and plugins"
/>
})
}}
{issue
.educationals
.into_iter()
.map(|educational| {
view! {
<SideBySide
title=educational.title
type_name="educational".to_string()
posted_date=None
images=educational.images
description=educational.description
primary_url=educational.post_url
discord_url=educational.discord_url
video_url=educational.video_url
/>
}
})
.collect_view()}
<Container center=true>
<Divider title="Pull Requests Merged This Week"/>
<ul role="list" class="space-y-6 mt-6">
{issue
.merged_pull_requests
.iter()
.sorted_by_key(|pr| &pr.merged_at_date)
.map(|pull_request| {
view! {
<ActivityListItem
date=&pull_request.merged_at_date
url=&pull_request.url
title=&pull_request.title
author=&pull_request.author
/>
}
})
.collect_view()}
</ul>
<Divider title="Contributing"/>
<CalloutInfo
r#type=CalloutType::Info
title="Want to contribute to Bevy?"
>
// link=CalloutLink {
// href: "https://github.com/bevyengine/bevy/blob/main/CONTRIBUTING.md".to_string(),
// label: "Learn More".to_string()
// }
<p>
Here you can find two types of potential contribution: Pull Requests that might need review and Issues that might need to be worked on.
</p>
<p class="flex justify-end mt-2">
<a href="https://github.com/bevyengine/bevy/blob/main/CONTRIBUTING.md">
How do I contribute?
</a>
</p>
</CalloutInfo>
<h2 class="mt-6 text-2xl font-bold text-ctp-text">
Pull Requests Opened this week
</h2>
<ul role="list" class="space-y-6 mt-6">
{
let merged_prs = issue
.merged_pull_requests
.iter()
.map(|v| v.github_id.as_str())
.collect::<std::collections::HashSet<&str>>();
issue
.new_pull_requests
.iter()
.sorted_by_key(|pr| &pr.gh_created_at)
.filter(|pr| !merged_prs.contains(&pr.github_id.as_str()))
.map(|pull_request| {
view! {
// build a HashSet of github_ids that were already shown
// in the merged_pull_requests section so that we don't show them twice
<ActivityListItem
date=&pull_request.gh_created_at
url=&pull_request.url
title=&pull_request.title
author=&pull_request.author
/>
}
})
.collect_view()
}
</ul>
<h2 class="mt-6 text-2xl font-bold text-ctp-text">
Issues Opened this week
</h2>
<ul role="list" class="space-y-6 mt-6">
{issue
.new_github_issues
.iter()
.sorted_by_key(|issue| &issue.github_created_at)
.map(|issue| {
view! {
<ActivityListItem
date=issue.github_created_at.clone()
url=&issue.url
title=&issue.title
author=&issue.author
/>
}
})
.collect::<Vec<_>>()}
</ul>
</Container>
</article>
})
}
}}
</Suspense>
}
}
#[allow(dead_code)]
enum ActivityListIcon {
Default,
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | true |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/custom.rs | src/app/routes/custom.rs | use std::ops::Not;
use crate::app::components::{Container, Divider};
use futures::future::join4;
use leptos::{
either::{Either, EitherOf4},
prelude::*,
};
use leptos_router::hooks::use_params_map;
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize)]
pub struct Issue {
/// The title of the issue is technically the
/// date in yyyy-mm-dd format, but this field
/// is a human-readable string that goes in
/// the email subject line and slug url
title: String,
/// What is this issue about? Is there
/// anything notable worth mentioning or
/// making sure people are aware of?
description: String,
/// Showcase what people are doing with Bevy
/// this week. Often these are in-progress
/// games, experimental rendering approaches,
/// or other in-progress bevy work
showcases: Vec<Showcase>,
/// Crates that have been released in the last
/// week. This includes updates and new
/// releases
crates: Vec<CrateRelease>,
/// merged pull requests
/// Meant to convey what is being added to
/// Bevy
pull_requests: Vec<PullRequest>,
/// educational resources published this week.
/// videos and blog posts
educational: Vec<Educational>,
/// newsletter contributors
/// (not a list of people that contribute to
/// the bevy repo itself, that exists in the
/// Bevy release announcements already)
contributors: Vec<Contributor>,
/// Want to contribute? check out these
/// pull requests that need review
new_pull_requests: Vec<NewPullRequest>,
/// Want to contribute? check out these
/// issues that just got opened
new_issues: Vec<NewIssue>,
}
/// `NewPullRequest` is calculated just before
/// publishing each issue. It is a stateful
/// representation of new pull requests that were
/// opened this week (and still open when the
/// issue is published), with the intent of
/// providing This Week in Bevy readers the
/// opportunity to discover pull requests that
/// could benefit from review this week.
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct NewPullRequest {
author: String,
github_id: String,
title: String,
url: String,
}
/// `NewIssue` is calculated just before
/// publishing each issue. It is a stateful
/// representation of new issues that were
/// opened this week (and still open when the
/// issue is published), with the intent of
/// providing This Week in Bevy readers the
/// opportunity to discover issues that
/// could benefit from reproduction cases and
/// other fixes.
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct NewIssue {
author: String,
github_id: String,
title: String,
url: String,
}
#[derive(Clone, Serialize, Deserialize)]
struct CrateRelease {
title: String,
description: String,
url: String,
images: Vec<String>,
}
#[derive(Clone, Serialize, Deserialize)]
struct Educational {
title: String,
description: String,
url: String,
images: Vec<String>,
}
#[derive(Clone, Serialize, Deserialize)]
struct Showcase;
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PullRequest {
author: PullRequestAuthor,
closed_at: String,
number: u32,
title: String,
url: String,
}
#[derive(Clone, Serialize, Deserialize)]
struct PullRequestAuthor {
login: String,
}
#[derive(Clone, Serialize, Deserialize)]
struct Contributor;
#[server]
async fn fetch_issue(
_date: time::Date,
) -> Result<Issue, leptos::server_fn::ServerFnError> {
use crate::markdown::compile;
let crates = vec![CrateRelease {
title: "Hexx 0.13.0".to_string(),
description: compile("hexx is an hexagonal utility library made with bevy integration in mind
What's new:
* A new sprite sheet example
* A lot of improvements in mesh generation, especially with procedural UV coordinates
* Quality of life improvements
* Fixes !"),
url: "https://discord.com/channels/691052431525675048/918591326096850974/1202285063358648350".to_string(),
images: vec!["/test_one.png".to_string(), "/test_two.png".to_string(), "/test_three.png".to_string()],
},
CrateRelease{
title: "bevy_smooth_pixel_camera".to_string(),
description: "bugfix release".to_string(),
url: "".to_string(),
images: vec![]
}];
Ok(Issue {
title: "The one before Bevy 0.13!".to_string(),
description: compile("It's a new year and there's another month or two until the 0.13 release.
There are three things in this to pay attention to
* Thing A
* Thing B
* Thing C
and a quote from a contributor
> Some Quote
> - [Contributor Person](https://github.com/bevyengine/bevy)"),
showcases: vec![],
crates,
pull_requests: vec![],
contributors: vec![],
educational: vec![],
new_pull_requests: vec![],
new_issues: vec![],
})
}
#[component]
pub fn Issue() -> impl IntoView {
let params = use_params_map();
// slug id only cares about the date, which is the
// unique id. the rest of the slug can be
// changed any time.
// 2024-02-11-the-one-before-bevy-0-13
let issue = Resource::new(
move || {
params.with(|p| {
p.get("slug").and_then(|slug|
crate::issue_date::parse_issue_date_from_slug(&slug)
)
})
},
|date| async move {
let date = date?;
Some(
join4(
fetch_issue(date),
crate::sql::get_merged_pull_requests(
date,
),
crate::sql::get_opened_pull_requests(
date,
),
crate::sql::get_opened_issues(date),
)
.await,
)
},
);
view! {
<Suspense fallback=move || {
view! { <p>"Loading..."</p> }
}>
{move || match issue.get() {
None | Some(None) => Either::Left(view! { <article>"404"</article> }),
Some(Some((issue, merged_pull_requests, opened_pull_requests, opened_issues))) => {
Either::Right(view! {
<article class="py-16 lg:py-36">
<Container>
<header class="flex flex-col">
<div class="flex items-center gap-6">
// <EpisodePlayButton
// episode={episode}
// class="group relative flex h-18 w-18 flex-shrink-0 items-center justify-center rounded-full bg-slate-700 hover:bg-slate-900 focus:outline-none focus:ring focus:ring-slate-700 focus:ring-offset-4"
// playing={
// <PauseIcon class="h-9 w-9 fill-white group-active:fill-white/80" />
// }
// paused={
// <PlayIcon class="h-9 w-9 fill-white group-active:fill-white/80" />
// }
// />
<div class="flex flex-col">
<h1 class="mt-2 text-4xl font-bold text-slate-900">
{issue.as_ref().unwrap().title.clone()}
</h1>
// <FormattedDate
// date={date}
<p class="order-first font-mono text-sm leading-7 text-slate-500">
// />
"2024-02-11"
</p>
</div>
</div>
// <p class="ml-24 mt-3 text-lg font-medium leading-8 text-slate-700">
// {issue.as_ref().unwrap().description.clone()}
// </p>
<div
class=r#"mt-3 leading-8 text-slate-700 prose [&>h2:nth-of-type(3n)]:before:bg-violet-200 [&>h2:nth-of-type(3n+2)]:before:bg-indigo-200 [&>h2]:mt-12 [&>h2]:flex [&>h2]:items-center [&>h2]:font-mono [&>h2]:text-sm [&>h2]:font-medium [&>h2]:leading-7 [&>h2]:text-slate-900 [&>h2]:before:mr-3 [&>h2]:before:h-3 [&>h2]:before:w-1.5 [&>h2]:before:rounded-r-full [&>h2]:before:bg-cyan-200 [&>ul]:mt-6 [&>ul]:list-['\2013\20'] [&>ul]:pl-5"#
inner_html=issue.as_ref().unwrap().description.clone()
></div>
</header>
<Divider title="Community Showcase"/>
<div class=r#"prose prose-slate mt-14 [&>h2:nth-of-type(3n)]:before:bg-violet-200 [&>h2:nth-of-type(3n+2)]:before:bg-indigo-200 [&>h2]:mt-12 [&>h2]:flex [&>h2]:items-center [&>h2]:font-mono [&>h2]:text-sm [&>h2]:font-medium [&>h2]:leading-7 [&>h2]:text-slate-900 [&>h2]:before:mr-3 [&>h2]:before:h-3 [&>h2]:before:w-1.5 [&>h2]:before:rounded-r-full [&>h2]:before:bg-cyan-200 [&>ul]:mt-6 [&>ul]:list-['\2013\20'] [&>ul]:pl-5"#></div>
// dangerouslySetInnerHTML={{ __html: episode.content }}
<h2 class="mt-2 text-2xl font-bold text-slate-900">Showcase</h2>
<h2 class="mt-2 text-2xl font-bold text-slate-900">Crates</h2>
{issue
.as_ref()
.unwrap()
.crates
.iter()
.map(|crate_release| {
view! {
<CrateRelease
title=crate_release.title.clone()
description=crate_release.description.clone()
url=crate_release.url.clone()
images=crate_release.images.clone()
/>
}
})
.collect::<Vec<_>>()}
<h2 class="mt-2 text-2xl font-bold text-slate-900">Devlogs</h2>
<h2 class="mt-2 text-2xl font-bold text-slate-900">Education</h2>
<Divider title="Fixes and Features"/>
<h2 class="mt-2 text-2xl font-bold text-slate-900">
Pull Requests Merged this week
</h2>
<ul role="list" class="space-y-6 mt-6">
{merged_pull_requests
.expect("")
.iter()
.map(|pull_request| {
view! {
<ActivityListItem
date=pull_request.merged_at_date.clone()
url=pull_request.url.clone()
title=pull_request.title.clone()
author=pull_request.author.clone()
/>
}
})
.collect::<Vec<_>>()}
</ul>
<Divider title="Contributing"/>
<CalloutInfo
r#type=CalloutType::Info
title="Want to contribute to Bevy?"
>
// link=CalloutLink {
// href: "https://github.com/bevyengine/bevy/blob/main/CONTRIBUTING.md".to_string(),
// label: "Learn More".to_string()
// }
<p>
Here you can find two types of potential contribution: Pull Requests that might need review and Issues that might need to be worked on.
</p>
</CalloutInfo>
<h2 class="mt-6 text-2xl font-bold text-slate-900">
Pull Requests Opened this week
</h2>
<ul role="list" class="space-y-6 mt-6">
{opened_pull_requests
.expect("")
.iter()
.map(|pull_request| {
view! {
<ActivityListItem
date=pull_request.gh_created_at.clone()
url=pull_request.url.clone()
title=pull_request.title.clone()
author=pull_request.author.clone()
/>
}
})
.collect::<Vec<_>>()}
</ul>
<h2 class="mt-6 text-2xl font-bold text-slate-900">
Issues Opened this week
</h2>
<ul role="list" class="space-y-6 mt-6">
{opened_issues
.expect("")
.iter()
.map(|issue| {
view! {
<ActivityListItem
date=issue.gh_created_at.clone()
url=issue.url.clone()
title=issue.title.clone()
author=issue.author.clone()
/>
}
})
.collect::<Vec<_>>()}
</ul>
</Container>
</article>
})
}
}}
</Suspense>
}
}
#[allow(dead_code)]
enum ActivityListIcon {
Default,
Check,
}
#[component]
fn ActivityListItem(
/// datetime for the <time> element
#[prop(into)]
date: String,
#[prop(into)] url: String,
#[prop(into)] title: String,
#[prop(into)] author: String,
#[prop(default=ActivityListIcon::Default)]
icon: ActivityListIcon,
) -> impl IntoView {
view! {
<li class="relative flex gap-x-4">
<div class="absolute left-0 top-0 flex w-6 justify-center -bottom-6">
<div class="w-px bg-gray-200"></div>
</div>
<div class="relative flex h-6 w-6 flex-none items-center justify-center bg-white">
{match icon {
ActivityListIcon::Default => {
Either::Left(view! {
<>
<div class="h-1.5 w-1.5 rounded-full bg-gray-100 ring-1 ring-gray-300"></div>
</>
})
}
ActivityListIcon::Check => {
Either::Right(view! {
<>
<svg
class="h-6 w-6 text-green-600"
viewBox="0 0 24 24"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm13.36-1.814a.75.75 0 10-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 00-1.06 1.06l2.25 2.25a.75.75 0 001.14-.094l3.75-5.25z"
clip-rule="evenodd"
></path>
</svg>
</>
})
}
}}
</div>
<p class="flex-auto py-0.5 text-xs leading-5 text-gray-500">
<a href=url class="font-medium text-gray-900">
{title}
</a>
" authored by "
<span class="font-medium text-gray-900">{author}</span>
</p>
<time datetime=date class="flex-none py-0.5 text-xs leading-5 text-gray-500">
{date.clone()}
</time>
</li>
}
}
#[component]
#[allow(unused_variables)]
fn ActivityListComment(
/// datetime for the <time> element
/// "2023-01-23T15:56"
#[prop(into)]
time: String,
#[prop(into)] url: String,
#[prop(
into,
default = "This is going to be super useful for something in the future!".to_string()
)]
comment: String,
#[prop(into, default = "Someone".to_string())]
author: String,
) -> impl IntoView {
view! {
<li class="relative flex gap-x-4">
<div class="absolute left-0 top-0 flex w-6 justify-center -bottom-6">
<div class="w-px bg-gray-200"></div>
</div>
<img
src="/this-week-in-bevydark"
alt=""
class="relative mt-3 h-6 w-6 flex-none rounded-full bg-gray-50"
/>
<div class="flex-auto rounded-md p-3 ring-1 ring-inset ring-gray-200">
<div class="flex justify-between gap-x-4">
<div class="py-0.5 text-xs leading-5 text-gray-500">
<span class="font-medium text-gray-900">{author}</span>
commented
</div>
<time datetime=time class="flex-none py-0.5 text-xs leading-5 text-gray-500">
3d ago
</time>
</div>
<p class="text-sm leading-6 text-gray-500">{comment}</p>
</div>
</li>
}
}
#[component]
#[allow(unused_variables)]
fn CrateRelease(
#[prop(into)] title: String,
#[prop(into)] description: String,
#[prop(into)] url: String,
#[prop(default=vec![])] images: Vec<String>,
) -> impl IntoView {
view! {
<h3 class="mt-2 text-xl font-bold text-slate-900">{title}</h3>
<ul
role="list"
class="mt-3 grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-3 sm:gap-x-6 lg:grid-cols-4 xl:gap-x-8"
>
{images
.clone()
.into_iter()
.map(|image| {
view! {
<li class="relative">
<div class="group aspect-h-7 aspect-w-10 block w-full overflow-hidden rounded-lg bg-gray-100 focus-within:ring-2 focus-within:ring-indigo-500 focus-within:ring-offset-2 focus-within:ring-offset-gray-100">
<img
src=image
alt=""
class="pointer-events-none object-cover group-hover:opacity-75"
/>
<button type="button" class="absolute inset-0 focus:outline-none">
<span class="sr-only">View details for IMG_4985</span>
</button>
</div>
</li>
}
})
.collect::<Vec<_>>()}
</ul>
<div
class=r#"mt-3 prose prose-slate [&>h2:nth-of-type(3n)]:before:bg-violet-200 [&>h2:nth-of-type(3n+2)]:before:bg-indigo-200 [&>h2]:mt-12 [&>h2]:flex [&>h2]:items-center [&>h2]:font-mono [&>h2]:text-sm [&>h2]:font-medium [&>h2]:leading-7 [&>h2]:text-slate-900 [&>h2]:before:mr-3 [&>h2]:before:h-3 [&>h2]:before:w-1.5 [&>h2]:before:rounded-r-full [&>h2]:before:bg-cyan-200 [&>ul]:mt-6 [&>ul]:list-['\2013\20'] [&>ul]:pl-5"#
inner_html=description
></div>
}
}
#[allow(dead_code)]
enum CalloutType {
Info,
Caution,
Warning,
Success,
}
impl CalloutType {
fn bg(&self) -> &str {
match self {
CalloutType::Info => "bg-blue-50",
CalloutType::Caution => "bg-yellow-50",
CalloutType::Warning => "bg-red-50",
CalloutType::Success => "bg-green-50",
}
}
fn icon(&self) -> &str {
match self {
CalloutType::Info => "text-blue-400",
CalloutType::Caution => "text-yellow-400",
CalloutType::Warning => "text-red-400",
CalloutType::Success => "text-green-400",
}
}
fn icon_svg(&self) -> impl IntoView {
match self {
CalloutType::Info => EitherOf4::A(view! {
<svg
class=format!("h-5 w-5 {}", self.icon())
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z"
clip-rule="evenodd"
></path>
</svg>
}),
CalloutType::Caution => EitherOf4::B(view! {
<svg
class=format!("h-5 w-5 {}", self.icon())
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 5a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 5zm0 9a1 1 0 100-2 1 1 0 000 2z"
clip-rule="evenodd"
></path>
</svg>
}),
CalloutType::Warning => EitherOf4::C(view! {
<svg
class=format!("h-5 w-5 {}", self.icon())
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.28 7.22a.75.75 0 00-1.06 1.06L8.94 10l-1.72 1.72a.75.75 0 101.06 1.06L10 11.06l1.72 1.72a.75.75 0 101.06-1.06L11.06 10l1.72-1.72a.75.75 0 00-1.06-1.06L10 8.94 8.28 7.22z"
clip-rule="evenodd"
></path>
</svg>
}),
CalloutType::Success => EitherOf4::D(view! {
<svg
class=format!("h-5 w-5 {}", self.icon())
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z"
clip-rule="evenodd"
></path>
</svg>
}),
}
}
fn title(&self) -> &str {
match self {
CalloutType::Info => "text-blue-800",
CalloutType::Caution => "text-yellow-800",
CalloutType::Warning => "text-red-800",
CalloutType::Success => "text-green-800",
}
}
fn content(&self) -> &str {
match self {
CalloutType::Info => "text-blue-700",
CalloutType::Caution => "text-yellow-700",
CalloutType::Warning => "text-red-700",
CalloutType::Success => "text-green-700",
}
}
fn child_links(&self) -> &str {
match self {
CalloutType::Info => "[&_a]:font-medium [&_a]:text-blue-700 [&_a]:underline [&_a]:hover:text-blue-600",
CalloutType::Caution => "[&_a]:font-medium [&_a]:text-yellow-700 [&_a]:underline [&_a]:hover:text-yellow-600",
CalloutType::Warning => "[&_a]:font-medium [&_a]:text-red-700 [&_a]:underline [&_a]:hover:text-red-600",
CalloutType::Success => "[&_a]:font-medium [&_a]:text-green-700 [&_a]:underline [&_a]:hover:text-green-600",
}
}
}
#[allow(dead_code)]
struct CalloutLink {
href: String,
label: String,
}
#[component]
fn CalloutInfo(
r#type: CalloutType,
#[prop(into, optional, default = "".to_string())] title: String,
#[prop(optional, default = None)] link: Option<
CalloutLink,
>,
children: Children,
) -> impl IntoView {
let has_link = link.is_none();
view! {
<div class=format!("rounded-md p-4 {}", r#type.bg())>
<div class="flex">
<div class="flex-shrink-0">
{r#type.icon_svg()}
</div>
<div class="ml-3">
{title
.is_empty()
.not()
.then_some(
view! {
<h3 class=format!(
"text-sm font-medium {}",
r#type.title(),
)>{title}</h3>
},
)}
<div class=if has_link {
format!("mt-2 text-sm {} {}", r#type.content(), r#type.child_links())
} else {
format!(
"ml-3 flex-1 md:flex md:justify-between {} {}",
r#type.content(),
r#type.child_links(),
)
}>
{children()}
{link
.map(|CalloutLink { href, label }| {
view! {
<p class="mt-3 text-sm md:ml-6 md:mt-0">
<a
href=href
class="whitespace-nowrap font-medium text-blue-700 hover:text-blue-600"
>
{label}
<span aria-hidden="true">" →"</span>
</a>
</p>
}
})}
</div>
// <div class="mt-4">
// <div class="-mx-2 -my-1.5 flex">
// <button type="button" class="rounded-md bg-green-50 px-2 py-1.5 text-sm font-medium text-green-800 hover:bg-green-100 focus:outline-none focus:ring-2 focus:ring-green-600 focus:ring-offset-2 focus:ring-offset-green-50">View status</button>
// <button type="button" class="ml-3 rounded-md bg-green-50 px-2 py-1.5 text-sm font-medium text-green-800 hover:bg-green-100 focus:outline-none focus:ring-2 focus:ring-green-600 focus:ring-offset-2 focus:ring-offset-green-50">Dismiss</button>
// </div>
// </div>
</div>
</div>
</div>
}
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/admin/issues.rs | src/app/routes/admin/issues.rs | use leptos::{either::Either, prelude::*};
use serde::{Deserialize, Serialize};
#[component]
pub fn Issues() -> impl IntoView {
let create_draft_issue: ServerAction<CreateDraftIssue> =
ServerAction::new();
let issues =
Resource::new(move || {}, |_| fetch_issues());
view! {
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<div class="bg-white shadow sm:rounded-lg">
<div class="px-4 py-5 sm:p-6">
<h3 class="text-base font-semibold leading-6 text-gray-900">
Create New Issue
</h3>
<div class="mt-2 max-w-xl text-sm text-gray-500">
<p>
Creates a new draft issue that content can be attached to. Pick a Monday for the issue date.
</p>
</div>
<ActionForm attr:class="mt-5 sm:flex sm:items-center" action=create_draft_issue>
<div class="w-full sm:max-w-xs">
<label for="issue_date" class="sr-only">
issue_date
</label>
<input
type="date"
name="issue_date"
id="issue_date"
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
/>
</div>
<button
type="submit"
class="mt-3 inline-flex w-full items-center justify-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 sm:ml-3 sm:mt-0 sm:w-auto"
>
Save
</button>
</ActionForm>
</div>
</div>
<Suspense fallback=move || view! { <p>"Loading (Suspense Fallback)..."</p> }>
<ul role="list" class="divide-y-4 divide-ctp-mantle">
{move || {
issues
.get()
.map(|data| match data {
Err(e) => Either::Left(view! { <pre>{e.to_string()}</pre> }),
Ok(issues) => {
Either::Right(issues
.iter()
.map(|issue| {
let status_style = match issue.status.as_ref() {
"draft" => "text-yellow-400 bg-yellow-400/10",
"publish" => "text-green-400 bg-green-400/10",
_ => "text-slate-400 bg-slate-400/10",
};
view! {
<li class="flex gap-x-4 py-5">
<div class=format!(
"flex-none rounded-full p-1 {status_style}",
)>
<div class="h-2 w-2 rounded-full bg-current"></div>
</div>
<div class="flex-auto">
<div class="flex items-baseline justify-between gap-x-4">
<a
href=format!("/admin/issue/{}", &issue.id)
class="text-sm font-semibold leading-6 text-gray-900"
>
{issue.display_name.clone()}
</a>
<time datetime=issue
.issue_date
.to_string()>{issue.issue_date.to_string()}</time>
<p class="flex-none text-xs text-gray-600">
something here
</p>
</div>
</div>
</li>
}
})
.collect_view())
}
})
}}
</ul>
</Suspense>
</div>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlIssueShort {
id: Vec<u8>,
display_name: String,
status: String,
issue_date: time::Date,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct IssueShort {
id: String,
display_name: String,
status: String,
issue_date: time::Date,
}
#[cfg(feature = "ssr")]
impl From<SqlIssueShort> for IssueShort {
fn from(value: SqlIssueShort) -> Self {
// let id: [u8; 16] =
// rusty_ulid::generate_ulid_bytes();
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
IssueShort {
id: id_str.to_string(),
display_name: value.display_name,
status: value.status,
issue_date: value.issue_date,
}
}
}
#[server]
pub async fn fetch_issues(
) -> Result<Vec<IssueShort>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issues: Vec<SqlIssueShort> = sqlx::query_as!(
SqlIssueShort,
"SELECT
id,
display_name,
status,
issue_date
FROM issue
ORDER BY status, issue_date DESC"
)
.fetch_all(&pool)
.await?;
Ok(issues.into_iter().map(IssueShort::from).collect())
}
#[server]
pub async fn create_draft_issue(
issue_date: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
// https://res.cloudinary.com/dilgcuzda/image/upload/v1708310121/
let id: [u8; 16] = rusty_ulid::generate_ulid_bytes();
let slug = format!("{issue_date}-todo");
// default id for opengraph image
let cloudinary_public_id = "thisweekinbevy/this-week-in-bevyopengraph-light_zwqzqz.avif";
let display_name = format!("Draft for {issue_date}");
sqlx::query!(
r#"
INSERT INTO issue ( id, issue_date, slug, cloudinary_public_id, display_name )
VALUES ( ?, ?, ?, ?, ? )
"#,
id.as_slice(),
issue_date,
slug,
cloudinary_public_id,
display_name
)
.execute(&pool)
.await
.expect("successful insert");
Ok(())
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/admin/image.rs | src/app/routes/admin/image.rs | use crate::app::components::Divider;
#[cfg(feature = "ssr")]
use crate::app::server_fn::error::NoCustomError;
use leptos::{
either::{Either, EitherOf3},
prelude::*,
};
use serde::{Deserialize, Serialize};
#[cfg(feature = "ssr")]
use tracing::error;
#[component]
pub fn Image() -> impl IntoView {
let add_image: ServerAction<AddImage> =
ServerAction::new();
view! {
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<ActionForm attr:class="isolate -space-y-px rounded-md shadow-sm" action=add_image>
<div class="relative rounded-md px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="cloudinary_public_id"
class="block text-xs font-medium text-gray-900"
>
cloudinary_public_id
</label>
<input
required
type="text"
name="cloudinary_public_id"
id="cloudinary_public_id"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
/>
</div>
<label
for="description"
class="block text-sm font-medium leading-6 text-gray-900"
>
Add your description (markdown compatible)
</label>
<div class="mt-2">
<textarea
required
rows="4"
name="description"
id="description"
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
></textarea>
</div>
<div class="pt-4">
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Add Image Id
</button>
</div>
</ActionForm>
<Divider title="last 5 images"/>
<Images/>
</div>
}
}
#[server]
async fn add_image(
cloudinary_public_id: String,
description: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let id: [u8; 16] = rusty_ulid::generate_ulid_bytes();
sqlx::query!(
r#"
INSERT INTO image ( id, cloudinary_public_id, description )
VALUES ( ?, ?, ? )
"#,
id.as_slice(),
cloudinary_public_id,
description
)
.execute(&pool)
.await
.map_err(|e| {
error!(?e);
ServerFnError::<NoCustomError>::ServerError("sql failed".to_string())
})?;
Ok(())
}
#[component]
fn Images() -> impl IntoView {
let images =
Resource::new(move || {}, |_| fetch_images());
view! {
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || images
.get()
.map(|data| match data {
Err(e) => Either::Left(view! { <div>{e.to_string()}</div> }),
Ok(images) => {
Either::Right(view! {
<ul
role="list"
class="grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-3 sm:gap-x-6 lg:grid-cols-4 xl:gap-x-8"
>
<For
each=move || images.clone()
key=|image| image.id.clone()
let:image
>
<ImageLi
id=image.id
url=image.url
description=image.description
/>
</For>
</ul>
})
}
})}
</Suspense>
}
}
#[component]
fn ImageLi(
id: String,
url: String,
description: String,
) -> impl IntoView {
view! {
<li class="relative">
<div class="group aspect-h-7 aspect-w-10 block w-full overflow-hidden rounded-lg bg-gray-100 focus-within:ring-2 focus-within:ring-indigo-500 focus-within:ring-offset-2 focus-within:ring-offset-gray-100">
<img
src=url
alt=""
class="pointer-events-none object-cover group-hover:opacity-75"
/>
<button type="button" class="absolute inset-0 focus:outline-none">
<span class="sr-only">View details</span>
</button>
</div>
<p class="pointer-events-none mt-2 block truncate text-sm font-medium text-gray-900">
{id}
</p>
<p class="pointer-events-none block text-sm font-medium text-gray-500">{description}</p>
</li>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlImage {
id: Vec<u8>,
description: String,
cloudinary_public_id: String,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct Image {
pub id: String,
pub description: String,
pub url: String,
}
#[cfg(feature = "ssr")]
impl From<SqlImage> for Image {
fn from(value: SqlImage) -> Self {
use cloudinary::transformation::{
resize_mode::ResizeMode::ScaleByWidth,
Image as CImage, Transformations::Resize,
};
let image = CImage::new(
"dilgcuzda".into(),
value.cloudinary_public_id.into(),
)
.add_transformation(Resize(ScaleByWidth {
width: 300,
ar: None,
liquid: None,
}));
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
Image {
id: id_str.to_string(),
description: value.description,
url: image.to_string(),
}
}
}
#[server]
async fn fetch_images() -> Result<Vec<Image>, ServerFnError>
{
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let images: Vec<SqlImage> = sqlx::query_as!(
SqlImage,
r#"SELECT
id,
cloudinary_public_id,
description
FROM image
ORDER BY created_at DESC
limit 5"#
)
.fetch_all(&pool)
.await
.map_err(|e| {
error!(?e);
ServerFnError::<NoCustomError>::ServerError(
"sql failed".to_string(),
)
})?;
Ok(images.into_iter().map(Image::from).collect())
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/admin/crate_release.rs | src/app/routes/admin/crate_release.rs | use crate::app::components::Divider;
use futures::future::join;
use leptos::{either::EitherOf3, prelude::*};
use serde::{Deserialize, Serialize};
pub mod id;
#[server]
async fn add_crate_release(
title: String,
url: String,
discord_url: String,
description: String,
posted_date: String,
) -> Result<(), ServerFnError> {
let pool = use_context::<sqlx::MySqlPool>()
.expect("to be able to access app_state");
let username = crate::sql::with_admin_access()?;
let id: [u8; 16] = rusty_ulid::generate_ulid_bytes();
sqlx::query!(
r#"
INSERT INTO crate_release ( id, title, url, discord_url, posted_date, description, submitted_by )
VALUES ( ?, ?, ?, ?, ?, ?, ? )
"#,
id.as_slice(),
title,
url,
discord_url,
posted_date,
description,
username.0
)
.execute(&pool)
.await
.expect("successful insert");
Ok(())
}
#[component]
pub fn CrateRelease() -> impl IntoView {
let add_crate_release: ServerAction<AddCrateRelease> =
ServerAction::new();
let crate_releases = Resource::new(
move || {},
|_| join(fetch_crate_releases(), fetch_issues()),
);
view! {
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<ActionForm attr:class="isolate -space-y-px rounded-md shadow-sm" action=add_crate_release>
<div class="relative rounded-md rounded-b-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="title" class="block text-xs font-medium text-gray-900">
Title
</label>
<input
required
type="text"
name="title"
id="title"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="Hexagon procedural generation"
/>
</div>
<div class="relative px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="url" class="block text-xs font-medium text-gray-900">
URL
</label>
<input
required
type="text"
name="url"
id="url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="https"
/>
</div>
<div class="relative rounded-md rounded-t-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="discord_url" class="block text-xs font-medium text-gray-900">
Discord URL
</label>
<input
type="text"
name="discord_url"
id="discord_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="https"
/>
</div>
<label
for="posted_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
Posted At
</label>
<div class="mt-2">
<input type="date" required id="posted_date" name="posted_date" min="2024-01-01"/>
</div>
<label
for="description"
class="block text-sm font-medium leading-6 text-gray-900"
>
Add your description (markdown compatible)
</label>
<div class="mt-2">
<textarea
required
rows="4"
name="description"
id="description"
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
></textarea>
</div>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Add CrateRelease
</button>
</ActionForm>
<Divider title="CrateReleases without an issue"/>
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || crate_releases
.get()
.map(|data| match data {
(Err(e), Err(e2)) => {
EitherOf3::A(view! {
<div>
<div>{e.to_string()}</div>
<div>{e2.to_string()}</div>
</div>
})
}
(_, Err(e)) | (Err(e), _) => {
EitherOf3::B(view! {
<div>
<div>{e.to_string()}</div>
</div>
})
}
(Ok(crate_releases), Ok(issues)) => {
EitherOf3::C(view! {
<div>
<ul role="list" class="divide-y divide-gray-100">
<For
each=move || crate_releases.clone()
key=|crate_release| crate_release.id.clone()
let:crate_release
>
<AddCrateReleaseToIssueForm
crate_release=crate_release
issue_id=issues.first().map(|issue| issue.id.clone())
/>
</For>
</ul>
</div>
})
}
})}
</Suspense>
</div>
}
}
#[component]
fn AddCrateReleaseToIssueForm(
crate_release: CrateReleaseData,
issue_id: Option<String>,
) -> impl IntoView {
let associate_crate_release_with_issue: ServerAction<
AssociateCrateReleaseWithIssue,
> = ServerAction::new();
view! {
<li class="flex items-center justify-between gap-x-6 py-5">
<div class="min-w-0">
<div class="flex items-start gap-x-3">
<p class="text-sm font-semibold leading-6 text-gray-900">
{crate_release.title}
</p>
</div>
<div class="mt-1 flex items-center gap-x-2 text-xs leading-5 text-gray-500">
<p class="whitespace-nowrap">
posted on
<time datetime=crate_release
.posted_date
.as_ref()
.unwrap()
.to_string()>
{crate_release.posted_date.as_ref().unwrap().to_string()}
</time>
</p>
<svg viewBox="0 0 2 2" class="h-0.5 w-0.5 fill-current">
<circle cx="1" cy="1" r="1"></circle>
</svg>
// <p class="truncate">Submitted by {crate_release.submitted_by}</p>
</div>
</div>
{issue_id
.map(|issue_id| {
view! {
<div class="flex flex-none items-center gap-x-4">
<ActionForm action=associate_crate_release_with_issue>
<input
type="hidden"
value=crate_release.id
name="crate_release_id"
/>
<input type="hidden" value=issue_id name="issue_id"/>
<button
type="submit"
class="hidden rounded-md bg-white px-2.5 py-1.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:block"
>
Add to current draft
</button>
</ActionForm>
</div>
}
})}
</li>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlCrateReleaseData {
id: Vec<u8>,
title: String,
posted_date: Option<time::Date>,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct CrateReleaseData {
pub id: String,
pub title: String,
pub posted_date: Option<time::Date>,
}
#[cfg(feature = "ssr")]
impl From<SqlCrateReleaseData> for CrateReleaseData {
fn from(value: SqlCrateReleaseData) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
CrateReleaseData {
id: id_str.to_string(),
title: value.title,
posted_date: value.posted_date,
}
}
}
#[server]
pub async fn fetch_crate_releases(
) -> Result<Vec<CrateReleaseData>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let crate_releases: Vec<SqlCrateReleaseData> = sqlx::query_as!(
SqlCrateReleaseData,
"SELECT
id,
title,
posted_date
FROM crate_release
LEFT JOIN issue__crate_release
ON crate_release.id = issue__crate_release.crate_release_id
WHERE issue__crate_release.issue_id IS NULL
ORDER BY crate_release.id"
)
.fetch_all(&pool)
.await?;
Ok(crate_releases
.into_iter()
.map(CrateReleaseData::from)
.collect())
}
#[server]
async fn associate_crate_release_with_issue(
crate_release_id: String,
issue_id: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issue_id: [u8; 16] = issue_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
let crate_release_id: [u8; 16] = crate_release_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
sqlx::query!(
r#"
INSERT INTO issue__crate_release ( issue_id, crate_release_id )
VALUES ( ?, ? )
"#,
issue_id.as_slice(),
crate_release_id.as_slice()
)
.execute(&pool)
.await
.expect("successful insert");
Ok(())
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlIssueShort {
id: Vec<u8>,
display_name: String,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct IssueShort {
pub id: String,
pub display_name: String,
}
#[cfg(feature = "ssr")]
impl From<SqlIssueShort> for IssueShort {
fn from(value: SqlIssueShort) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
IssueShort {
id: id_str.to_string(),
display_name: value.display_name,
}
}
}
#[server]
async fn fetch_issues(
) -> Result<Vec<IssueShort>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issues: Vec<SqlIssueShort> = sqlx::query_as!(
SqlIssueShort,
r#"SELECT
id,
display_name
FROM issue
WHERE status = "draft"
ORDER BY issue_date DESC"#
)
.fetch_all(&pool)
.await?;
Ok(issues.into_iter().map(IssueShort::from).collect())
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/admin/issue.rs | src/app/routes/admin/issue.rs | use crate::app::components::Divider;
use leptos::{either::Either, prelude::*};
use leptos_router::hooks::use_params_map;
use serde::{Deserialize, Serialize};
#[component]
pub fn Issue() -> impl IntoView {
let params = use_params_map();
let issue = Resource::new(
move || {
params.with(|p| p.get("id").unwrap_or_default())
},
fetch_issue,
);
view! {
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || {
issue
.get()
.map(|data| match data {
Err(e) => Either::Left(view! { <pre>{e.to_string()}</pre> }),
Ok(issue) => {
Either::Right(issue
.map(|issue| {
view! { <IssueForm issue=issue/> }
})
.collect_view())
}
})
}}
</Suspense>
<Divider title="Showcases"/>
<Showcases/>
<Divider title="Crate Releases"/>
<CrateReleases/>
<Divider title="Devlogs"/>
<Devlogs/>
<Divider title="Educationals"/>
<Educationals/>
</div>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlIssueData {
id: Vec<u8>,
slug: String,
issue_date: time::Date,
cloudinary_public_id: String,
status: String,
display_name: String,
description: String,
youtube_id: String,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct IssueData {
pub id: String,
pub slug: String,
pub issue_date: time::Date,
pub cloudinary_public_id: String,
pub status: String,
pub display_name: String,
pub description: String,
pub youtube_id: String,
}
#[cfg(feature = "ssr")]
impl From<SqlIssueData> for IssueData {
fn from(value: SqlIssueData) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
IssueData {
id: id_str.to_string(),
slug: value.slug,
issue_date: value.issue_date,
cloudinary_public_id: value
.cloudinary_public_id,
status: value.status,
display_name: value.display_name,
description: value.description,
youtube_id: value.youtube_id,
}
}
}
#[server]
pub async fn fetch_issue(
id: String,
) -> Result<Option<IssueData>, ServerFnError> {
let id: [u8; 16] = id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issue = sqlx::query_as!(
SqlIssueData,
"SELECT
id,
slug,
issue_date,
cloudinary_public_id,
status,
display_name,
description,
youtube_id
FROM issue
WHERE id = ?",
id.as_slice()
)
.fetch_optional(&pool)
.await?;
Ok(issue.map(IssueData::from))
}
#[server]
pub async fn update_issue_metadata(
issue_id: String,
display_name: String,
slug: String,
cloudinary_public_id: String,
youtube_id: String,
description: String,
) -> Result<(), ServerFnError> {
let pool = use_context::<sqlx::MySqlPool>()
.expect("to be able to access app_state");
let _username = crate::sql::with_admin_access()?;
let id: [u8; 16] = issue_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
sqlx::query!(
r#"
UPDATE issue
SET
display_name = ?,
slug = ?,
cloudinary_public_id = ?,
youtube_id = ?,
description = ?
WHERE id = ?
"#,
display_name,
slug,
cloudinary_public_id,
youtube_id,
description,
id.as_slice()
)
.execute(&pool)
.await
.expect("successful insert");
Ok(())
}
#[component]
fn IssueForm(issue: IssueData) -> impl IntoView {
let update_issue_metadata: ServerAction<
UpdateIssueMetadata,
> = ServerAction::new();
view! {
<div class="isolate bg-white px-6 py-24 sm:py-32 lg:px-8">
<div class="mx-auto max-w-2xl text-center">
<h2 class="text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl">
{issue.issue_date.to_string()}
</h2>
<p class="mt-2 text-lg leading-8 text-gray-600">{issue.status}</p>
</div>
<ActionForm attr:class="mx-auto mt-16 max-w-xl sm:mt-20" action=update_issue_metadata>
<input type="hidden" name="issue_id" id="issue_id" value=issue.id/>
<div class="grid grid-cols-1 gap-x-8 gap-y-6 sm:grid-cols-2">
<div>
<label
for="display_name"
class="block text-sm font-semibold leading-6 text-gray-900"
>
display_name
</label>
<div class="mt-2.5">
<input
type="text"
name="display_name"
id="display_name"
class="block w-full rounded-md border-0 px-3.5 py-2 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
value=issue.display_name
/>
</div>
</div>
<div>
<label
for="slug"
class="block text-sm font-semibold leading-6 text-gray-900"
>
slug
</label>
<div class="mt-2.5">
<input
type="text"
name="slug"
id="slug"
class="block w-full rounded-md border-0 px-3.5 py-2 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
value=issue.slug
/>
</div>
</div>
<div class="sm:col-span-2">
<label
for="cloudinary_public_id"
class="block text-sm font-semibold leading-6 text-gray-900"
>
cloudinary_public_id
</label>
<div class="mt-2.5">
<input
type="text"
name="cloudinary_public_id"
id="cloudinary_public_id"
class="block w-full rounded-md border-0 px-3.5 py-2 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
value=issue.cloudinary_public_id
/>
</div>
</div>
<div class="sm:col-span-2">
<label
for="youtube_id"
class="block text-sm font-semibold leading-6 text-gray-900"
>
youtube_id
</label>
<div class="mt-2.5">
<input
type="youtube_id"
name="youtube_id"
id="youtube_id"
class="block w-full rounded-md border-0 px-3.5 py-2 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
value=issue.youtube_id
/>
</div>
</div>
<div class="sm:col-span-2">
<label
for="description"
class="block text-sm font-semibold leading-6 text-gray-900"
>
description
</label>
<div class="mt-2.5">
<textarea
name="description"
id="description"
rows="4"
class="block w-full rounded-md border-0 px-3.5 py-2 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
>
{issue.description}
</textarea>
</div>
</div>
</div>
<div class="mt-10">
<button
type="submit"
class="block w-full rounded-md bg-indigo-600 px-3.5 py-2.5 text-center text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Save
</button>
</div>
</ActionForm>
</div>
}
}
#[component]
fn Showcases() -> impl IntoView {
let params = use_params_map();
let showcases = Resource::new(
move || {
params.with(|p| p.get("id").unwrap_or_default())
},
fetch_showcases_for_issue_id,
);
view! {
<ul
role="list"
class="divide-y divide-gray-100 overflow-hidden bg-white shadow-sm ring-1 ring-gray-900/5 sm:rounded-xl"
>
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || {
showcases
.get()
.map(|data| match data {
Err(e) => Either::Left(view! { <pre>{e.to_string()}</pre> }),
Ok(showcases) => {
Either::Right(showcases
.iter()
.map(|showcase| {
view! { <ShowcaseLi showcase=showcase.clone()/> }
})
.collect_view())
}
})
}}
</Suspense>
</ul>
}
}
#[component]
fn ShowcaseLi(showcase: ShowcaseData) -> impl IntoView {
view! {
<li class="relative flex justify-between gap-x-6 px-4 py-5 hover:bg-gray-50 sm:px-6">
<div class="flex min-w-0 gap-x-4">
<div class="min-w-0 flex-auto">
<p class="text-sm font-semibold leading-6 text-gray-900">
<a href=format!("/admin/showcase/{}", showcase.id)>
<span class="absolute inset-x-0 -top-px bottom-0"></span>
{showcase.title}
</a>
</p>
{showcase
.posted_date
.map(|posted_date| {
view! {
<p class="mt-1 flex text-xs leading-5 text-gray-500">
<span>"posted at"</span>
<time datetime=posted_date.to_string() class="ml-1">
{posted_date.to_string()}
</time>
</p>
}
})}
</div>
</div>
<div class="flex shrink-0 items-center gap-x-4">
<div class="hidden sm:flex sm:flex-col sm:items-end">
<p class="text-sm leading-6 text-gray-900">{showcase.image_count} images</p>
// <p class="mt-1 text-xs leading-5 text-gray-500">Last seen <time datetime="2023-01-23T13:23Z">3h ago</time></p>
</div>
<svg
class="h-5 w-5 flex-none text-gray-400"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z"
clip-rule="evenodd"
></path>
</svg>
</div>
</li>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlShowcaseData {
id: Vec<u8>,
title: String,
posted_date: Option<time::Date>,
image_count: Option<i64>,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct ShowcaseData {
pub id: String,
pub title: String,
pub posted_date: Option<time::Date>,
pub image_count: u32,
}
#[cfg(feature = "ssr")]
impl From<SqlShowcaseData> for ShowcaseData {
fn from(value: SqlShowcaseData) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
ShowcaseData {
id: id_str.to_string(),
title: value.title,
posted_date: value.posted_date,
image_count: value
.image_count
.unwrap_or_default()
as u32,
}
}
}
#[server]
pub async fn fetch_showcases_for_issue_id(
issue_id: String,
) -> Result<Vec<ShowcaseData>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issue_id: [u8; 16] = issue_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
let showcases: Vec<SqlShowcaseData> = sqlx::query_as!(
SqlShowcaseData,
"SELECT
showcase.id,
showcase.title,
showcase.posted_date,
si.image_count
FROM issue__showcase
INNER JOIN showcase
ON showcase.id = issue__showcase.showcase_id
LEFT JOIN (
SELECT showcase__image.showcase_id, COUNT(*) as image_count
FROM showcase__image
GROUP BY showcase__image.showcase_id
) AS si ON si.showcase_id = showcase.id
WHERE issue__showcase.issue_id = ?
ORDER BY showcase.posted_date",
issue_id.as_slice()
)
.fetch_all(&pool)
.await?;
Ok(showcases
.into_iter()
.map(ShowcaseData::from)
.collect())
}
// crate_releases
#[component]
fn CrateReleases() -> impl IntoView {
let params = use_params_map();
let crate_releases = Resource::new(
move || {
params.with(|p| p.get("id").unwrap_or_default())
},
fetch_crate_releases_for_issue_id,
);
view! {
<ul
role="list"
class="divide-y divide-gray-100 overflow-hidden bg-white shadow-sm ring-1 ring-gray-900/5 sm:rounded-xl"
>
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || {
crate_releases
.get()
.map(|data| match data {
Err(e) => Either::Left(view! { <pre>{e.to_string()}</pre> }),
Ok(crate_releases) => {
Either::Right(crate_releases
.iter()
.map(|crate_release| {
view! {
<CrateReleaseLi crate_release=crate_release.clone()/>
}
})
.collect_view())
}
})
}}
</Suspense>
</ul>
}
}
#[component]
fn CrateReleaseLi(
crate_release: CrateReleaseData,
) -> impl IntoView {
view! {
<li class="relative flex justify-between gap-x-6 px-4 py-5 hover:bg-gray-50 sm:px-6">
<div class="flex min-w-0 gap-x-4">
<div class="min-w-0 flex-auto">
<p class="text-sm font-semibold leading-6 text-gray-900">
<a href=format!("/admin/crate_release/{}", crate_release.id)>
<span class="absolute inset-x-0 -top-px bottom-0"></span>
{crate_release.title}
</a>
</p>
{crate_release
.posted_date
.map(|posted_date| {
view! {
<p class="mt-1 flex text-xs leading-5 text-gray-500">
<span>"posted at"</span>
<time datetime=posted_date.to_string() class="ml-1">
{posted_date.to_string()}
</time>
</p>
}
})}
</div>
</div>
<div class="flex shrink-0 items-center gap-x-4">
<div class="hidden sm:flex sm:flex-col sm:items-end">
<p class="text-sm leading-6 text-gray-900">
{crate_release.image_count} images
</p>
// <p class="mt-1 text-xs leading-5 text-gray-500">Last seen <time datetime="2023-01-23T13:23Z">3h ago</time></p>
</div>
<svg
class="h-5 w-5 flex-none text-gray-400"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z"
clip-rule="evenodd"
></path>
</svg>
</div>
</li>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlCrateReleaseData {
id: Vec<u8>,
title: String,
posted_date: Option<time::Date>,
image_count: Option<i64>,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct CrateReleaseData {
pub id: String,
pub title: String,
pub posted_date: Option<time::Date>,
pub image_count: u32,
}
#[cfg(feature = "ssr")]
impl From<SqlCrateReleaseData> for CrateReleaseData {
fn from(value: SqlCrateReleaseData) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
CrateReleaseData {
id: id_str.to_string(),
title: value.title,
posted_date: value.posted_date,
image_count: value
.image_count
.unwrap_or_default()
as u32,
}
}
}
#[server]
pub async fn fetch_crate_releases_for_issue_id(
issue_id: String,
) -> Result<Vec<CrateReleaseData>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issue_id: [u8; 16] = issue_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
let crate_releases: Vec<SqlCrateReleaseData> = sqlx::query_as!(
SqlCrateReleaseData,
"SELECT
crate_release.id,
crate_release.title,
crate_release.posted_date,
si.image_count
FROM issue__crate_release
INNER JOIN crate_release
ON crate_release.id = issue__crate_release.crate_release_id
LEFT JOIN (
SELECT crate_release__image.crate_release_id, COUNT(*) as image_count
FROM crate_release__image
GROUP BY crate_release__image.crate_release_id
) AS si ON si.crate_release_id = crate_release.id
WHERE issue__crate_release.issue_id = ?
ORDER BY crate_release.posted_date",
issue_id.as_slice()
)
.fetch_all(&pool)
.await?;
Ok(crate_releases
.into_iter()
.map(CrateReleaseData::from)
.collect())
}
// devlogs
#[component]
fn Devlogs() -> impl IntoView {
let params = use_params_map();
let devlogs = Resource::new(
move || {
params.with(|p| p.get("id").unwrap_or_default())
},
fetch_devlogs_for_issue_id,
);
view! {
<ul
role="list"
class="divide-y divide-gray-100 overflow-hidden bg-white shadow-sm ring-1 ring-gray-900/5 sm:rounded-xl"
>
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || {
devlogs
.get()
.map(|data| match data {
Err(e) => Either::Left(view! { <pre>{e.to_string()}</pre> }),
Ok(devlogs) => {
Either::Right(devlogs
.iter()
.map(|devlog| {
view! { <DevlogLi devlog=devlog.clone()/> }
})
.collect_view())
}
})
}}
</Suspense>
</ul>
}
}
#[component]
fn DevlogLi(devlog: DevlogData) -> impl IntoView {
view! {
<li class="relative flex justify-between gap-x-6 px-4 py-5 hover:bg-gray-50 sm:px-6">
<div class="flex min-w-0 gap-x-4">
<div class="min-w-0 flex-auto">
<p class="text-sm font-semibold leading-6 text-gray-900">
<a href=format!("/admin/devlog/{}", devlog.id)>
<span class="absolute inset-x-0 -top-px bottom-0"></span>
{devlog.title}
</a>
</p>
{devlog
.posted_date
.map(|posted_date| {
view! {
<p class="mt-1 flex text-xs leading-5 text-gray-500">
<span>"posted at"</span>
<time datetime=posted_date.to_string() class="ml-1">
{posted_date.to_string()}
</time>
</p>
}
})}
</div>
</div>
<div class="flex shrink-0 items-center gap-x-4">
<div class="hidden sm:flex sm:flex-col sm:items-end">
<p class="text-sm leading-6 text-gray-900">{devlog.image_count} images</p>
// <p class="mt-1 text-xs leading-5 text-gray-500">Last seen <time datetime="2023-01-23T13:23Z">3h ago</time></p>
</div>
<svg
class="h-5 w-5 flex-none text-gray-400"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z"
clip-rule="evenodd"
></path>
</svg>
</div>
</li>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlDevlogData {
id: Vec<u8>,
title: String,
posted_date: Option<time::Date>,
image_count: Option<i64>,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct DevlogData {
pub id: String,
pub title: String,
pub posted_date: Option<time::Date>,
pub image_count: u32,
}
#[cfg(feature = "ssr")]
impl From<SqlDevlogData> for DevlogData {
fn from(value: SqlDevlogData) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
DevlogData {
id: id_str.to_string(),
title: value.title,
posted_date: value.posted_date,
image_count: value
.image_count
.unwrap_or_default()
as u32,
}
}
}
#[server]
pub async fn fetch_devlogs_for_issue_id(
issue_id: String,
) -> Result<Vec<DevlogData>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issue_id: [u8; 16] = issue_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
let devlogs: Vec<SqlDevlogData> = sqlx::query_as!(
SqlDevlogData,
"SELECT
devlog.id,
devlog.title,
devlog.posted_date,
si.image_count
FROM issue__devlog
INNER JOIN devlog
ON devlog.id = issue__devlog.devlog_id
LEFT JOIN (
SELECT devlog__image.devlog_id, COUNT(*) as image_count
FROM devlog__image
GROUP BY devlog__image.devlog_id
) AS si ON si.devlog_id = devlog.id
WHERE issue__devlog.issue_id = ?
ORDER BY devlog.posted_date",
issue_id.as_slice()
)
.fetch_all(&pool)
.await?;
Ok(devlogs.into_iter().map(DevlogData::from).collect())
}
// educationals
#[component]
fn Educationals() -> impl IntoView {
let params = use_params_map();
let educationals = Resource::new(
move || {
params.with(|p| p.get("id").unwrap_or_default())
},
fetch_educationals_for_issue_id,
);
view! {
<ul
role="list"
class="divide-y divide-gray-100 overflow-hidden bg-white shadow-sm ring-1 ring-gray-900/5 sm:rounded-xl"
>
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || {
educationals
.get()
.map(|data| match data {
Err(e) => Either::Left(view! { <pre>{e.to_string()}</pre> }),
Ok(educationals) => {
Either::Right(educationals
.iter()
.map(|educational| {
view! { <EducationalLi educational=educational.clone()/> }
})
.collect_view())
}
})
}}
</Suspense>
</ul>
}
}
#[component]
fn EducationalLi(
educational: EducationalData,
) -> impl IntoView {
view! {
<li class="relative flex justify-between gap-x-6 px-4 py-5 hover:bg-gray-50 sm:px-6">
<div class="flex min-w-0 gap-x-4">
<div class="min-w-0 flex-auto">
<p class="text-sm font-semibold leading-6 text-gray-900">
<a href=format!("/admin/educational/{}", educational.id)>
<span class="absolute inset-x-0 -top-px bottom-0"></span>
{educational.title}
</a>
</p>
{educational
.posted_date
.map(|posted_date| {
view! {
<p class="mt-1 flex text-xs leading-5 text-gray-500">
<span>"posted at"</span>
<time datetime=posted_date.to_string() class="ml-1">
{posted_date.to_string()}
</time>
</p>
}
})}
</div>
</div>
<div class="flex shrink-0 items-center gap-x-4">
<div class="hidden sm:flex sm:flex-col sm:items-end">
<p class="text-sm leading-6 text-gray-900">{educational.image_count} images</p>
// <p class="mt-1 text-xs leading-5 text-gray-500">Last seen <time datetime="2023-01-23T13:23Z">3h ago</time></p>
</div>
<svg
class="h-5 w-5 flex-none text-gray-400"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z"
clip-rule="evenodd"
></path>
</svg>
</div>
</li>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlEducationalData {
id: Vec<u8>,
title: String,
posted_date: Option<time::Date>,
image_count: Option<i64>,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct EducationalData {
pub id: String,
pub title: String,
pub posted_date: Option<time::Date>,
pub image_count: u32,
}
#[cfg(feature = "ssr")]
impl From<SqlEducationalData> for EducationalData {
fn from(value: SqlEducationalData) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
EducationalData {
id: id_str.to_string(),
title: value.title,
posted_date: value.posted_date,
image_count: value
.image_count
.unwrap_or_default()
as u32,
}
}
}
#[server]
pub async fn fetch_educationals_for_issue_id(
issue_id: String,
) -> Result<Vec<EducationalData>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issue_id: [u8; 16] = issue_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
let educationals: Vec<SqlEducationalData> = sqlx::query_as!(
SqlEducationalData,
"SELECT
educational.id,
educational.title,
educational.posted_date,
si.image_count
FROM issue__educational
INNER JOIN educational
ON educational.id = issue__educational.educational_id
LEFT JOIN (
SELECT educational__image.educational_id, COUNT(*) as image_count
FROM educational__image
GROUP BY educational__image.educational_id
) AS si ON si.educational_id = educational.id
WHERE issue__educational.issue_id = ?
ORDER BY educational.posted_date",
issue_id.as_slice()
)
.fetch_all(&pool)
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | true |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/admin/devlog.rs | src/app/routes/admin/devlog.rs | use crate::app::components::Divider;
use futures::future::join;
use leptos::{either::EitherOf3, prelude::*};
use serde::{Deserialize, Serialize};
pub mod id;
#[server]
async fn add_devlog(
title: String,
video_url: String,
post_url: String,
discord_url: String,
description: String,
posted_date: String,
) -> Result<(), ServerFnError> {
let pool = use_context::<sqlx::MySqlPool>()
.expect("to be able to access app_state");
let username = crate::sql::with_admin_access()?;
let id: [u8; 16] = rusty_ulid::generate_ulid_bytes();
sqlx::query!(
r#"
INSERT INTO devlog ( id, title, video_url, post_url, discord_url, posted_date, description, submitted_by )
VALUES ( ?, ?, ?, ?, ?, ?, ?, ? )
"#,
id.as_slice(),
title,
video_url,
post_url,
discord_url,
posted_date,
description,
username.0
)
.execute(&pool)
.await
.expect("successful insert");
Ok(())
}
#[component]
pub fn Devlog() -> impl IntoView {
let add_devlog: ServerAction<AddDevlog> =
ServerAction::new();
let devlogs = Resource::new(
move || {},
|_| join(fetch_devlogs(), fetch_issues()),
);
view! {
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<ActionForm attr:class="isolate -space-y-px rounded-md shadow-sm" action=add_devlog>
<div class="relative rounded-md rounded-b-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="title" class="block text-xs font-medium text-gray-900">
Title
</label>
<input
required
type="text"
name="title"
id="title"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="Hexagon procedural generation"
/>
</div>
<div class="relative px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="video_url" class="block text-xs font-medium text-gray-900">
Video URL
</label>
<input
required
type="text"
name="video_url"
id="video_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="https://www.youtube.com/watch?v=Jcw_v1w7dbI"
/>
</div>
<div class="relative px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="post_url" class="block text-xs font-medium text-gray-900">
Post URL
</label>
<input
required
type="text"
name="post_url"
id="post_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="https://www.nikl.me/blog/2024/bevy_ecs_as_data_layer_in_leptos_ssg/"
/>
</div>
<div class="relative rounded-md rounded-t-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="discord_url" class="block text-xs font-medium text-gray-900">
Discord URL
</label>
<input
type="text"
name="discord_url"
id="discord_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="https"
/>
</div>
<label
for="posted_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
Posted At
</label>
<div class="mt-2">
<input required type="date" id="posted_date" name="posted_date" min="2024-01-01"/>
</div>
<label
for="description"
class="block text-sm font-medium leading-6 text-gray-900"
>
Add your description (markdown compatible)
</label>
<div class="mt-2">
<textarea
required
rows="4"
name="description"
id="description"
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
></textarea>
</div>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Add Devlog
</button>
</ActionForm>
<Divider title="Devlogs without an issue"/>
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || devlogs
.get()
.map(|data| match data {
(Err(e), Err(e2)) => {
EitherOf3::A(view! {
<div>
<div>{e.to_string()}</div>
<div>{e2.to_string()}</div>
</div>
})
}
(_, Err(e)) | (Err(e), _) => {
EitherOf3::B(view! {
<div>
<div>{e.to_string()}</div>
</div>
})
}
(Ok(devlogs), Ok(issues)) => {
EitherOf3::C(view! {
<div>
<ul role="list" class="divide-y divide-gray-100">
<For
each=move || devlogs.clone()
key=|devlog| devlog.id.clone()
let:devlog
>
<AddDevlogToIssueForm
devlog=devlog
issue_id=issues.first().map(|issue| issue.id.clone())
/>
</For>
</ul>
</div>
})
}
})}
</Suspense>
</div>
}
}
#[component]
fn AddDevlogToIssueForm(
devlog: DevlogData,
issue_id: Option<String>,
) -> impl IntoView {
let associate_devlog_with_issue: ServerAction<
AssociateDevlogWithIssue,
> = ServerAction::new();
view! {
<li class="flex items-center justify-between gap-x-6 py-5">
<div class="min-w-0">
<div class="flex items-start gap-x-3">
<p class="text-sm font-semibold leading-6 text-gray-900">{devlog.title}</p>
</div>
<div class="mt-1 flex items-center gap-x-2 text-xs leading-5 text-gray-500">
<p class="whitespace-nowrap">
posted on
<time datetime=devlog
.posted_date
.as_ref()
.unwrap()
.to_string()>{devlog.posted_date.as_ref().unwrap().to_string()}</time>
</p>
<svg viewBox="0 0 2 2" class="h-0.5 w-0.5 fill-current">
<circle cx="1" cy="1" r="1"></circle>
</svg>
// <p class="truncate">Submitted by {devlog.submitted_by}</p>
</div>
</div>
{issue_id
.map(|issue_id| {
view! {
<div class="flex flex-none items-center gap-x-4">
<ActionForm action=associate_devlog_with_issue>
<input type="hidden" value=devlog.id name="devlog_id"/>
<input type="hidden" value=issue_id name="issue_id"/>
<button
type="submit"
class="hidden rounded-md bg-white px-2.5 py-1.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:block"
>
Add to current draft
</button>
</ActionForm>
</div>
}
})}
</li>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlDevlogData {
id: Vec<u8>,
title: String,
posted_date: Option<time::Date>,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct DevlogData {
pub id: String,
pub title: String,
pub posted_date: Option<time::Date>,
}
#[cfg(feature = "ssr")]
impl From<SqlDevlogData> for DevlogData {
fn from(value: SqlDevlogData) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
DevlogData {
id: id_str.to_string(),
title: value.title,
posted_date: value.posted_date,
}
}
}
#[server]
pub async fn fetch_devlogs(
) -> Result<Vec<DevlogData>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let devlogs: Vec<SqlDevlogData> = sqlx::query_as!(
SqlDevlogData,
"SELECT
id,
title,
posted_date
FROM devlog
LEFT JOIN issue__devlog
ON devlog.id = issue__devlog.devlog_id
WHERE issue__devlog.issue_id IS NULL
ORDER BY devlog.id"
)
.fetch_all(&pool)
.await?;
Ok(devlogs.into_iter().map(DevlogData::from).collect())
}
#[server]
async fn associate_devlog_with_issue(
devlog_id: String,
issue_id: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issue_id: [u8; 16] = issue_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
let devlog_id: [u8; 16] = devlog_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
sqlx::query!(
r#"
INSERT INTO issue__devlog ( issue_id, devlog_id )
VALUES ( ?, ? )
"#,
issue_id.as_slice(),
devlog_id.as_slice()
)
.execute(&pool)
.await
.expect("successful insert");
Ok(())
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlIssueShort {
id: Vec<u8>,
display_name: String,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct IssueShort {
pub id: String,
pub display_name: String,
}
#[cfg(feature = "ssr")]
impl From<SqlIssueShort> for IssueShort {
fn from(value: SqlIssueShort) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
IssueShort {
id: id_str.to_string(),
display_name: value.display_name,
}
}
}
#[server]
async fn fetch_issues(
) -> Result<Vec<IssueShort>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issues: Vec<SqlIssueShort> = sqlx::query_as!(
SqlIssueShort,
r#"SELECT
id,
display_name
FROM issue
WHERE status = "draft"
ORDER BY issue_date DESC"#
)
.fetch_all(&pool)
.await?;
Ok(issues.into_iter().map(IssueShort::from).collect())
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/admin/educational.rs | src/app/routes/admin/educational.rs | use crate::app::components::Divider;
use futures::future::join;
use leptos::{either::EitherOf3, prelude::*};
use serde::{Deserialize, Serialize};
pub mod id;
#[server]
async fn add_educational(
title: String,
video_url: String,
post_url: String,
discord_url: String,
description: String,
posted_date: String,
) -> Result<(), ServerFnError> {
let pool = use_context::<sqlx::MySqlPool>()
.expect("to be able to access app_state");
let username = crate::sql::with_admin_access()?;
let id: [u8; 16] = rusty_ulid::generate_ulid_bytes();
sqlx::query!(
r#"
INSERT INTO educational ( id, title, video_url, post_url, discord_url, posted_date, description, submitted_by )
VALUES ( ?, ?, ?, ?, ?, ?, ?, ? )
"#,
id.as_slice(),
title,
video_url,
post_url,
discord_url,
posted_date,
description,
username.0
)
.execute(&pool)
.await
.expect("successful insert");
Ok(())
}
#[component]
pub fn Educational() -> impl IntoView {
let add_educational: ServerAction<AddEducational> =
ServerAction::new();
let educationals = Resource::new(
move || {},
|_| join(fetch_educationals(), fetch_issues()),
);
view! {
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<ActionForm attr:class="isolate -space-y-px rounded-md shadow-sm" action=add_educational>
<div class="relative rounded-md rounded-b-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="title" class="block text-xs font-medium text-gray-900">
Title
</label>
<input
required
type="text"
name="title"
id="title"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="Hexagon procedural generation"
/>
</div>
<div class="relative px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="video_url" class="block text-xs font-medium text-gray-900">
Video URL
</label>
<input
required
type="text"
name="video_url"
id="video_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="https://www.youtube.com/watch?v=Jcw_v1w7dbI"
/>
</div>
<div class="relative px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="post_url" class="block text-xs font-medium text-gray-900">
Post URL
</label>
<input
required
type="text"
name="post_url"
id="post_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="https://www.nikl.me/blog/2024/bevy_ecs_as_data_layer_in_leptos_ssg/"
/>
</div>
<div class="relative rounded-md rounded-t-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="discord_url" class="block text-xs font-medium text-gray-900">
Discord URL
</label>
<input
type="text"
name="discord_url"
id="discord_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="https"
/>
</div>
<label
for="posted_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
Posted At
</label>
<div class="mt-2">
<input type="date" required id="posted_date" name="posted_date" min="2024-01-01"/>
</div>
<label
for="description"
class="block text-sm font-medium leading-6 text-gray-900"
>
Add your description (markdown compatible)
</label>
<div class="mt-2">
<textarea
required
rows="4"
name="description"
id="description"
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
></textarea>
</div>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Add Educational
</button>
</ActionForm>
<Divider title="Educationals without an issue"/>
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || educationals
.get()
.map(|data| match data {
(Err(e), Err(e2)) => {
EitherOf3::A(view! {
<div>
<div>{e.to_string()}</div>
<div>{e2.to_string()}</div>
</div>
})
}
(_, Err(e)) | (Err(e), _) => {
EitherOf3::B(view! {
<div>
<div>{e.to_string()}</div>
</div>
})
}
(Ok(educationals), Ok(issues)) => {
EitherOf3::C(view! {
<div>
<ul role="list" class="divide-y divide-gray-100">
<For
each=move || educationals.clone()
key=|educational| educational.id.clone()
let:educational
>
<AddEducationalToIssueForm
educational=educational
issue_id=issues.first().map(|issue| issue.id.clone())
/>
</For>
</ul>
</div>
})
}
})}
</Suspense>
</div>
}
}
#[component]
fn AddEducationalToIssueForm(
educational: EducationalData,
issue_id: Option<String>,
) -> impl IntoView {
let associate_educational_with_issue: ServerAction<
AssociateEducationalWithIssue,
> = ServerAction::new();
view! {
<li class="flex items-center justify-between gap-x-6 py-5">
<div class="min-w-0">
<div class="flex items-start gap-x-3">
<p class="text-sm font-semibold leading-6 text-gray-900">{educational.title}</p>
</div>
<div class="mt-1 flex items-center gap-x-2 text-xs leading-5 text-gray-500">
<p class="whitespace-nowrap">
posted on
<time datetime=educational
.posted_date
.as_ref()
.unwrap()
.to_string()>
{educational.posted_date.as_ref().unwrap().to_string()}
</time>
</p>
<svg viewBox="0 0 2 2" class="h-0.5 w-0.5 fill-current">
<circle cx="1" cy="1" r="1"></circle>
</svg>
// <p class="truncate">Submitted by {educational.submitted_by}</p>
</div>
</div>
{issue_id
.map(|issue_id| {
view! {
<div class="flex flex-none items-center gap-x-4">
<ActionForm action=associate_educational_with_issue>
<input type="hidden" value=educational.id name="educational_id"/>
<input type="hidden" value=issue_id name="issue_id"/>
<button
type="submit"
class="hidden rounded-md bg-white px-2.5 py-1.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:block"
>
Add to current draft
</button>
</ActionForm>
</div>
}
})}
</li>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlEducationalData {
id: Vec<u8>,
title: String,
posted_date: Option<time::Date>,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct EducationalData {
pub id: String,
pub title: String,
pub posted_date: Option<time::Date>,
}
#[cfg(feature = "ssr")]
impl From<SqlEducationalData> for EducationalData {
fn from(value: SqlEducationalData) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
EducationalData {
id: id_str.to_string(),
title: value.title,
posted_date: value.posted_date,
}
}
}
#[server]
pub async fn fetch_educationals(
) -> Result<Vec<EducationalData>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let educationals: Vec<SqlEducationalData> =
sqlx::query_as!(
SqlEducationalData,
"SELECT
id,
title,
posted_date
FROM educational
LEFT JOIN issue__educational
ON educational.id = issue__educational.educational_id
WHERE issue__educational.issue_id IS NULL
ORDER BY educational.id"
)
.fetch_all(&pool)
.await?;
Ok(educationals
.into_iter()
.map(EducationalData::from)
.collect())
}
#[server]
async fn associate_educational_with_issue(
educational_id: String,
issue_id: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issue_id: [u8; 16] = issue_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
let educational_id: [u8; 16] = educational_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
sqlx::query!(
r#"
INSERT INTO issue__educational ( issue_id, educational_id )
VALUES ( ?, ? )
"#,
issue_id.as_slice(),
educational_id.as_slice()
)
.execute(&pool)
.await
.expect("successful insert");
Ok(())
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlIssueShort {
id: Vec<u8>,
display_name: String,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct IssueShort {
pub id: String,
pub display_name: String,
}
#[cfg(feature = "ssr")]
impl From<SqlIssueShort> for IssueShort {
fn from(value: SqlIssueShort) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
IssueShort {
id: id_str.to_string(),
display_name: value.display_name,
}
}
}
#[server]
async fn fetch_issues(
) -> Result<Vec<IssueShort>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issues: Vec<SqlIssueShort> = sqlx::query_as!(
SqlIssueShort,
r#"SELECT
id,
display_name
FROM issue
WHERE status = "draft"
ORDER BY issue_date DESC"#
)
.fetch_all(&pool)
.await?;
Ok(issues.into_iter().map(IssueShort::from).collect())
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/admin/github.rs | src/app/routes/admin/github.rs | use crate::app::components::Divider;
use crate::app::server_fn::error::NoCustomError;
use leptos::{either::EitherOf3, prelude::*};
use serde::{Deserialize, Serialize};
#[component]
pub fn GitHub() -> impl IntoView {
let select_new_github_issues: ServerAction<
SelectNewGithubIssues,
> = ServerAction::new();
let select_new_pull_requests: ServerAction<
SelectNewPullRequests,
> = ServerAction::new();
let select_merged_pull_requests: ServerAction<
SelectMergedPullRequests,
> = ServerAction::new();
let issues =
Resource::new(move || {}, |_| fetch_issues());
view! {
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || match issues.get() {
None => EitherOf3::A(view! { <div>error</div> }),
Some(Err(e)) => EitherOf3::B(view! { <div>{e.to_string()}</div> }),
Some(Ok(issues)) => {
let issues_a = issues.clone();
let issues_b = issues.clone();
EitherOf3::C(view! {
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<Divider title="new github issues"/>
<ActionForm
action=select_new_github_issues
attr:class="isolate -space-y-px rounded-md shadow-sm"
>
<label
for="issue_id"
class="block text-sm font-medium leading-6 text-gray-900"
>
issue_id
</label>
<select
name="issue_id"
class="mt-2 block w-full rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-indigo-600 sm:text-sm sm:leading-6"
>
{issues_a
.iter()
.map(|issue| {
view! {
<option value=issue.id.clone()>
{issue.issue_date.to_string()} - {issue.display_name.clone()}
</option>
}
})
.collect_view()}
</select>
<label
for="start_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
Start Date
</label>
<div class="mt-2">
<input
type="date"
id="start_date"
name="start_date"
min="2024-01-01"
/>
</div>
<label
for="end_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
End Date
</label>
<div class="mt-2">
<input
type="date"
id="end_date"
name="end_date"
min="2024-01-01"
/>
</div>
<button type="submit">Add to Issue</button>
</ActionForm>
<Divider title="new pull requests"/>
<ActionForm
action=select_new_pull_requests
attr:class="isolate -space-y-px rounded-md shadow-sm"
>
<label
for="issue_id"
class="block text-sm font-medium leading-6 text-gray-900"
>
issue_id
</label>
<select
name="issue_id"
class="mt-2 block w-full rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-indigo-600 sm:text-sm sm:leading-6"
>
{issues_b
.clone()
.iter()
.map(|issue| {
view! {
<option value=issue.id.clone()>
{issue.issue_date.to_string()} - {issue.display_name.clone()}
</option>
}
})
.collect_view()}
</select>
<label
for="start_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
Start Date
</label>
<div class="mt-2">
<input
type="date"
id="start_date"
name="start_date"
min="2024-01-01"
/>
</div>
<label
for="end_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
End Date
</label>
<div class="mt-2">
<input
type="date"
id="end_date"
name="end_date"
min="2024-01-01"
/>
</div>
<button type="submit">Add to Issue</button>
</ActionForm>
<Divider title="merged pull requests"/>
<ActionForm
action=select_merged_pull_requests
attr:class="isolate -space-y-px rounded-md shadow-sm"
>
<label
for="issue_id"
class="block text-sm font-medium leading-6 text-gray-900"
>
issue_id
</label>
<select
name="issue_id"
class="mt-2 block w-full rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-indigo-600 sm:text-sm sm:leading-6"
>
{issues
.iter()
.map(|issue| {
view! {
<option value=issue.id.clone()>
{issue.issue_date.to_string()} - {issue.display_name.clone()}
</option>
}
})
.collect_view()}
</select>
<label
for="start_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
Start Date
</label>
<div class="mt-2">
<input
type="date"
id="start_date"
name="start_date"
min="2024-01-01"
/>
</div>
<label
for="end_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
End Date
</label>
<div class="mt-2">
<input
type="date"
id="end_date"
name="end_date"
min="2024-01-01"
/>
</div>
<button type="submit">Add to Issue</button>
</ActionForm>
</div>
})
}
}}
</Suspense>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlIssueShort {
id: Vec<u8>,
display_name: String,
issue_date: time::Date,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct IssueShort {
pub id: String,
pub display_name: String,
issue_date: time::Date,
}
#[cfg(feature = "ssr")]
impl From<SqlIssueShort> for IssueShort {
fn from(value: SqlIssueShort) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
IssueShort {
id: id_str.to_string(),
display_name: value.display_name,
issue_date: value.issue_date,
}
}
}
#[server]
async fn fetch_issues(
) -> Result<Vec<IssueShort>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issues: Vec<SqlIssueShort> = sqlx::query_as!(
SqlIssueShort,
r#"SELECT
id,
display_name,
issue_date
FROM issue
WHERE status = "draft"
ORDER BY issue_date DESC"#
)
.fetch_all(&pool)
.await?;
Ok(issues.into_iter().map(IssueShort::from).collect())
}
#[server]
pub async fn select_new_github_issues(
issue_id: String,
start_date: time::Date,
end_date: time::Date,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
tracing::info!(
issue_id,
?start_date,
?end_date,
"select_new_github_issue"
);
let issue_id: [u8; 16] = issue_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
sqlx::query!(
"INSERT INTO issue__new_github_issue (issue_id, github_issue_id )
SELECT ?, ngi.id
FROM new_github_issue ngi
WHERE gh_created_at BETWEEN ? AND ?",
issue_id.as_slice(),
start_date,
end_date,
)
.execute(&pool)
.await
.map_err(|e| {
tracing::error!(?e);
ServerFnError::<NoCustomError>::ServerError(
e.to_string(),
)
})?;
Ok(())
}
#[server]
pub async fn select_new_pull_requests(
issue_id: String,
start_date: time::Date,
end_date: time::Date,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issue_id: [u8; 16] = issue_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
sqlx::query!(
"INSERT INTO issue__new_pull_request (issue_id, pull_request_id )
SELECT ?, ngi.id
FROM new_pull_request ngi
WHERE gh_created_at BETWEEN ? AND ?",
issue_id.as_slice(),
start_date,
end_date,
)
.execute(&pool)
.await
.map_err(|e| {
tracing::error!(?e);
ServerFnError::<NoCustomError>::ServerError(
e.to_string(),
)
})?;
Ok(())
}
#[server]
pub async fn select_merged_pull_requests(
issue_id: String,
start_date: time::Date,
end_date: time::Date,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issue_id: [u8; 16] = issue_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
sqlx::query!(
"INSERT INTO issue__merged_pull_request (issue_id, merged_pull_request_id )
SELECT ?, ngi.id
FROM merged_pull_request ngi
WHERE merged_at_date BETWEEN ? AND ?",
issue_id.as_slice(),
start_date,
end_date,
)
.execute(&pool)
.await
.map_err(|e| {
tracing::error!(?e);
ServerFnError::<NoCustomError>::ServerError(
e.to_string(),
)
})?;
Ok(())
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/admin/showcase.rs | src/app/routes/admin/showcase.rs | use crate::app::components::Divider;
use futures::future::join;
use leptos::{either::EitherOf3, prelude::*};
use serde::{Deserialize, Serialize};
pub mod id;
#[server]
async fn add_showcase(
title: String,
url: String,
discord_url: String,
description: String,
posted_date: String,
) -> Result<(), ServerFnError> {
let pool = use_context::<sqlx::MySqlPool>()
.expect("to be able to access app_state");
let username = crate::sql::with_admin_access()?;
let id: [u8; 16] = rusty_ulid::generate_ulid_bytes();
sqlx::query!(
r#"
INSERT INTO showcase ( id, title, url, discord_url, posted_date, description, submitted_by )
VALUES ( ?, ?, ?, ?, ?, ?, ? )
"#,
id.as_slice(),
title,
url,
discord_url,
posted_date,
description,
username.0
)
.execute(&pool)
.await
.expect("successful insert");
Ok(())
}
#[component]
pub fn Showcase() -> impl IntoView {
let add_showcase: ServerAction<AddShowcase> =
ServerAction::new();
let showcases = Resource::new(
move || {},
|_| join(fetch_showcases(), fetch_issues()),
);
view! {
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<ActionForm attr:class="isolate -space-y-px rounded-md shadow-sm" action=add_showcase>
<div class="relative rounded-md rounded-b-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="title" class="block text-xs font-medium text-gray-900">
Title
</label>
<input
required
type="text"
name="title"
id="title"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="Hexagon procedural generation"
/>
</div>
<div class="relative px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="url" class="block text-xs font-medium text-gray-900">
URL
</label>
<input
required
type="text"
name="url"
id="url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="https"
/>
</div>
<div class="relative rounded-md rounded-t-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label for="discord_url" class="block text-xs font-medium text-gray-900">
Discord URL
</label>
<input
type="text"
name="discord_url"
id="discord_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="https"
/>
</div>
<label
for="posted_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
Posted At
</label>
<div class="mt-2">
<input type="date" required id="posted_date" name="posted_date" min="2024-01-01"/>
</div>
<label
for="description"
class="block text-sm font-medium leading-6 text-gray-900"
>
Add your description (markdown compatible)
</label>
<div class="mt-2">
<textarea
required
rows="4"
name="description"
id="description"
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
></textarea>
</div>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Add Showcase
</button>
</ActionForm>
<Divider title="Showcases without an issue"/>
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || showcases
.get()
.map(|data| match data {
(Err(e), Err(e2)) => {
EitherOf3::A(view! {
<div>
<div>{e.to_string()}</div>
<div>{e2.to_string()}</div>
</div>
})
}
(_, Err(e)) | (Err(e), _) => {
EitherOf3::B(view! {
<div>
<div>{e.to_string()}</div>
</div>
})
}
(Ok(showcases), Ok(issues)) => {
EitherOf3::C(view! {
<div>
<ul role="list" class="divide-y divide-gray-100">
<For
each=move || showcases.clone()
key=|showcase| showcase.id.clone()
let:showcase
>
<AddShowcaseToIssueForm
showcase=showcase
issue_id=issues.first().map(|issue| issue.id.clone())
/>
</For>
</ul>
</div>
})
}
})}
</Suspense>
</div>
}
}
#[component]
fn AddShowcaseToIssueForm(
showcase: ShowcaseData,
issue_id: Option<String>,
) -> impl IntoView {
let associate_showcase_with_issue: ServerAction<
AssociateShowcaseWithIssue,
> = ServerAction::new();
view! {
<li class="flex items-center justify-between gap-x-6 py-5">
<div class="min-w-0">
<div class="flex items-start gap-x-3">
<p class="text-sm font-semibold leading-6 text-gray-900">{showcase.title}</p>
</div>
<div class="mt-1 flex items-center gap-x-2 text-xs leading-5 text-gray-500">
<p class="whitespace-nowrap">
posted on
<time datetime=showcase
.posted_date
.as_ref()
.unwrap()
.to_string()>{showcase.posted_date.as_ref().unwrap().to_string()}</time>
</p>
<svg viewBox="0 0 2 2" class="h-0.5 w-0.5 fill-current">
<circle cx="1" cy="1" r="1"></circle>
</svg>
// <p class="truncate">Submitted by {showcase.submitted_by}</p>
</div>
</div>
{issue_id
.map(|issue_id| {
view! {
<div class="flex flex-none items-center gap-x-4">
<ActionForm action=associate_showcase_with_issue>
<input type="hidden" value=showcase.id name="showcase_id"/>
<input type="hidden" value=issue_id name="issue_id"/>
<button
type="submit"
class="hidden rounded-md bg-white px-2.5 py-1.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:block"
>
Add to current draft
</button>
</ActionForm>
</div>
}
})}
</li>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlShowcaseData {
id: Vec<u8>,
title: String,
posted_date: Option<time::Date>,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct ShowcaseData {
pub id: String,
pub title: String,
pub posted_date: Option<time::Date>,
}
#[cfg(feature = "ssr")]
impl From<SqlShowcaseData> for ShowcaseData {
fn from(value: SqlShowcaseData) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
ShowcaseData {
id: id_str.to_string(),
title: value.title,
posted_date: value.posted_date,
}
}
}
#[server]
pub async fn fetch_showcases(
) -> Result<Vec<ShowcaseData>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let showcases: Vec<SqlShowcaseData> = sqlx::query_as!(
SqlShowcaseData,
"SELECT
id,
title,
posted_date
FROM showcase
LEFT JOIN issue__showcase
ON showcase.id = issue__showcase.showcase_id
WHERE issue__showcase.issue_id IS NULL
ORDER BY showcase.id"
)
.fetch_all(&pool)
.await?;
Ok(showcases
.into_iter()
.map(ShowcaseData::from)
.collect())
}
#[server]
async fn associate_showcase_with_issue(
showcase_id: String,
issue_id: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issue_id: [u8; 16] = issue_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
let showcase_id: [u8; 16] = showcase_id
.parse::<rusty_ulid::Ulid>()
.expect("a valid ulid to be returned from the form")
.into();
sqlx::query!(
r#"
INSERT INTO issue__showcase ( issue_id, showcase_id )
VALUES ( ?, ? )
"#,
issue_id.as_slice(),
showcase_id.as_slice()
)
.execute(&pool)
.await
.expect("successful insert");
Ok(())
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlIssueShort {
id: Vec<u8>,
display_name: String,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct IssueShort {
pub id: String,
pub display_name: String,
}
#[cfg(feature = "ssr")]
impl From<SqlIssueShort> for IssueShort {
fn from(value: SqlIssueShort) -> Self {
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
IssueShort {
id: id_str.to_string(),
display_name: value.display_name,
}
}
}
#[server]
async fn fetch_issues(
) -> Result<Vec<IssueShort>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let issues: Vec<SqlIssueShort> = sqlx::query_as!(
SqlIssueShort,
r#"SELECT
id,
display_name
FROM issue
WHERE status = "draft"
ORDER BY issue_date DESC"#
)
.fetch_all(&pool)
.await?;
Ok(issues.into_iter().map(IssueShort::from).collect())
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/admin/educational/id.rs | src/app/routes/admin/educational/id.rs | use crate::app::components::Divider;
use leptos::{either::Either, prelude::*};
use leptos_router::hooks::use_params_map;
use serde::{Deserialize, Serialize};
#[cfg(feature = "ssr")]
use crate::app::server_fn::error::NoCustomError;
#[server]
#[allow(unused_variables)]
async fn update_educational(
educational_id: String,
title: String,
url: String,
discord_url: String,
description: String,
posted_date: String,
) -> Result<(), ServerFnError> {
let _pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let _id: [u8; 16] = educational_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid educational id"
.to_string(),
)
})?
.into();
dbg!(title);
// sqlx::query!(
// r#"
// UPDATE showcase
// SET
// id = ?
// title = ?
// url = ?
// discord_url = ?
// posted_date = ?
// description
// VALUES ( ?, ?, ?, ?, ?, ? )
// "#,
// id.as_slice(),
// title,
// url,
// discord_url,
// posted_date,
// description
// )
// .execute(&pool)
// .await
// .expect("successful insert");
Ok(())
}
#[component]
pub fn Educational() -> impl IntoView {
let params = use_params_map();
let update_educational: ServerAction<
UpdateEducational,
> = ServerAction::new();
let educational = Resource::new(
move || {
params.with(|p| p.get("id").unwrap_or_default())
},
fetch_educational_by_id,
);
view! {
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<Suspense fallback=move || {
view! { <p>"Loading Crate Release"</p> }
}>
{move || educational
.get()
.map(|data| match data {
Err(e) => {
Either::Left(view! {
<div>
<div>{e.to_string()}</div>
</div>
})
}
Ok(None) => {
Either::Left(view! {
<div>
<div>{"Unable to find Crate Release".to_string()}</div>
</div>
})
}
Ok(Some(educational)) => {
let educational_id = educational.id.clone();
Either::Right(view! {
<div>
<ActionForm
attr:class="isolate -space-y-px rounded-md shadow-sm"
action=update_educational
>
<div class="relative rounded-md rounded-b-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="title"
class="block text-xs font-medium text-gray-900"
>
Title
</label>
<input
type="hidden"
name="educational_id"
id="educational_id"
value=educational.id
/>
<input
required
type="text"
name="title"
id="title"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=educational.title
/>
</div>
<div class="relative px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="video_url"
class="block text-xs font-medium text-gray-900"
>
Video URL
</label>
<input
required
type="text"
name="video_url"
id="video_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=educational.video_url
/>
</div>
<div class="relative px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="post_url"
class="block text-xs font-medium text-gray-900"
>
Post URL
</label>
<input
required
type="text"
name="post_url"
id="post_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=educational.post_url
/>
</div>
<div class="relative rounded-md rounded-t-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="discord_url"
class="block text-xs font-medium text-gray-900"
>
Discord URL
</label>
<input
type="text"
name="discord_url"
id="discord_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=educational.discord_url
/>
</div>
<label
for="posted_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
Posted At
</label>
<div class="mt-2">
<input
type="date"
required
id="posted_date"
name="posted_date"
min="2024-01-01"
value=educational.posted_date.unwrap().to_string()
/>
</div>
<label
for="description"
class="block text-sm font-medium leading-6 text-gray-900"
>
Add your description (markdown compatible)
</label>
<div class="mt-2">
<textarea
required
rows="4"
name="description"
id="description"
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
>
{educational.description}
</textarea>
</div>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Update Release
</button>
</ActionForm>
<Divider title="Crate Release Images"/>
<ul
role="list"
class="grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-3 sm:gap-x-6 lg:grid-cols-4 xl:gap-x-8"
>
<For
each=move || educational.images.clone()
key=|image| image.id.clone()
let:image
>
<EducationalImageLi
educational_id=educational_id.clone()
id=image.id
url=image.url
/>
</For>
</ul>
</div>
})
}
})}
</Suspense>
<Divider title="All Images"/>
<Images educational_id=params.with(|p| { p.get("id").unwrap_or_default() })/>
</div>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlEducationalData {
id: Vec<u8>,
title: String,
video_url: String,
post_url: String,
posted_date: Option<time::Date>,
discord_url: String,
description: String,
images: serde_json::Value,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct EducationalData {
id: String,
title: String,
video_url: String,
post_url: String,
posted_date: Option<time::Date>,
discord_url: String,
description: String,
images: Vec<ImgDataTransformed>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
struct ImgData {
id: String,
cloudinary_public_id: String,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
struct ImgDataTransformed {
id: String,
url: String,
}
#[cfg(feature = "ssr")]
impl From<SqlEducationalData> for EducationalData {
fn from(value: SqlEducationalData) -> Self {
use data_encoding::BASE64;
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
let images =
serde_json::from_value::<Vec<ImgData>>(
value.images,
)
.inspect_err(|e| {
tracing::warn!(?e);
})
.unwrap_or_default()
.into_iter()
.map(|img_data| {
use cloudinary::transformation::{
resize_mode::ResizeMode::ScaleByWidth,
Image as CImage,
Transformations::Resize,
};
let base_id = BASE64
.decode(img_data.id.as_bytes())
.expect("a valid id in base64 format");
let img_ulid = rusty_ulid::Ulid::try_from(
base_id.as_slice(),
)
.expect(
"expect valid ids from the database",
);
let image = CImage::new(
"dilgcuzda".into(),
img_data.cloudinary_public_id.into(),
)
.add_transformation(Resize(ScaleByWidth {
width: 300,
ar: None,
liquid: None,
}));
ImgDataTransformed {
id: img_ulid.to_string(),
url: image.to_string(),
}
})
.collect();
EducationalData {
id: id_str.to_string(),
title: value.title,
video_url: value.video_url,
post_url: value.post_url,
posted_date: value.posted_date,
discord_url: value.discord_url,
description: value.description,
images,
}
}
}
#[server]
pub async fn fetch_educational_by_id(
educational_id: String,
) -> Result<Option<EducationalData>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let educational_id: [u8; 16] = educational_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid issue id".to_string(),
)
})?
.into();
let educational: Option<SqlEducationalData> = sqlx::query_as!(
SqlEducationalData,
r#"SELECT
id,
title,
video_url,
post_url,
posted_date,
discord_url,
description,
images
from
educational
LEFT JOIN (
SELECT
educational_id,
JSON_ARRAYAGG(
JSON_OBJECT(
"id",
TO_BASE64(image.id),
"cloudinary_public_id",
cloudinary_public_id
)
) AS images
FROM
educational__image
LEFT JOIN image ON educational__image.image_id = image.id
GROUP BY
educational_id
) as i on i.educational_id = educational.id
WHERE educational.id = ?"#,
educational_id.as_slice()
)
.fetch_optional(&pool)
.await?;
Ok(educational.map(EducationalData::from))
}
#[server]
async fn associate_image_with_educational(
image_id: String,
educational_id: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let image_id: [u8; 16] = image_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid image id".to_string(),
)
})?
.into();
let educational_id: [u8; 16] = educational_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid educational id"
.to_string(),
)
})?
.into();
sqlx::query!(
r#"
INSERT INTO educational__image ( image_id, educational_id )
VALUES ( ?, ? )
"#,
image_id.as_slice(),
educational_id.as_slice()
)
.execute(&pool)
.await
.map_err(|e| {
ServerFnError::<NoCustomError>::ServerError(
e.to_string(),
)
})?;
Ok(())
}
#[server]
async fn remove_image_from_educational(
image_id: String,
educational_id: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let image_id: [u8; 16] = image_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid image id".to_string(),
)
})?
.into();
let educational_id: [u8; 16] = educational_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid educational id"
.to_string(),
)
})?
.into();
sqlx::query!(
r#"
DELETE FROM educational__image
WHERE image_id = ?
AND educational_id = ?
"#,
image_id.as_slice(),
educational_id.as_slice()
)
.execute(&pool)
.await
.map_err(|e| {
ServerFnError::<NoCustomError>::ServerError(
e.to_string(),
)
})?;
Ok(())
}
#[component]
fn Images(educational_id: String) -> impl IntoView {
let images =
Resource::new(move || {}, |_| fetch_images());
view! {
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || {
let educational_id = educational_id.clone();
images
.get()
.map(move |data| match (educational_id, data) {
(_, Err(e)) => Either::Left(view! { <div>{e.to_string()}</div> }),
(educational_id, Ok(images)) => {
Either::Right(view! {
<ul
role="list"
class="grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-3 sm:gap-x-6 lg:grid-cols-4 xl:gap-x-8"
>
<For
each=move || images.clone()
key=|image| image.id.clone()
let:image
>
<ImageLi
educational_id=educational_id.clone()
id=image.id
url=image.url
description=image.description
/>
</For>
</ul>
})
}
})
}}
</Suspense>
}
}
#[component]
fn EducationalImageLi(
educational_id: String,
id: String,
url: String,
) -> impl IntoView {
let remove_image_from_educational: ServerAction<
RemoveImageFromEducational,
> = ServerAction::new();
view! {
<li class="relative">
<div class="group aspect-h-7 aspect-w-10 block w-full overflow-hidden rounded-lg bg-gray-100 focus-within:ring-2 focus-within:ring-indigo-500 focus-within:ring-offset-2 focus-within:ring-offset-gray-100">
<img
src=url
alt=""
class="pointer-events-none object-cover group-hover:opacity-75"
/>
<button type="submit" class="absolute inset-0 focus:outline-none">
<span class="sr-only">View details</span>
</button>
</div>
<p class="pointer-events-none mt-2 block truncate text-sm font-medium text-gray-900">
{id.clone()}
</p>
// <p class="pointer-events-none block text-sm font-medium text-gray-500">{description}</p>
<ActionForm action=remove_image_from_educational>
<input type="hidden" name="educational_id" value=educational_id/>
<input type="hidden" name="image_id" value=id/>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Remove from Educational
</button>
</ActionForm>
</li>
}
}
#[component]
fn ImageLi(
educational_id: String,
id: String,
url: String,
description: String,
) -> impl IntoView {
let associate_image_with_educational: ServerAction<
AssociateImageWithEducational,
> = ServerAction::new();
view! {
<li class="relative">
<div class="group aspect-h-7 aspect-w-10 block w-full overflow-hidden rounded-lg bg-gray-100 focus-within:ring-2 focus-within:ring-indigo-500 focus-within:ring-offset-2 focus-within:ring-offset-gray-100">
<img
src=url
alt=""
class="pointer-events-none object-cover group-hover:opacity-75"
/>
<button type="submit" class="absolute inset-0 focus:outline-none">
<span class="sr-only">View details</span>
</button>
</div>
<p class="pointer-events-none mt-2 block truncate text-sm font-medium text-gray-900">
{id.clone()}
</p>
<p class="pointer-events-none block text-sm font-medium text-gray-500">{description}</p>
<ActionForm action=associate_image_with_educational>
<input type="hidden" name="educational_id" value=educational_id/>
<input type="hidden" name="image_id" value=id/>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Add To Educational
</button>
</ActionForm>
</li>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlImage {
id: Vec<u8>,
description: String,
cloudinary_public_id: String,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct Image {
pub id: String,
pub description: String,
pub url: String,
}
#[cfg(feature = "ssr")]
impl From<SqlImage> for Image {
fn from(value: SqlImage) -> Self {
use cloudinary::transformation::{
resize_mode::ResizeMode::ScaleByWidth,
Image as CImage, Transformations::Resize,
};
let image = CImage::new(
"dilgcuzda".into(),
value.cloudinary_public_id.into(),
)
.add_transformation(Resize(ScaleByWidth {
width: 300,
ar: None,
liquid: None,
}));
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
Image {
id: id_str.to_string(),
description: value.description,
url: image.to_string(),
}
}
}
#[server]
async fn fetch_images() -> Result<Vec<Image>, ServerFnError>
{
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let images: Vec<SqlImage> = sqlx::query_as!(
SqlImage,
r#"SELECT
id,
cloudinary_public_id,
description
FROM image
ORDER BY created_at DESC
limit 5"#
)
.fetch_all(&pool)
.await
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"sql failed".to_string(),
)
})?;
Ok(images.into_iter().map(Image::from).collect())
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/admin/devlog/id.rs | src/app/routes/admin/devlog/id.rs | use crate::app::components::Divider;
use leptos::{either::Either, prelude::*};
use leptos_router::hooks::use_params_map;
use serde::{Deserialize, Serialize};
#[cfg(feature = "ssr")]
use crate::app::server_fn::error::NoCustomError;
#[server]
#[allow(unused_variables)]
async fn update_devlog(
devlog_id: String,
title: String,
url: String,
discord_url: String,
description: String,
posted_date: String,
) -> Result<(), ServerFnError> {
let _pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let _id: [u8; 16] = devlog_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid devlog id".to_string(),
)
})?
.into();
dbg!(title);
// sqlx::query!(
// r#"
// UPDATE showcase
// SET
// id = ?
// title = ?
// url = ?
// discord_url = ?
// posted_date = ?
// description
// VALUES ( ?, ?, ?, ?, ?, ? )
// "#,
// id.as_slice(),
// title,
// url,
// discord_url,
// posted_date,
// description
// )
// .execute(&pool)
// .await
// .expect("successful insert");
Ok(())
}
#[component]
pub fn Devlog() -> impl IntoView {
let params = use_params_map();
let update_devlog: ServerAction<UpdateDevlog> =
ServerAction::new();
let devlog = Resource::new(
move || {
params.with(|p| p.get("id").unwrap_or_default())
},
fetch_devlog_by_id,
);
view! {
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<Suspense fallback=move || {
view! { <p>"Loading Crate Release"</p> }
}>
{move || devlog
.get()
.map(|data| match data {
Err(e) => {
Either::Left(view! {
<div>
<div>{e.to_string()}</div>
</div>
})
}
Ok(None) => {
Either::Left(view! {
<div>
<div>{"Unable to find Crate Release".to_string()}</div>
</div>
})
}
Ok(Some(devlog)) => {
let devlog_id = devlog.id.clone();
Either::Right(view! {
<div>
<ActionForm
attr:class="isolate -space-y-px rounded-md shadow-sm"
action=update_devlog
>
<div class="relative rounded-md rounded-b-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="title"
class="block text-xs font-medium text-gray-900"
>
Title
</label>
<input
type="hidden"
name="devlog_id"
id="devlog_id"
value=devlog.id
/>
<input
required
type="text"
name="title"
id="title"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=devlog.title
/>
</div>
<div class="relative px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="video_url"
class="block text-xs font-medium text-gray-900"
>
Video URL
</label>
<input
required
type="text"
name="video_url"
id="video_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=devlog.video_url
/>
</div>
<div class="relative px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="post_url"
class="block text-xs font-medium text-gray-900"
>
Post URL
</label>
<input
required
type="text"
name="post_url"
id="post_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=devlog.post_url
/>
</div>
<div class="relative rounded-md rounded-t-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="discord_url"
class="block text-xs font-medium text-gray-900"
>
Discord URL
</label>
<input
type="text"
name="discord_url"
id="discord_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=devlog.discord_url
/>
</div>
<label
for="posted_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
Posted At
</label>
<div class="mt-2">
<input
type="date"
required
id="posted_date"
name="posted_date"
min="2024-01-01"
value=devlog.posted_date.unwrap().to_string()
/>
</div>
<label
for="description"
class="block text-sm font-medium leading-6 text-gray-900"
>
Add your description (markdown compatible)
</label>
<div class="mt-2">
<textarea
rows="4"
name="description"
id="description"
required
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
>
{devlog.description}
</textarea>
</div>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Update Release
</button>
</ActionForm>
<Divider title="Crate Release Images"/>
<ul
role="list"
class="grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-3 sm:gap-x-6 lg:grid-cols-4 xl:gap-x-8"
>
<For
each=move || devlog.images.clone()
key=|image| image.id.clone()
let:image
>
<DevlogImageLi
devlog_id=devlog_id.clone()
id=image.id
url=image.url
/>
</For>
</ul>
</div>
})
}
})}
</Suspense>
<Divider title="All Images"/>
<Images devlog_id=params.with(|p| { p.get("id").unwrap_or_default() })/>
</div>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlDevlogData {
id: Vec<u8>,
title: String,
video_url: String,
post_url: String,
posted_date: Option<time::Date>,
discord_url: String,
description: String,
images: serde_json::Value,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct DevlogData {
id: String,
title: String,
video_url: String,
post_url: String,
posted_date: Option<time::Date>,
discord_url: String,
description: String,
images: Vec<ImgDataTransformed>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
struct ImgData {
id: String,
cloudinary_public_id: String,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
struct ImgDataTransformed {
id: String,
url: String,
}
#[cfg(feature = "ssr")]
impl From<SqlDevlogData> for DevlogData {
fn from(value: SqlDevlogData) -> Self {
use data_encoding::BASE64;
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
let images =
serde_json::from_value::<Vec<ImgData>>(
value.images,
)
.inspect_err(|e| {
tracing::warn!(?e);
})
.unwrap_or_default()
.into_iter()
.map(|img_data| {
use cloudinary::transformation::{
resize_mode::ResizeMode::ScaleByWidth,
Image as CImage,
Transformations::Resize,
};
let base_id = BASE64
.decode(img_data.id.as_bytes())
.expect("a valid id in base64 format");
let img_ulid = rusty_ulid::Ulid::try_from(
base_id.as_slice(),
)
.expect(
"expect valid ids from the database",
);
let image = CImage::new(
"dilgcuzda".into(),
img_data.cloudinary_public_id.into(),
)
.add_transformation(Resize(ScaleByWidth {
width: 300,
ar: None,
liquid: None,
}));
ImgDataTransformed {
id: img_ulid.to_string(),
url: image.to_string(),
}
})
.collect();
DevlogData {
id: id_str.to_string(),
title: value.title,
video_url: value.video_url,
post_url: value.post_url,
posted_date: value.posted_date,
discord_url: value.discord_url,
description: value.description,
images,
}
}
}
#[server]
pub async fn fetch_devlog_by_id(
devlog_id: String,
) -> Result<Option<DevlogData>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let devlog_id: [u8; 16] = devlog_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid issue id".to_string(),
)
})?
.into();
let devlog: Option<SqlDevlogData> = sqlx::query_as!(
SqlDevlogData,
r#"SELECT
id,
title,
video_url,
post_url,
posted_date,
discord_url,
description,
images
from
devlog
LEFT JOIN (
SELECT
devlog_id,
JSON_ARRAYAGG(
JSON_OBJECT(
"id",
TO_BASE64(image.id),
"cloudinary_public_id",
cloudinary_public_id
)
) AS images
FROM
devlog__image
LEFT JOIN image ON devlog__image.image_id = image.id
GROUP BY
devlog_id
) as i on i.devlog_id = devlog.id
WHERE devlog.id = ?"#,
devlog_id.as_slice()
)
.fetch_optional(&pool)
.await?;
Ok(devlog.map(DevlogData::from))
}
#[server]
async fn associate_image_with_devlog(
image_id: String,
devlog_id: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let image_id: [u8; 16] = image_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid image id".to_string(),
)
})?
.into();
let devlog_id: [u8; 16] = devlog_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid devlog id".to_string(),
)
})?
.into();
sqlx::query!(
r#"
INSERT INTO devlog__image ( image_id, devlog_id )
VALUES ( ?, ? )
"#,
image_id.as_slice(),
devlog_id.as_slice()
)
.execute(&pool)
.await
.map_err(|e| {
ServerFnError::<NoCustomError>::ServerError(
e.to_string(),
)
})?;
Ok(())
}
#[server]
async fn remove_image_from_devlog(
image_id: String,
devlog_id: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let image_id: [u8; 16] = image_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid image id".to_string(),
)
})?
.into();
let devlog_id: [u8; 16] = devlog_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid devlog id".to_string(),
)
})?
.into();
sqlx::query!(
r#"
DELETE FROM devlog__image
WHERE image_id = ?
AND devlog_id = ?
"#,
image_id.as_slice(),
devlog_id.as_slice()
)
.execute(&pool)
.await
.map_err(|e| {
ServerFnError::<NoCustomError>::ServerError(
e.to_string(),
)
})?;
Ok(())
}
#[component]
fn Images(devlog_id: String) -> impl IntoView {
let images =
Resource::new(move || {}, |_| fetch_images());
view! {
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || {
let devlog_id = devlog_id.clone();
images
.get()
.map(move |data| match (devlog_id, data) {
(_, Err(e)) => Either::Left(view! { <div>{e.to_string()}</div> }),
(devlog_id, Ok(images)) => {
Either::Right(view! {
<ul
role="list"
class="grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-3 sm:gap-x-6 lg:grid-cols-4 xl:gap-x-8"
>
<For
each=move || images.clone()
key=|image| image.id.clone()
let:image
>
<ImageLi
devlog_id=devlog_id.clone()
id=image.id
url=image.url
description=image.description
/>
</For>
</ul>
})
}
})
}}
</Suspense>
}
}
#[component]
fn DevlogImageLi(
devlog_id: String,
id: String,
url: String,
) -> impl IntoView {
let remove_image_from_devlog: ServerAction<
RemoveImageFromDevlog,
> = ServerAction::new();
view! {
<li class="relative">
<div class="group aspect-h-7 aspect-w-10 block w-full overflow-hidden rounded-lg bg-gray-100 focus-within:ring-2 focus-within:ring-indigo-500 focus-within:ring-offset-2 focus-within:ring-offset-gray-100">
<img
src=url
alt=""
class="pointer-events-none object-cover group-hover:opacity-75"
/>
<button type="submit" class="absolute inset-0 focus:outline-none">
<span class="sr-only">View details</span>
</button>
</div>
<p class="pointer-events-none mt-2 block truncate text-sm font-medium text-gray-900">
{id.clone()}
</p>
// <p class="pointer-events-none block text-sm font-medium text-gray-500">{description}</p>
<ActionForm action=remove_image_from_devlog>
<input type="hidden" name="devlog_id" value=devlog_id/>
<input type="hidden" name="image_id" value=id/>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Remove from Devlog
</button>
</ActionForm>
</li>
}
}
#[component]
fn ImageLi(
devlog_id: String,
id: String,
url: String,
description: String,
) -> impl IntoView {
let associate_image_with_devlog: ServerAction<
AssociateImageWithDevlog,
> = ServerAction::new();
view! {
<li class="relative">
<div class="group aspect-h-7 aspect-w-10 block w-full overflow-hidden rounded-lg bg-gray-100 focus-within:ring-2 focus-within:ring-indigo-500 focus-within:ring-offset-2 focus-within:ring-offset-gray-100">
<img
src=url
alt=""
class="pointer-events-none object-cover group-hover:opacity-75"
/>
<button type="submit" class="absolute inset-0 focus:outline-none">
<span class="sr-only">View details</span>
</button>
</div>
<p class="pointer-events-none mt-2 block truncate text-sm font-medium text-gray-900">
{id.clone()}
</p>
<p class="pointer-events-none block text-sm font-medium text-gray-500">{description}</p>
<ActionForm action=associate_image_with_devlog>
<input type="hidden" name="devlog_id" value=devlog_id/>
<input type="hidden" name="image_id" value=id/>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Add To Devlog
</button>
</ActionForm>
</li>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlImage {
id: Vec<u8>,
description: String,
cloudinary_public_id: String,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct Image {
pub id: String,
pub description: String,
pub url: String,
}
#[cfg(feature = "ssr")]
impl From<SqlImage> for Image {
fn from(value: SqlImage) -> Self {
use cloudinary::transformation::{
resize_mode::ResizeMode::ScaleByWidth,
Image as CImage, Transformations::Resize,
};
let image = CImage::new(
"dilgcuzda".into(),
value.cloudinary_public_id.into(),
)
.add_transformation(Resize(ScaleByWidth {
width: 300,
ar: None,
liquid: None,
}));
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
Image {
id: id_str.to_string(),
description: value.description,
url: image.to_string(),
}
}
}
#[server]
async fn fetch_images() -> Result<Vec<Image>, ServerFnError>
{
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let images: Vec<SqlImage> = sqlx::query_as!(
SqlImage,
r#"SELECT
id,
cloudinary_public_id,
description
FROM image
ORDER BY created_at DESC
limit 5"#
)
.fetch_all(&pool)
.await
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"sql failed".to_string(),
)
})?;
Ok(images.into_iter().map(Image::from).collect())
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/admin/crate_release/id.rs | src/app/routes/admin/crate_release/id.rs | use crate::app::components::Divider;
use leptos::{either::Either, prelude::*};
use leptos_router::hooks::use_params_map;
use serde::{Deserialize, Serialize};
#[cfg(feature = "ssr")]
use crate::app::server_fn::error::NoCustomError;
#[server]
#[allow(unused_variables)]
async fn update_crate_release(
crate_release_id: String,
title: String,
url: String,
discord_url: String,
description: String,
posted_date: String,
) -> Result<(), ServerFnError> {
let _pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let _id: [u8; 16] = crate_release_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid crate_release id"
.to_string(),
)
})?
.into();
dbg!(title);
// sqlx::query!(
// r#"
// UPDATE showcase
// SET
// id = ?
// title = ?
// url = ?
// discord_url = ?
// posted_date = ?
// description
// VALUES ( ?, ?, ?, ?, ?, ? )
// "#,
// id.as_slice(),
// title,
// url,
// discord_url,
// posted_date,
// description
// )
// .execute(&pool)
// .await
// .expect("successful insert");
Ok(())
}
#[component]
pub fn CrateRelease() -> impl IntoView {
let params = use_params_map();
let update_crate_release: ServerAction<
UpdateCrateRelease,
> = ServerAction::new();
let crate_release = Resource::new(
move || {
params.with(|p| p.get("id").unwrap_or_default())
},
fetch_crate_release_by_id,
);
view! {
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<Suspense fallback=move || {
view! { <p>"Loading Crate Release"</p> }
}>
{move || crate_release
.get()
.map(|data| match data {
Err(e) => {
Either::Left(view! {
<div>
<div>{e.to_string()}</div>
</div>
})
}
Ok(None) => {
Either::Left(view! {
<div>
<div>{"Unable to find Crate Release".to_string()}</div>
</div>
})
}
Ok(Some(crate_release)) => {
let crate_release_id = crate_release.id.clone();
Either::Right(view! {
<div>
<ActionForm
attr:class="isolate -space-y-px rounded-md shadow-sm"
action=update_crate_release
>
<div class="relative rounded-md rounded-b-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="title"
class="block text-xs font-medium text-gray-900"
>
Title
</label>
<input
type="hidden"
name="crate_release_id"
id="crate_release_id"
value=crate_release.id
/>
<input
required
type="text"
name="title"
id="title"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=crate_release.title
/>
</div>
<div class="relative px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="url"
class="block text-xs font-medium text-gray-900"
>
URL
</label>
<input
required
type="text"
name="url"
id="url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=crate_release.url
/>
</div>
<div class="relative rounded-md rounded-t-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="discord_url"
class="block text-xs font-medium text-gray-900"
>
Discord URL
</label>
<input
type="text"
name="discord_url"
id="discord_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=crate_release.discord_url
/>
</div>
<label
for="posted_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
Posted At
</label>
<div class="mt-2">
<input
required
type="date"
id="posted_date"
name="posted_date"
min="2024-01-01"
value=crate_release.posted_date.unwrap().to_string()
/>
</div>
<label
for="description"
class="block text-sm font-medium leading-6 text-gray-900"
>
Add your description (markdown compatible)
</label>
<div class="mt-2">
<textarea
rows="4"
name="description"
id="description"
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
required
>
{crate_release.description}
</textarea>
</div>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Update Release
</button>
</ActionForm>
<Divider title="Crate Release Images"/>
<ul
role="list"
class="grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-3 sm:gap-x-6 lg:grid-cols-4 xl:gap-x-8"
>
<For
each=move || crate_release.images.clone()
key=|image| image.id.clone()
let:image
>
<CrateReleaseImageLi
crate_release_id=crate_release_id.clone()
id=image.id
url=image.url
/>
</For>
</ul>
</div>
})
}
})}
</Suspense>
<Divider title="All Images"/>
<Images crate_release_id=params.with(|p| { p.get("id").unwrap_or_default() })/>
</div>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlCrateReleaseData {
id: Vec<u8>,
title: String,
url: String,
posted_date: Option<time::Date>,
discord_url: String,
description: String,
images: serde_json::Value,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct CrateReleaseData {
id: String,
title: String,
url: String,
posted_date: Option<time::Date>,
discord_url: String,
description: String,
images: Vec<ImgDataTransformed>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
struct ImgData {
id: String,
cloudinary_public_id: String,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
struct ImgDataTransformed {
id: String,
url: String,
}
#[cfg(feature = "ssr")]
impl From<SqlCrateReleaseData> for CrateReleaseData {
fn from(value: SqlCrateReleaseData) -> Self {
use data_encoding::BASE64;
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
let images =
serde_json::from_value::<Vec<ImgData>>(
value.images,
)
.inspect_err(|e| {
tracing::warn!(?e);
})
.unwrap_or_default()
.into_iter()
.map(|img_data| {
use cloudinary::transformation::{
resize_mode::ResizeMode::ScaleByWidth,
Image as CImage,
Transformations::Resize,
};
let base_id = BASE64
.decode(img_data.id.as_bytes())
.expect("a valid id in base64 format");
let img_ulid = rusty_ulid::Ulid::try_from(
base_id.as_slice(),
)
.expect(
"expect valid ids from the database",
);
let image = CImage::new(
"dilgcuzda".into(),
img_data.cloudinary_public_id.into(),
)
.add_transformation(Resize(ScaleByWidth {
width: 300,
ar: None,
liquid: None,
}));
ImgDataTransformed {
id: img_ulid.to_string(),
url: image.to_string(),
}
})
.collect();
CrateReleaseData {
id: id_str.to_string(),
title: value.title,
url: value.url,
posted_date: value.posted_date,
discord_url: value.discord_url,
description: value.description,
images,
}
}
}
#[server]
pub async fn fetch_crate_release_by_id(
crate_release_id: String,
) -> Result<Option<CrateReleaseData>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let crate_release_id: [u8; 16] = crate_release_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid issue id".to_string(),
)
})?
.into();
let crate_release: Option<SqlCrateReleaseData> = sqlx::query_as!(
SqlCrateReleaseData,
r#"SELECT
id,
title,
url,
posted_date,
discord_url,
description,
images
from
crate_release
LEFT JOIN (
SELECT
crate_release_id,
JSON_ARRAYAGG(
JSON_OBJECT(
"id",
TO_BASE64(image.id),
"cloudinary_public_id",
cloudinary_public_id
)
) AS images
FROM
crate_release__image
LEFT JOIN image ON crate_release__image.image_id = image.id
GROUP BY
crate_release_id
) as i on i.crate_release_id = crate_release.id
WHERE crate_release.id = ?"#,
crate_release_id.as_slice()
)
.fetch_optional(&pool)
.await?;
Ok(crate_release.map(CrateReleaseData::from))
}
#[server]
async fn associate_image_with_crate_release(
image_id: String,
crate_release_id: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let image_id: [u8; 16] = image_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid image id".to_string(),
)
})?
.into();
let crate_release_id: [u8; 16] = crate_release_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid crate_release id"
.to_string(),
)
})?
.into();
sqlx::query!(
r#"
INSERT INTO crate_release__image ( image_id, crate_release_id )
VALUES ( ?, ? )
"#,
image_id.as_slice(),
crate_release_id.as_slice()
)
.execute(&pool)
.await
.map_err(|e| {
ServerFnError::<NoCustomError>::ServerError(
e.to_string(),
)
})?;
Ok(())
}
#[server]
async fn remove_image_from_crate_release(
image_id: String,
crate_release_id: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let image_id: [u8; 16] = image_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid image id".to_string(),
)
})?
.into();
let crate_release_id: [u8; 16] = crate_release_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid crate_release id"
.to_string(),
)
})?
.into();
sqlx::query!(
r#"
DELETE FROM crate_release__image
WHERE image_id = ?
AND crate_release_id = ?
"#,
image_id.as_slice(),
crate_release_id.as_slice()
)
.execute(&pool)
.await
.map_err(|e| {
ServerFnError::<NoCustomError>::ServerError(
e.to_string(),
)
})?;
Ok(())
}
#[component]
fn Images(crate_release_id: String) -> impl IntoView {
let images =
Resource::new(move || {}, |_| fetch_images());
view! {
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || {
let crate_release_id = crate_release_id.clone();
images
.get()
.map(move |data| match (crate_release_id, data) {
(_, Err(e)) => Either::Left(view! { <div>{e.to_string()}</div> }),
(crate_release_id, Ok(images)) => {
Either::Right(view! {
<ul
role="list"
class="grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-3 sm:gap-x-6 lg:grid-cols-4 xl:gap-x-8"
>
<For
each=move || images.clone()
key=|image| image.id.clone()
let:image
>
<ImageLi
crate_release_id=crate_release_id.clone()
id=image.id
url=image.url
description=image.description
/>
</For>
</ul>
})
}
})
}}
</Suspense>
}
}
#[component]
fn CrateReleaseImageLi(
crate_release_id: String,
id: String,
url: String,
) -> impl IntoView {
let remove_image_from_crate_release: ServerAction<
RemoveImageFromCrateRelease,
> = ServerAction::new();
view! {
<li class="relative">
<div class="group aspect-h-7 aspect-w-10 block w-full overflow-hidden rounded-lg bg-gray-100 focus-within:ring-2 focus-within:ring-indigo-500 focus-within:ring-offset-2 focus-within:ring-offset-gray-100">
<img
src=url
alt=""
class="pointer-events-none object-cover group-hover:opacity-75"
/>
<button type="submit" class="absolute inset-0 focus:outline-none">
<span class="sr-only">View details</span>
</button>
</div>
<p class="pointer-events-none mt-2 block truncate text-sm font-medium text-gray-900">
{id.clone()}
</p>
// <p class="pointer-events-none block text-sm font-medium text-gray-500">{description}</p>
<ActionForm action=remove_image_from_crate_release>
<input type="hidden" name="crate_release_id" value=crate_release_id/>
<input type="hidden" name="image_id" value=id/>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Remove from CrateRelease
</button>
</ActionForm>
</li>
}
}
#[component]
fn ImageLi(
crate_release_id: String,
id: String,
url: String,
description: String,
) -> impl IntoView {
let associate_image_with_crate_release: ServerAction<
AssociateImageWithCrateRelease,
> = ServerAction::new();
view! {
<li class="relative">
<div class="group aspect-h-7 aspect-w-10 block w-full overflow-hidden rounded-lg bg-gray-100 focus-within:ring-2 focus-within:ring-indigo-500 focus-within:ring-offset-2 focus-within:ring-offset-gray-100">
<img
src=url
alt=""
class="pointer-events-none object-cover group-hover:opacity-75"
/>
<button type="submit" class="absolute inset-0 focus:outline-none">
<span class="sr-only">View details</span>
</button>
</div>
<p class="pointer-events-none mt-2 block truncate text-sm font-medium text-gray-900">
{id.clone()}
</p>
<p class="pointer-events-none block text-sm font-medium text-gray-500">{description}</p>
<ActionForm action=associate_image_with_crate_release>
<input type="hidden" name="crate_release_id" value=crate_release_id/>
<input type="hidden" name="image_id" value=id/>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Add To CrateRelease
</button>
</ActionForm>
</li>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlImage {
id: Vec<u8>,
description: String,
cloudinary_public_id: String,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct Image {
pub id: String,
pub description: String,
pub url: String,
}
#[cfg(feature = "ssr")]
impl From<SqlImage> for Image {
fn from(value: SqlImage) -> Self {
use cloudinary::transformation::{
resize_mode::ResizeMode::ScaleByWidth,
Image as CImage, Transformations::Resize,
};
let image = CImage::new(
"dilgcuzda".into(),
value.cloudinary_public_id.into(),
)
.add_transformation(Resize(ScaleByWidth {
width: 300,
ar: None,
liquid: None,
}));
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
Image {
id: id_str.to_string(),
description: value.description,
url: image.to_string(),
}
}
}
#[server]
async fn fetch_images() -> Result<Vec<Image>, ServerFnError>
{
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let images: Vec<SqlImage> = sqlx::query_as!(
SqlImage,
r#"SELECT
id,
cloudinary_public_id,
description
FROM image
ORDER BY created_at DESC
limit 5"#
)
.fetch_all(&pool)
.await
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"sql failed".to_string(),
)
})?;
Ok(images.into_iter().map(Image::from).collect())
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/admin/showcase/id.rs | src/app/routes/admin/showcase/id.rs | use crate::app::components::Divider;
use leptos::{either::Either, prelude::*};
use leptos_router::hooks::use_params_map;
use serde::{Deserialize, Serialize};
#[cfg(feature = "ssr")]
use crate::app::server_fn::error::NoCustomError;
#[server]
#[allow(unused_variables)]
async fn update_showcase(
showcase_id: String,
title: String,
url: String,
discord_url: String,
description: String,
posted_date: String,
) -> Result<(), ServerFnError> {
let _pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let _id: [u8; 16] = showcase_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid showcase id".to_string(),
)
})?
.into();
dbg!(title);
// sqlx::query!(
// r#"
// UPDATE showcase
// SET
// id = ?
// title = ?
// url = ?
// discord_url = ?
// posted_date = ?
// description
// VALUES ( ?, ?, ?, ?, ?, ? )
// "#,
// id.as_slice(),
// title,
// url,
// discord_url,
// posted_date,
// description
// )
// .execute(&pool)
// .await
// .expect("successful insert");
Ok(())
}
#[component]
pub fn Showcase() -> impl IntoView {
let params = use_params_map();
let update_showcase: ServerAction<UpdateShowcase> =
ServerAction::new();
let showcase = Resource::new(
move || {
params.with(|p| p.get("id").unwrap_or_default())
},
fetch_showcase_by_id,
);
view! {
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<Suspense fallback=move || {
view! { <p>"Loading Showcase"</p> }
}>
{move || showcase
.get()
.map(|data| match data {
Err(e) => {
Either::Left(view! {
<div>
<div>{e.to_string()}</div>
</div>
})
}
Ok(None) => {
Either::Left(view! {
<div>
<div>{"Unable to find Showcase".to_string()}</div>
</div>
})
}
Ok(Some(showcase)) => {
let showcase_id = showcase.id.clone();
Either::Right(view! {
<div>
<ActionForm
attr:class="isolate -space-y-px rounded-md shadow-sm"
action=update_showcase
>
<div class="relative rounded-md rounded-b-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="title"
class="block text-xs font-medium text-gray-900"
>
Title
</label>
<input
type="hidden"
name="showcase_id"
id="showcase_id"
value=showcase.id
/>
<input
required
type="text"
name="title"
id="title"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=showcase.title
/>
</div>
<div class="relative px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="url"
class="block text-xs font-medium text-gray-900"
>
URL
</label>
<input
required
type="text"
name="url"
id="url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=showcase.url
/>
</div>
<div class="relative rounded-md rounded-t-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-indigo-600">
<label
for="discord_url"
class="block text-xs font-medium text-gray-900"
>
Discord URL
</label>
<input
type="text"
name="discord_url"
id="discord_url"
class="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
value=showcase.discord_url
/>
</div>
<label
for="posted_date"
class="block text-sm font-medium leading-6 text-gray-900"
>
Posted At
</label>
<div class="mt-2">
<input
required
type="date"
id="posted_date"
name="posted_date"
min="2024-01-01"
value=showcase.posted_date.unwrap().to_string()
/>
</div>
<label
for="description"
class="block text-sm font-medium leading-6 text-gray-900"
>
Add your description (markdown compatible)
</label>
<div class="mt-2">
<textarea
required
rows="4"
name="description"
id="description"
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
>
{showcase.description}
</textarea>
</div>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Update Showcase
</button>
</ActionForm>
<Divider title="Showcase Images"/>
<ul
role="list"
class="grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-3 sm:gap-x-6 lg:grid-cols-4 xl:gap-x-8"
>
<For
each=move || showcase.images.clone()
key=|image| image.id.clone()
let:image
>
<ShowcaseImageLi
showcase_id=showcase_id.clone()
id=image.id
url=image.url
/>
</For>
</ul>
</div>
})
}
})}
</Suspense>
<Divider title="All Images"/>
<Images showcase_id=params.with(|p| { p.get("id").unwrap_or_default() })/>
</div>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlShowcaseData {
id: Vec<u8>,
title: String,
url: String,
posted_date: Option<time::Date>,
discord_url: String,
description: String,
images: serde_json::Value,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct ShowcaseData {
id: String,
title: String,
url: String,
posted_date: Option<time::Date>,
discord_url: String,
description: String,
images: Vec<ImgDataTransformed>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
struct ImgData {
id: String,
cloudinary_public_id: String,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
struct ImgDataTransformed {
id: String,
url: String,
}
#[cfg(feature = "ssr")]
impl From<SqlShowcaseData> for ShowcaseData {
fn from(value: SqlShowcaseData) -> Self {
use data_encoding::BASE64;
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
let images =
serde_json::from_value::<Vec<ImgData>>(
value.images,
)
.inspect_err(|e| {
tracing::warn!(?e);
})
.unwrap_or_default()
.into_iter()
.map(|img_data| {
use cloudinary::transformation::{
resize_mode::ResizeMode::ScaleByWidth,
Image as CImage,
Transformations::Resize,
};
let base_id = BASE64
.decode(img_data.id.as_bytes())
.expect("a valid id in base64 format");
let img_ulid = rusty_ulid::Ulid::try_from(
base_id.as_slice(),
)
.expect(
"expect valid ids from the database",
);
let image = CImage::new(
"dilgcuzda".into(),
img_data.cloudinary_public_id.into(),
)
.add_transformation(Resize(ScaleByWidth {
width: 300,
ar: None,
liquid: None,
}));
ImgDataTransformed {
id: img_ulid.to_string(),
url: image.to_string(),
}
})
.collect();
ShowcaseData {
id: id_str.to_string(),
title: value.title,
url: value.url,
posted_date: value.posted_date,
discord_url: value.discord_url,
description: value.description,
images,
}
}
}
#[server]
pub async fn fetch_showcase_by_id(
showcase_id: String,
) -> Result<Option<ShowcaseData>, ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let showcase_id: [u8; 16] = showcase_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid issue id".to_string(),
)
})?
.into();
let showcase: Option<SqlShowcaseData> = sqlx::query_as!(
SqlShowcaseData,
r#"SELECT
id,
title,
url,
posted_date,
discord_url,
description,
images
from
showcase
LEFT JOIN (
SELECT
showcase_id,
JSON_ARRAYAGG(
JSON_OBJECT(
"id",
TO_BASE64(image.id),
"cloudinary_public_id",
cloudinary_public_id
)
) AS images
FROM
showcase__image
LEFT JOIN image ON showcase__image.image_id = image.id
GROUP BY
showcase_id
) as i on i.showcase_id = showcase.id
WHERE showcase.id = ?"#,
showcase_id.as_slice()
)
.fetch_optional(&pool)
.await?;
Ok(showcase.map(ShowcaseData::from))
}
#[server]
async fn associate_image_with_showcase(
image_id: String,
showcase_id: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let image_id: [u8; 16] = image_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid image id".to_string(),
)
})?
.into();
let showcase_id: [u8; 16] = showcase_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid showcase id".to_string(),
)
})?
.into();
sqlx::query!(
r#"
INSERT INTO showcase__image ( image_id, showcase_id )
VALUES ( ?, ? )
"#,
image_id.as_slice(),
showcase_id.as_slice()
)
.execute(&pool)
.await
.map_err(|e| {
ServerFnError::<NoCustomError>::ServerError(
e.to_string(),
)
})?;
Ok(())
}
#[server]
async fn remove_image_from_showcase(
image_id: String,
showcase_id: String,
) -> Result<(), ServerFnError> {
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let image_id: [u8; 16] = image_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid image id".to_string(),
)
})?
.into();
let showcase_id: [u8; 16] = showcase_id
.parse::<rusty_ulid::Ulid>()
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"expected a valid showcase id".to_string(),
)
})?
.into();
sqlx::query!(
r#"
DELETE FROM showcase__image
WHERE image_id = ?
AND showcase_id = ?
"#,
image_id.as_slice(),
showcase_id.as_slice()
)
.execute(&pool)
.await
.map_err(|e| {
ServerFnError::<NoCustomError>::ServerError(
e.to_string(),
)
})?;
Ok(())
}
#[component]
fn Images(showcase_id: String) -> impl IntoView {
let images =
Resource::new(move || {}, |_| fetch_images());
view! {
<Suspense fallback=move || {
view! { <p>"Loading (Suspense Fallback)..."</p> }
}>
{move || {
let showcase_id = showcase_id.clone();
images
.get()
.map(move |data| match (showcase_id, data) {
(_, Err(e)) => Either::Left(view! { <div>{e.to_string()}</div> }),
(showcase_id, Ok(images)) => {
Either::Right(view! {
<ul
role="list"
class="grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-3 sm:gap-x-6 lg:grid-cols-4 xl:gap-x-8"
>
<For
each=move || images.clone()
key=|image| image.id.clone()
let:image
>
<ImageLi
showcase_id=showcase_id.clone()
id=image.id
url=image.url
description=image.description
/>
</For>
</ul>
})
}
})
}
}
</Suspense>
}
}
#[component]
fn ShowcaseImageLi(
showcase_id: String,
id: String,
url: String,
) -> impl IntoView {
let remove_image_from_showcase: ServerAction<
RemoveImageFromShowcase,
> = ServerAction::new();
view! {
<li class="relative">
<div class="group aspect-h-7 aspect-w-10 block w-full overflow-hidden rounded-lg bg-gray-100 focus-within:ring-2 focus-within:ring-indigo-500 focus-within:ring-offset-2 focus-within:ring-offset-gray-100">
<img
src=url
alt=""
class="pointer-events-none object-cover group-hover:opacity-75"
/>
<button type="submit" class="absolute inset-0 focus:outline-none">
<span class="sr-only">View details</span>
</button>
</div>
<p class="pointer-events-none mt-2 block truncate text-sm font-medium text-gray-900">
{id.clone()}
</p>
// <p class="pointer-events-none block text-sm font-medium text-gray-500">{description}</p>
<ActionForm action=remove_image_from_showcase>
<input type="hidden" name="showcase_id" value=showcase_id/>
<input type="hidden" name="image_id" value=id/>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Remove from Showcase
</button>
</ActionForm>
</li>
}
}
#[component]
fn ImageLi(
showcase_id: String,
id: String,
url: String,
description: String,
) -> impl IntoView {
let associate_image_with_showcase: ServerAction<
AssociateImageWithShowcase,
> = ServerAction::new();
view! {
<li class="relative">
<div class="group aspect-h-7 aspect-w-10 block w-full overflow-hidden rounded-lg bg-gray-100 focus-within:ring-2 focus-within:ring-indigo-500 focus-within:ring-offset-2 focus-within:ring-offset-gray-100">
<img
src=url
alt=""
class="pointer-events-none object-cover group-hover:opacity-75"
/>
<button type="submit" class="absolute inset-0 focus:outline-none">
<span class="sr-only">View details</span>
</button>
</div>
<p class="pointer-events-none mt-2 block truncate text-sm font-medium text-gray-900">
{id.clone()}
</p>
<p class="pointer-events-none block text-sm font-medium text-gray-500">{description}</p>
<ActionForm action=associate_image_with_showcase>
<input type="hidden" name="showcase_id" value=showcase_id/>
<input type="hidden" name="image_id" value=id/>
<button
type="submit"
class="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Add To Showcase
</button>
</ActionForm>
</li>
}
}
#[cfg(feature = "ssr")]
#[derive(Debug, sqlx::FromRow)]
struct SqlImage {
id: Vec<u8>,
description: String,
cloudinary_public_id: String,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct Image {
pub id: String,
pub description: String,
pub url: String,
}
#[cfg(feature = "ssr")]
impl From<SqlImage> for Image {
fn from(value: SqlImage) -> Self {
use cloudinary::transformation::{
resize_mode::ResizeMode::ScaleByWidth,
Image as CImage, Transformations::Resize,
};
let image = CImage::new(
"dilgcuzda".into(),
value.cloudinary_public_id.into(),
)
.add_transformation(Resize(ScaleByWidth {
width: 300,
ar: None,
liquid: None,
}));
let id_str =
rusty_ulid::Ulid::try_from(value.id.as_slice())
.expect(
"expect valid ids from the database",
);
Image {
id: id_str.to_string(),
description: value.description,
url: image.to_string(),
}
}
}
#[server]
async fn fetch_images() -> Result<Vec<Image>, ServerFnError>
{
let pool = crate::sql::pool()?;
let _username = crate::sql::with_admin_access()?;
let images: Vec<SqlImage> = sqlx::query_as!(
SqlImage,
r#"SELECT
id,
cloudinary_public_id,
description
FROM image
ORDER BY created_at DESC
limit 5"#
)
.fetch_all(&pool)
.await
.map_err(|_| {
ServerFnError::<NoCustomError>::ServerError(
"sql failed".to_string(),
)
})?;
Ok(images.into_iter().map(Image::from).collect())
}
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | false |
rust-adventure/thisweekinbevy | https://github.com/rust-adventure/thisweekinbevy/blob/41f5e797fe6817a4275d80fe15cb158adee670ca/src/app/routes/issue/cards.rs | src/app/routes/issue/cards.rs | use super::PROSE;
use crate::app::issue::ImgDataTransformed;
use leptos::{
either::{Either, EitherOf8},
prelude::*,
};
use std::ops::Not;
#[component]
pub fn SideBySide(
title: String,
type_name: String,
images: Vec<ImgDataTransformed>,
description: String,
primary_url: String,
discord_url: String,
posted_date: Option<String>,
#[prop(optional)] video_url: String,
) -> impl IntoView {
view! {
<div class="bg-ctp-base">
<div class="mx-auto px-4 py-16 sm:px-6 sm:py-24 lg:max-w-7xl lg:px-8">
<div class="lg:grid lg:grid-cols-7 lg:grid-rows-1 lg:gap-x-8 lg:gap-y-10 xl:gap-x-16">
{images
.is_empty()
.not()
.then_some(
view! {
<div class="lg:col-span-4 lg:row-end-1">
<div class="aspect-h-3 aspect-w-4 overflow-hidden rounded-lg bg-gray-100 divide-y-8">
{images
.clone()
.into_iter()
.map(|image| {
view! {
<img
loading="lazy"
class="w-full object-cover object-center"
src=image.url
alt=image.description
/>
}
})
.collect_view()}
</div>
</div>
},
)}
<div class=format!(
"mx-auto mt-14 max-w-2xl sm:mt-16 {} lg:mt-0 lg:max-w-none",
if images.is_empty() {
"col-span-7"
} else {
"lg:col-span-3 lg:row-span-2 lg:row-end-2"
},
)>
<div class="flex flex-col-reverse">
<div class="mt-4">
<h2 class="text-2xl font-bold tracking-tight text-ctp-text sm:text-3xl">
{title}
</h2>
<h3 id="information-heading" class="sr-only">
{type_name}
</h3>
{posted_date
.map(|date| {
view! {
<p class="mt-2 text-sm text-gray-500">
"(Posted " <time datetime=date.clone()>{date.clone()}</time> ")"
</p>
}
})}
</div>
</div>
<div
class=format!("mt-3 text-ctp-text {}", PROSE)
inner_html=description
></div>
<div class="mt-10 grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-2">
{discord_url
.trim()
.is_empty()
.not()
.then_some(
view! {
<a
href=discord_url.clone()
class="flex w-full items-center justify-center rounded-md border border-transparent bg-indigo-600 px-8 py-3 text-base font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:ring-offset-gray-50"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 508.67 96.36"
class="h-4"
>
<g fill="#fff">
<path d="M170.85 20.2h27.3q9.87 0 16.7 3.08a22.5 22.5 0 0 1 10.21 8.58 23.34 23.34 0 0 1 3.4 12.56A23.24 23.24 0 0 1 224.93 57a23.94 23.94 0 0 1-10.79 8.92q-7.24 3.3-17.95 3.29h-25.34Zm25.06 36.54q6.65 0 10.22-3.32a11.8 11.8 0 0 0 3.57-9.07 11.5 11.5 0 0 0-3.18-8.5q-3.2-3.18-9.63-3.19h-8.54v24.08ZM269.34 69.13a37 37 0 0 1-10.22-4.27V53.24a27.77 27.77 0 0 0 9.2 4.38 39.31 39.31 0 0 0 11.17 1.71 8.71 8.71 0 0 0 3.82-.66c.86-.44 1.29-1 1.29-1.58a2.37 2.37 0 0 0-.7-1.75 6.15 6.15 0 0 0-2.73-1.19l-8.4-1.89q-7.22-1.68-10.25-4.65a10.39 10.39 0 0 1-3-7.81 10.37 10.37 0 0 1 2.66-7.07 17.13 17.13 0 0 1 7.56-4.65 36 36 0 0 1 11.48-1.65A43.27 43.27 0 0 1 292 27.69a30.25 30.25 0 0 1 8.12 3.22v11a30 30 0 0 0-7.6-3.11 34 34 0 0 0-8.85-1.16q-6.58 0-6.58 2.24a1.69 1.69 0 0 0 1 1.58 16.14 16.14 0 0 0 3.74 1.08l7 1.26Q295.65 45 299 48t3.36 8.78a11.61 11.61 0 0 1-5.57 10.12q-5.53 3.71-15.79 3.7a46.41 46.41 0 0 1-11.66-1.47ZM318.9 67.66a21 21 0 0 1-9.07-8 21.59 21.59 0 0 1-3-11.34 20.62 20.62 0 0 1 3.15-11.27 21.16 21.16 0 0 1 9.24-7.8 34.25 34.25 0 0 1 14.56-2.84q10.5 0 17.43 4.41v12.83a21.84 21.84 0 0 0-5.7-2.73 22.65 22.65 0 0 0-7-1.05q-6.51 0-10.19 2.38a7.15 7.15 0 0 0-.1 12.43q3.57 2.41 10.36 2.41a23.91 23.91 0 0 0 6.9-1 25.71 25.71 0 0 0 5.84-2.49V66a34 34 0 0 1-17.85 4.62 32.93 32.93 0 0 1-14.57-2.96ZM368.64 67.66a21.77 21.77 0 0 1-9.25-8 21.14 21.14 0 0 1-3.18-11.41A20.27 20.27 0 0 1 359.39 37a21.42 21.42 0 0 1 9.21-7.74 38.17 38.17 0 0 1 28.7 0 21.25 21.25 0 0 1 9.17 7.7 20.41 20.41 0 0 1 3.15 11.27 21.29 21.29 0 0 1-3.15 11.41 21.51 21.51 0 0 1-9.2 8 36.32 36.32 0 0 1-28.63 0Zm21.27-12.42a9.12 9.12 0 0 0 2.56-6.76 8.87 8.87 0 0 0-2.56-6.68 9.53 9.53 0 0 0-7-2.49 9.67 9.67 0 0 0-7 2.49 8.9 8.9 0 0 0-2.55 6.68 9.15 9.15 0 0 0 2.55 6.76 9.53 9.53 0 0 0 7 2.55 9.4 9.4 0 0 0 7-2.55ZM451.69 29v15.14a12.47 12.47 0 0 0-6.93-1.75c-3.73 0-6.61 1.14-8.61 3.4s-3 5.77-3 10.53V69.2H416V28.25h16.8v13q1.4-7.14 4.52-10.53a10.38 10.38 0 0 1 8-3.4 11.71 11.71 0 0 1 6.37 1.68ZM508.67 18.8v50.4h-17.15V60a16.23 16.23 0 0 1-6.62 7.88A20.81 20.81 0 0 1 474 70.6a18.11 18.11 0 0 1-10.15-2.83 18.6 18.6 0 0 1-6.74-7.77 25.75 25.75 0 0 1-2.34-11.17 24.87 24.87 0 0 1 2.48-11.55 19.43 19.43 0 0 1 7.21-8 19.85 19.85 0 0 1 10.61-2.87q12.24 0 16.45 10.64V18.8ZM489 55a8.83 8.83 0 0 0 2.63-6.62A8.42 8.42 0 0 0 489 42a11 11 0 0 0-13.89 0 8.55 8.55 0 0 0-2.59 6.47 8.67 8.67 0 0 0 2.62 6.53 9.42 9.42 0 0 0 6.86 2.51 9.56 9.56 0 0 0 7-2.51ZM107.7 8.07A105.15 105.15 0 0 0 81.47 0a72.06 72.06 0 0 0-3.36 6.83 97.68 97.68 0 0 0-29.11 0A72.37 72.37 0 0 0 45.64 0a105.89 105.89 0 0 0-26.25 8.09C2.79 32.65-1.71 56.6.54 80.21a105.73 105.73 0 0 0 32.17 16.15 77.7 77.7 0 0 0 6.89-11.11 68.42 68.42 0 0 1-10.85-5.18c.91-.66 1.8-1.34 2.66-2a75.57 75.57 0 0 0 64.32 0c.87.71 1.76 1.39 2.66 2a68.68 68.68 0 0 1-10.87 5.19 77 77 0 0 0 6.89 11.1 105.25 105.25 0 0 0 32.19-16.14c2.64-27.38-4.51-51.11-18.9-72.15ZM42.45 65.69C36.18 65.69 31 60 31 53s5-12.74 11.43-12.74S54 46 53.89 53s-5.05 12.69-11.44 12.69Zm42.24 0C78.41 65.69 73.25 60 73.25 53s5-12.74 11.44-12.74S96.23 46 96.12 53s-5.04 12.69-11.43 12.69Z"></path>
<ellipse
cx="242.92"
cy="24.93"
rx="8.55"
ry="7.68"
></ellipse>
<path d="M234.36 37.9a22.08 22.08 0 0 0 17.11 0v31.52h-17.11Z"></path>
</g>
</svg>
</a>
},
)}
{(primary_url != discord_url)
.then_some(view! { <PrimaryLink url=primary_url/> })}
<PrimaryLink url=video_url/>
</div>
// content under description/links
</div>
// technically body content under images
<div class="mx-auto mt-16 w-full max-w-2xl lg:col-span-4 lg:mt-0 lg:max-w-none"></div>
</div>
</div>
</div>
}
}
#[component]
fn PrimaryLink(url: String) -> impl IntoView {
url
.trim()
.is_empty()
.not()
.then_some(view! {
<a
href=url
class=format!(
"flex w-full items-center justify-center rounded-md border border-transparent px-8 py-3 text-base font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-50 {}",
match domain_heuristic(&url) {
Some(Domain::Discord) => {
"bg-brand-discord-faded1 text-brand-discord hover:bg-brand-discord-faded2 focus:ring-brand-discord"
}
Some(Domain::YouTube) => {
"bg-[#ffebeb] text-brand-youtube hover:border-brand-youtube focus:ring-brand-youtube"
}
Some(Domain::Itchio) => {
"bg-brand-itchio-faded1 text-brand-itchio hover:bg-brand-itchio-faded2 focus:ring-brand-itchio"
}
Some(Domain::Apple) => {
"bg-brand-apple-faded1 text-brand-apple hover:bg-brand-apple-faded2 focus:ring-brand-apple"
}
Some(Domain::GitHub) => {
"bg-white text-brand-github hover:border hover:border-brand-github focus:ring-brand-github"
}
Some(Domain::Mastodon) => {
"bg-brand-mastodon-faded1 text-brand-mastodon hover:bg-brand-mastodon-faded2 focus:ring-brand-mastodon"
}
Some(Domain::Cratesio) => "bg-[#264323] text-white focus:ring-[#264323]",
Some(Domain::Docsrs) => "bg-[#353535] text-white focus:ring-[#353535]",
None => "bg-sky-50 text-sky-700 hover:bg-sky-100 focus:ring-sky-500",
},
)
>
{match domain_heuristic(&url) {
Some(d) => d.icon().into_any(),
None => {
view! {
<>
<span>Visit</span>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="ml-6 w-6 h-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M13.5 6H5.25A2.25 2.25 0 0 0 3 8.25v10.5A2.25 2.25 0 0 0 5.25 21h10.5A2.25 2.25 0 0 0 18 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25"
></path>
</svg>
</>
}.into_any()
}
}}
</a>
})
}
#[derive(Debug, Eq, PartialEq)]
enum Domain {
Discord,
YouTube,
Itchio,
Apple,
GitHub,
Mastodon,
Docsrs,
Cratesio,
}
impl Domain {
fn icon(&self) -> impl IntoView {
match self {
Domain::Itchio => EitherOf8::A(view! {
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 774.778 198.926">
<g fill="#fff">
<path d="M253.95 174.12V70.95h34.81v103.17h-34.81zm17.614-111.56q-8.808 0-13.63-4.404-4.614-4.403-4.614-11.743 0-6.92 4.613-11.743 4.823-4.823 13.63-4.823 8.808 0 13.422 4.823 4.823 4.823 4.823 11.743 0 7.34-4.823 11.743-4.613 4.404-13.42 4.404zM340.7 176.22q-15.1 0-22.86-7.97-7.548-8.177-7.548-22.647v-48.86h-13.84V70.948h13.84V45.784h34.81V70.95h22.65v25.79H345.1v43.828q0 4.824 1.888 6.92 2.097 1.888 6.29 1.888 5.663 0 12.373-5.033l7.97 22.858q-6.08 4.2-13.84 6.71-7.76 2.31-19.08 2.31zm85.62 0q-23.907 0-37.747-13.63-13.63-13.632-13.63-39.635 0-18.873 7.758-31.665 7.97-13.21 19.93-17.825 12.58-4.823 23.28-4.823 13.42 0 22.44 5.452 9.02 5.243 13.21 11.534 4.41 6.29 6.29 9.856l-24.11 15.518q-3.35-6.92-7.34-10.905-3.98-3.984-9.64-3.984-7.97 0-12.58 6.29-4.61 6.292-4.61 19.084 0 13.84 5.45 20.34 5.45 6.502 15.52 6.502 7.97 0 13.21-2.94 5.45-2.94 10.277-7.55l11.115 26q-5.034 4.19-14.89 8.39-9.856 3.98-23.906 3.98zm50.65-2.1V34.04h35.02v42.57q4.403-3.146 10.694-5.452 6.29-2.517 15.1-2.517 18.453 0 27.47 10.49 9.227 10.49 9.227 29.57v65.43h-35.02v-61.24q0-8.8-3.35-12.79-3.35-4.19-8.81-4.19-4.61 0-8.6 2.1-3.98 2.1-6.71 4.41v71.72h-35.02zm124.4 2.1q-8.39 0-13.212-4.823-4.823-4.823-4.823-12.372 0-7.55 4.823-12.582 4.823-5.033 13.21-5.033 7.97 0 12.793 5.033 4.83 5.033 4.83 12.582 0 7.55-4.82 12.372-4.61 4.823-12.79 4.823zm25.75-2.1V70.95h34.81v103.17h-34.81zm17.61-111.54q-8.81 0-13.632-4.404-4.613-4.404-4.613-11.743 0-6.92 4.613-11.743 4.823-4.823 13.63-4.823 8.808 0 13.422 4.823 4.823 4.823 4.823 11.743 0 7.34-4.823 11.743-4.613 4.404-13.42 4.404zm78.67 113.64q-12.164 0-21.6-3.984-9.437-4.194-16.147-11.324-6.5-7.34-10.066-17.196-3.355-10.066-3.355-21.81 0-17.404 7.55-30.406 7.758-12.792 19.292-17.825 11.743-5.033 24.325-5.033 18.03 0 29.77 8.388 11.95 8.388 16.78 20.97 4.82 12.582 4.82 23.906 0 11.743-3.57 21.81-3.35 9.855-10.07 17.195-6.5 7.13-16.15 11.33-9.435 3.99-21.6 3.99zm0-26.842q8.807 0 12.79-7.34 3.985-7.55 3.985-20.13 0-11.954-4.194-19.084-4.19-7.13-12.58-7.13-8.18 0-12.37 7.13-4.19 7.13-4.19 19.083 0 12.582 3.99 20.13 4.2 7.34 12.58 7.34z"></path>
<path
d="M28.832 1.228C19.188 6.954.186 28.785.004 34.51v9.478c0 12.014 11.23 22.572 21.424 22.572 12.24 0 22.44-10.146 22.442-22.187 0 12.04 9.85 22.187 22.093 22.187 12.242 0 21.776-10.146 21.776-22.187 0 12.04 10.47 22.187 22.71 22.187h.22c12.24 0 22.72-10.146 22.72-22.187 0 12.04 9.53 22.187 21.77 22.187s22.09-10.146 22.09-22.187c0 12.04 10.2 22.187 22.44 22.187 10.19 0 21.42-10.557 21.42-22.572V34.51c-.19-5.725-19.19-27.556-28.83-33.282-29.97-1.053-50.76-1.234-81.73-1.23C79.59 0 37.36.483 28.83 1.228zm58.753 59.674a25.261 25.261 0 0 1-4.308 5.546 25.588 25.588 0 0 1-17.94 7.32c-6.985 0-13.356-2.8-17.976-7.322-1.67-1.64-2.94-3.394-4.11-5.436v.004c-1.16 2.046-2.79 3.798-4.46 5.44a25.664 25.664 0 0 1-17.97 7.317c-.84 0-1.71-.23-2.42-.47-.982 10.25-1.4 20.04-1.545 27.19v.04c-.02 3.63-.035 6.61-.054 10.75.19 21.51-2.13 69.7 9.48 81.54 17.99 4.2 51.094 6.11 84.31 6.12h.003c33.214-.01 66.32-1.92 84.31-6.11 11.61-11.843 9.29-60.033 9.48-81.536-.017-4.14-.034-7.122-.053-10.75v-.04c-.15-7.142-.565-16.935-1.55-27.183-.71.24-1.587.473-2.43.473a25.681 25.681 0 0 1-17.975-7.316c-1.675-1.644-3.3-3.396-4.463-5.44l-.005-.006c-1.166 2.04-2.437 3.797-4.112 5.436-4.62 4.522-10.99 7.322-17.973 7.322s-13.32-2.8-17.94-7.32a25.428 25.428 0 0 1-4.31-5.547 25.185 25.185 0 0 1-4.266 5.546 25.673 25.673 0 0 1-17.98 7.32c-.244 0-.49-.01-.73-.02h-.008c-.243.01-.486.02-.73.02-6.986 0-13.357-2.8-17.978-7.32a25.161 25.161 0 0 1-4.27-5.544zM69.123 84.775l-.002.008h.02c7.31.016 13.81 0 21.85 8.783 6.34-.663 12.95-.996 19.58-.985h.01c6.63-.01 13.24.33 19.58.99 8.05-8.78 14.54-8.76 21.85-8.78h.02v-.01c3.458 0 17.27 0 26.9 27.04l10.347 37.1c7.665 27.6-2.453 28.28-15.073 28.3-18.72-.69-29.08-14.29-29.08-27.88-10.36 1.7-22.45 2.55-34.535 2.55h-.005c-12.086 0-24.172-.85-34.53-2.55 0 13.59-10.36 27.18-29.078 27.88-12.62-.02-22.74-.7-15.073-28.29l10.34-37.1c9.63-27.04 23.45-27.04 26.9-27.04zm41.44 21.25v.007c-.017.017-19.702 18.096-23.24 24.526l12.89-.516v11.24c0 .527 5.174.313 10.35.074h.007c5.177.24 10.35.453 10.35-.073v-11.24l12.89.514c-3.538-6.43-23.24-24.525-23.24-24.525v-.006l-.002.002z"
color="#000"
></path>
</g>
</svg>
}),
Domain::YouTube => EitherOf8::B(view! {
<svg xmlns="http://www.w3.org/2000/svg" viewBox="409.289 277.787 512 114.301">
<g class="style-scope yt-icon">
<g class="style-scope yt-icon">
<path
fill="red"
d="M569.154 295.637a20.447 20.447 0 0 0-14.436-14.436c-12.728-3.414-63.79-3.414-63.79-3.414s-51.061 0-63.79 3.414a20.447 20.447 0 0 0-14.435 14.436c-3.414 12.728-3.414 39.3-3.414 39.3s0 26.573 3.414 39.302a20.446 20.446 0 0 0 14.435 14.435c12.729 3.414 63.79 3.414 63.79 3.414s51.062 0 63.79-3.414a20.446 20.446 0 0 0 14.436-14.435c3.414-12.729 3.414-39.301 3.414-39.301s-.014-26.573-3.414-39.301Z"
class="style-scope yt-icon"
></path>
<path
fill="#fff"
d="m474.585 359.429 42.42-24.49-42.42-24.488v48.978Z"
class="style-scope yt-icon"
></path>
</g>
<g class="style-scope yt-icon">
<g class="style-scope yt-icon">
<path
d="M34.602 13.004 31.395 1.418h2.798l1.124 5.252c.287 1.294.497 2.397.633 3.31h.082c.094-.655.306-1.75.633-3.291l1.164-5.27h2.799L37.38 13.003v5.557H34.6v-5.557h.002ZM41.47 18.194c-.565-.381-.967-.974-1.207-1.778-.237-.805-.357-1.872-.357-3.208V11.39c0-1.348.136-2.432.409-3.248.273-.816.699-1.413 1.277-1.787.579-.374 1.338-.563 2.279-.563.927 0 1.667.191 2.227.572.558.381.967.978 1.225 1.787.26.812.389 1.891.389 3.239v1.818c0 1.336-.128 2.408-.38 3.217-.25.811-.66 1.404-1.224 1.778-.565.374-1.332.562-2.298.562-.997.002-1.776-.19-2.34-.571Zm3.165-1.962c.156-.409.236-1.074.236-2.001v-3.902c0-.898-.078-1.557-.236-1.97-.157-.417-.432-.624-.828-.624-.38 0-.651.207-.806.623-.158.417-.235 1.073-.235 1.971v3.902c0 .927.075 1.594.225 2.001.15.41.421.614.816.614.396 0 .67-.204.828-.614ZM56.815 18.563H54.61l-.244-1.533h-.061c-.6 1.157-1.498 1.736-2.698 1.736-.83 0-1.444-.273-1.839-.816-.395-.546-.593-1.397-.593-2.554V6.037h2.82v9.193c0 .56.061.957.184 1.195.122.237.327.357.613.357.245 0 .48-.075.706-.226.226-.15.39-.34.5-.571v-9.95h2.818v12.527Z"
class="style-scope yt-icon"
style="fill:#282828"
transform="matrix(5.71504 0 0 5.71504 409.289 277.787)"
></path>
<path
d="M64.475 3.688h-2.798v14.875h-2.759V3.688H56.12V1.42h8.356v2.268Z"
class="style-scope yt-icon"
style="fill:#282828"
transform="matrix(5.71504 0 0 5.71504 409.289 277.787)"
></path>
<path
d="M71.277 18.563H69.07l-.245-1.533h-.06c-.6 1.157-1.499 1.736-2.699 1.736-.83 0-1.443-.273-1.839-.816-.395-.546-.592-1.397-.592-2.554V6.037h2.82v9.193c0 .56.06.957.183 1.195.122.237.327.357.614.357.244 0 .48-.075.705-.226.226-.15.39-.34.501-.571v-9.95h2.818v12.527ZM80.609 8.039c-.172-.79-.447-1.362-.828-1.717-.38-.355-.905-.532-1.573-.532-.518 0-1.002.146-1.451.44-.45.294-.798.677-1.042 1.155h-.021v-6.6h-2.717v17.776h2.329l.287-1.186h.06c.22.424.546.755.981 1.002.436.245.92.367 1.451.367.953 0 1.656-.44 2.105-1.317.45-.88.675-2.25.675-4.118v-1.982c0-1.4-.087-2.498-.256-3.288Zm-2.585 5.11c0 .913-.037 1.628-.113 2.145-.075.518-.2.887-.378 1.103a.871.871 0 0 1-.715.327c-.233 0-.447-.054-.645-.165a1.232 1.232 0 0 1-.48-.489V8.96c.095-.34.26-.618.492-.837.23-.218.485-.327.755-.327a.76.76 0 0 1 .663.337c.158.226.266.602.327 1.133.061.532.092 1.287.092 2.268v1.615h.002ZM84.866 13.871c0 .804.023 1.407.07 1.809.047.402.146.694.297.88.15.183.38.274.693.274.421 0 .713-.164.868-.491.158-.327.243-.873.257-1.634l2.431.143c.014.108.022.259.022.45 0 1.156-.318 2.022-.95 2.593-.633.572-1.53.859-2.686.859-1.39 0-2.364-.436-2.921-1.308-.56-.873-.838-2.22-.838-4.045v-2.187c0-1.88.29-3.253.868-4.118.579-.866 1.569-1.299 2.973-1.299.966 0 1.71.177 2.227.532.517.355.882.905 1.094 1.656.211.75.317 1.785.317 3.106v2.145h-4.722v.635Zm.357-5.903c-.143.176-.237.466-.287.868-.047.402-.07 1.011-.07 1.83v.898h2.062v-.898c0-.805-.028-1.414-.082-1.83-.054-.416-.153-.708-.296-.88-.144-.169-.365-.256-.664-.256-.3.002-.522.092-.663.268Z"
class="style-scope yt-icon"
style="fill:#282828"
transform="matrix(5.71504 0 0 5.71504 409.289 277.787)"
></path>
</g>
</g>
</g>
</svg>
}),
Domain::Discord => EitherOf8::C(view! {
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 508.67 96.36">
<g fill="#fff">
<path d="M170.85 20.2h27.3q9.87 0 16.7 3.08a22.5 22.5 0 0 1 10.21 8.58 23.34 23.34 0 0 1 3.4 12.56A23.24 23.24 0 0 1 224.93 57a23.94 23.94 0 0 1-10.79 8.92q-7.24 3.3-17.95 3.29h-25.34Zm25.06 36.54q6.65 0 10.22-3.32a11.8 11.8 0 0 0 3.57-9.07 11.5 11.5 0 0 0-3.18-8.5q-3.2-3.18-9.63-3.19h-8.54v24.08ZM269.34 69.13a37 37 0 0 1-10.22-4.27V53.24a27.77 27.77 0 0 0 9.2 4.38 39.31 39.31 0 0 0 11.17 1.71 8.71 8.71 0 0 0 3.82-.66c.86-.44 1.29-1 1.29-1.58a2.37 2.37 0 0 0-.7-1.75 6.15 6.15 0 0 0-2.73-1.19l-8.4-1.89q-7.22-1.68-10.25-4.65a10.39 10.39 0 0 1-3-7.81 10.37 10.37 0 0 1 2.66-7.07 17.13 17.13 0 0 1 7.56-4.65 36 36 0 0 1 11.48-1.65A43.27 43.27 0 0 1 292 27.69a30.25 30.25 0 0 1 8.12 3.22v11a30 30 0 0 0-7.6-3.11 34 34 0 0 0-8.85-1.16q-6.58 0-6.58 2.24a1.69 1.69 0 0 0 1 1.58 16.14 16.14 0 0 0 3.74 1.08l7 1.26Q295.65 45 299 48t3.36 8.78a11.61 11.61 0 0 1-5.57 10.12q-5.53 3.71-15.79 3.7a46.41 46.41 0 0 1-11.66-1.47ZM318.9 67.66a21 21 0 0 1-9.07-8 21.59 21.59 0 0 1-3-11.34 20.62 20.62 0 0 1 3.15-11.27 21.16 21.16 0 0 1 9.24-7.8 34.25 34.25 0 0 1 14.56-2.84q10.5 0 17.43 4.41v12.83a21.84 21.84 0 0 0-5.7-2.73 22.65 22.65 0 0 0-7-1.05q-6.51 0-10.19 2.38a7.15 7.15 0 0 0-.1 12.43q3.57 2.41 10.36 2.41a23.91 23.91 0 0 0 6.9-1 25.71 25.71 0 0 0 5.84-2.49V66a34 34 0 0 1-17.85 4.62 32.93 32.93 0 0 1-14.57-2.96ZM368.64 67.66a21.77 21.77 0 0 1-9.25-8 21.14 21.14 0 0 1-3.18-11.41A20.27 20.27 0 0 1 359.39 37a21.42 21.42 0 0 1 9.21-7.74 38.17 38.17 0 0 1 28.7 0 21.25 21.25 0 0 1 9.17 7.7 20.41 20.41 0 0 1 3.15 11.27 21.29 21.29 0 0 1-3.15 11.41 21.51 21.51 0 0 1-9.2 8 36.32 36.32 0 0 1-28.63 0Zm21.27-12.42a9.12 9.12 0 0 0 2.56-6.76 8.87 8.87 0 0 0-2.56-6.68 9.53 9.53 0 0 0-7-2.49 9.67 9.67 0 0 0-7 2.49 8.9 8.9 0 0 0-2.55 6.68 9.15 9.15 0 0 0 2.55 6.76 9.53 9.53 0 0 0 7 2.55 9.4 9.4 0 0 0 7-2.55ZM451.69 29v15.14a12.47 12.47 0 0 0-6.93-1.75c-3.73 0-6.61 1.14-8.61 3.4s-3 5.77-3 10.53V69.2H416V28.25h16.8v13q1.4-7.14 4.52-10.53a10.38 10.38 0 0 1 8-3.4 11.71 11.71 0 0 1 6.37 1.68ZM508.67 18.8v50.4h-17.15V60a16.23 16.23 0 0 1-6.62 7.88A20.81 20.81 0 0 1 474 70.6a18.11 18.11 0 0 1-10.15-2.83 18.6 18.6 0 0 1-6.74-7.77 25.75 25.75 0 0 1-2.34-11.17 24.87 24.87 0 0 1 2.48-11.55 19.43 19.43 0 0 1 7.21-8 19.85 19.85 0 0 1 10.61-2.87q12.24 0 16.45 10.64V18.8ZM489 55a8.83 8.83 0 0 0 2.63-6.62A8.42 8.42 0 0 0 489 42a11 11 0 0 0-13.89 0 8.55 8.55 0 0 0-2.59 6.47 8.67 8.67 0 0 0 2.62 6.53 9.42 9.42 0 0 0 6.86 2.51 9.56 9.56 0 0 0 7-2.51ZM107.7 8.07A105.15 105.15 0 0 0 81.47 0a72.06 72.06 0 0 0-3.36 6.83 97.68 97.68 0 0 0-29.11 0A72.37 72.37 0 0 0 45.64 0a105.89 105.89 0 0 0-26.25 8.09C2.79 32.65-1.71 56.6.54 80.21a105.73 105.73 0 0 0 32.17 16.15 77.7 77.7 0 0 0 6.89-11.11 68.42 68.42 0 0 1-10.85-5.18c.91-.66 1.8-1.34 2.66-2a75.57 75.57 0 0 0 64.32 0c.87.71 1.76 1.39 2.66 2a68.68 68.68 0 0 1-10.87 5.19 77 77 0 0 0 6.89 11.1 105.25 105.25 0 0 0 32.19-16.14c2.64-27.38-4.51-51.11-18.9-72.15ZM42.45 65.69C36.18 65.69 31 60 31 53s5-12.74 11.43-12.74S54 46 53.89 53s-5.05 12.69-11.44 12.69Zm42.24 0C78.41 65.69 73.25 60 73.25 53s5-12.74 11.44-12.74S96.23 46 96.12 53s-5.04 12.69-11.43 12.69Z"></path>
<ellipse cx="242.92" cy="24.93" rx="8.55" ry="7.68"></ellipse>
<path d="M234.36 37.9a22.08 22.08 0 0 0 17.11 0v31.52h-17.11Z"></path>
</g>
</svg>
}),
Domain::Apple => EitherOf8::D(view! {
<>
<span>Apple</span>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 842.32 1000"
class="max-w-[50px]"
>
<path
fill="#fff"
d="M824.666 779.304c-15.123 34.937-33.023 67.096-53.763 96.663-28.271 40.308-51.419 68.208-69.258 83.702-27.653 25.43-57.282 38.455-89.01 39.196-22.776 0-50.245-6.481-82.219-19.63-32.08-13.085-61.56-19.566-88.516-19.566-28.27 0-58.59 6.48-91.022 19.567-32.48 13.148-58.646 20-78.652 20.678-30.425 1.296-60.75-12.098-91.022-40.245-19.32-16.852-43.486-45.74-72.436-86.665-31.06-43.702-56.597-94.38-76.602-152.155C10.74 658.443 0 598.013 0 539.509c0-67.017 14.481-124.818 43.486-173.255 22.796-38.906 53.122-69.596 91.078-92.126 37.955-22.53 78.967-34.012 123.132-34.746 24.166 0 55.856 7.475 95.238 22.166 39.27 14.74 64.485 22.215 75.54 22.215 8.266 0 36.277-8.74 83.764-26.166 44.906-16.16 82.806-22.85 113.854-20.215 84.133 6.79 147.341 39.955 189.377 99.707-75.245 45.59-112.466 109.447-111.725 191.364.68 63.807 23.827 116.904 69.319 159.063 20.617 19.568 43.64 34.69 69.257 45.431-5.555 16.11-11.42 31.542-17.654 46.357zM631.71 20.006c0 50.011-18.27 96.707-54.69 139.928-43.949 51.38-97.108 81.071-154.754 76.386-.735-6-1.16-12.314-1.16-18.95 0-48.01 20.9-99.392 58.016-141.403 18.53-21.271 42.098-38.957 70.677-53.066C578.316 9.002 605.29 1.316 630.66 0c.74 6.686 1.05 13.372 1.05 20.005z"
></path>
</svg>
</>
}),
Domain::GitHub => EitherOf8::E(view! {
<>
<svg
xmlns="http://www.w3.org/2000/svg"
class="w-8"
preserveAspectRatio="xMinYMin meet"
viewBox="0 0 256 249"
>
<g fill="#161614">
<path d="M127.505 0C57.095 0 0 57.085 0 127.505c0 56.336 36.534 104.13 87.196 120.99 6.372 1.18 8.712-2.766 8.712-6.134 0-3.04-.119-13.085-.173-23.739-35.473 7.713-42.958-15.044-42.958-15.044-5.8-14.738-14.157-18.656-14.157-18.656-11.568-7.914.872-7.752.872-7.752 12.804.9 19.546 13.14 19.546 13.14 11.372 19.493 29.828 13.857 37.104 10.6 1.144-8.242 4.449-13.866 8.095-17.05-28.32-3.225-58.092-14.158-58.092-63.014 0-13.92 4.981-25.295 13.138-34.224-1.324-3.212-5.688-16.18 1.235-33.743 0 0 10.707-3.427 35.073 13.07 10.17-2.826 21.078-4.242 31.914-4.29 10.836.048 21.752 1.464 31.942 4.29 24.337-16.497 35.029-13.07 35.029-13.07 6.94 17.563 2.574 30.531 1.25 33.743 8.175 8.929 13.122 20.303 13.122 34.224 0 48.972-29.828 59.756-58.22 62.912 4.573 3.957 8.648 11.717 8.648 23.612 0 17.06-.148 30.791-.148 34.991 0 3.393 2.295 7.369 8.759 6.117 50.634-16.879 87.122-64.656 87.122-120.973C255.009 57.085 197.922 0 127.505 0"></path>
<path d="M47.755 181.634c-.28.633-1.278.823-2.185.389-.925-.416-1.445-1.28-1.145-1.916.275-.652 1.273-.834 2.196-.396.927.415 1.455 1.287 1.134 1.923m6.272 5.596c-.608.564-1.797.302-2.604-.589-.834-.889-.99-2.077-.373-2.65.627-.563 1.78-.3 2.616.59.834.899.996 2.08.36 2.65m4.304 7.159c-.782.543-2.06.034-2.849-1.1-.781-1.133-.781-2.493.017-3.038.792-.545 2.05-.055 2.85 1.07.78 1.153.78 2.513-.019 3.069m7.277 8.292c-.699.77-2.187.564-3.277-.488-1.114-1.028-1.425-2.487-.724-3.258.707-.772 2.204-.555 3.302.488 1.107 1.026 1.445 2.496.7 3.258m9.403 2.8c-.307.998-1.741 1.452-3.185 1.028-1.442-.437-2.386-1.607-2.095-2.616.3-1.005 1.74-1.478 3.195-1.024 1.44.435 2.386 1.596 2.086 2.612m10.703 1.187c.036 1.052-1.189 1.924-2.705 1.943-1.525.033-2.758-.818-2.774-1.852 0-1.062 1.197-1.926 2.721-1.951 1.516-.03 2.758.815 2.758 1.86m10.514-.403c.182 1.026-.872 2.08-2.377 2.36-1.48.27-2.85-.363-3.039-1.38-.184-1.052.89-2.105 2.367-2.378 1.508-.262 2.857.355 3.049 1.398"></path>
</g>
</svg>
<span class="text-[#1b1f23] ml-4 font-bold">GitHub</span>
</>
}),
Domain::Mastodon => EitherOf8::F(view! {
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 314 80" fill="none">
<path
fill="url(#a)"
d="M73.445 17.696C72.317 9.198 65.004 2.49 56.346 1.198 54.881.98 49.346.176 36.521.176h-.096c-12.837 0-15.587.803-17.052 1.022-8.43 1.267-16.115 7.281-17.988 15.89C.496 21.325.4 26.023.568 30.334c.24 6.186.289 12.347.84 18.507a88.18 88.18 0 0 0 1.994 12.14c1.777 7.378 8.958 13.514 15.995 16.01a42.384 42.384 0 0 0 23.392 1.254 37.162 37.162 0 0 0 2.534-.706c1.885-.609 4.094-1.29 5.727-2.484.025-.012.037-.036.049-.06a.178.178 0 0 0 .024-.086v-5.966s0-.048-.024-.073c0-.024-.024-.049-.049-.06a16.122 16.122 0 0 1-.072-.037h-.072a63.814 63.814 0 0 1-15.178 1.802c-8.802 0-11.168-4.237-11.84-5.99a19.304 19.304 0 0 1-1.033-4.725c0-.024 0-.048.012-.073 0-.024.024-.048.049-.06l.071-.037h.085a63.02 63.02 0 0 0 14.938 1.802c1.212 0 2.413 0 3.626-.037 5.055-.146 10.387-.401 15.37-1.388.12-.024.253-.048.36-.073 7.854-1.534 15.323-6.331 16.08-18.482.024-.475.096-5.017.096-5.504 0-1.692.54-11.968-.084-18.287l-.013-.025Z"
></path>
<path
fill="#fff"
d="M15.315 22.445c0-2.484 1.957-4.48 4.382-4.48 2.426 0 4.383 2.009 4.383 4.48 0 2.472-1.957 4.48-4.383 4.48-2.425 0-4.382-2.008-4.382-4.48Z"
></path>
<path
fill="#000"
| rust | MIT | 41f5e797fe6817a4275d80fe15cb158adee670ca | 2026-01-04T20:19:42.107426Z | true |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/swapchain.rs | src/swapchain.rs | use std::{collections::VecDeque, slice, sync::Arc};
use ash::{
khr,
prelude::VkResult,
vk::{self, CompositeAlphaFlagsKHR},
};
use crate::{device::Device, surface::Surface, ImageDimensions};
pub struct Frame {
command_buffer: vk::CommandBuffer,
image_available_semaphore: vk::Semaphore,
render_finished_semaphore: vk::Semaphore,
pub present_finished: vk::Fence,
device: Arc<Device>,
}
impl Frame {
fn destroy(&mut self, pool: &vk::CommandPool) {
unsafe {
self.device.destroy_fence(self.present_finished, None);
self.device
.destroy_semaphore(self.image_available_semaphore, None);
self.device
.destroy_semaphore(self.render_finished_semaphore, None);
self.device
.free_command_buffers(*pool, &[self.command_buffer]);
}
}
}
impl Frame {
fn new(device: &Arc<Device>, command_pool: &vk::CommandPool) -> VkResult<Self> {
let present_finished = unsafe {
device.create_fence(
&vk::FenceCreateInfo::default().flags(vk::FenceCreateFlags::default()),
None,
)
}?;
let image_available_semaphore =
unsafe { device.create_semaphore(&vk::SemaphoreCreateInfo::default(), None)? };
let render_finished_semaphore =
unsafe { device.create_semaphore(&vk::SemaphoreCreateInfo::default(), None)? };
let alloc_info = vk::CommandBufferAllocateInfo::default()
.command_pool(*command_pool)
.level(vk::CommandBufferLevel::PRIMARY)
.command_buffer_count(1);
let command_buffer = unsafe { device.allocate_command_buffers(&alloc_info) }?[0];
Ok(Self {
command_buffer,
image_available_semaphore,
render_finished_semaphore,
present_finished,
device: device.clone(),
})
}
}
pub struct FrameGuard {
frame: Frame,
extent: vk::Extent2D,
image_idx: usize,
device: Arc<Device>,
}
pub struct Swapchain {
pub images: Vec<vk::Image>,
pub views: Vec<vk::ImageView>,
pub frames: VecDeque<Frame>,
command_pool: vk::CommandPool,
pub current_image: usize,
pub format: vk::SurfaceFormatKHR,
pub extent: vk::Extent2D,
pub image_dimensions: ImageDimensions,
inner: vk::SwapchainKHR,
loader: khr::swapchain::Device,
device: Arc<Device>,
}
impl Swapchain {
const SUBRANGE: vk::ImageSubresourceRange = vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1,
base_array_layer: 0,
layer_count: 1,
};
pub fn format(&self) -> vk::Format {
self.format.format
}
pub fn extent(&self) -> vk::Extent2D {
self.extent
}
pub fn new(
device: &Arc<Device>,
surface: &Surface,
swapchain_loader: khr::swapchain::Device,
) -> VkResult<Self> {
let info = surface.info(device);
let capabilities = info.capabilities;
let format = info
.formats
.iter()
.find(|format| {
matches!(
format.format,
vk::Format::B8G8R8A8_SRGB | vk::Format::R8G8B8A8_SRGB
)
})
.unwrap_or(&info.formats[0]);
let image_count = capabilities
.max_image_count
.min(3)
.max(capabilities.min_image_count);
let queue_family_index = [device.main_queue_family_idx];
let mut extent = capabilities.current_extent;
//Sadly _current_extent_ can be outside the min/max capabilities :(.
extent.width = extent.width.min(capabilities.max_image_extent.width);
extent.height = extent.height.min(capabilities.max_image_extent.height);
assert!(capabilities
.supported_composite_alpha
.contains(CompositeAlphaFlagsKHR::OPAQUE));
let swapchain_create_info = vk::SwapchainCreateInfoKHR::default()
.surface(**surface)
.image_format(format.format)
.image_usage(vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::TRANSFER_SRC)
.image_extent(extent)
.image_color_space(format.color_space)
.min_image_count(image_count)
.image_array_layers(capabilities.max_image_array_layers)
.queue_family_indices(&queue_family_index)
.image_sharing_mode(vk::SharingMode::EXCLUSIVE)
.pre_transform(vk::SurfaceTransformFlagsKHR::IDENTITY)
.composite_alpha(CompositeAlphaFlagsKHR::OPAQUE)
.present_mode(vk::PresentModeKHR::FIFO)
.clipped(true);
let swapchain = unsafe { swapchain_loader.create_swapchain(&swapchain_create_info, None)? };
let images = unsafe { swapchain_loader.get_swapchain_images(swapchain)? };
let views = images
.iter()
.map(|img| device.create_2d_view(img, format.format))
.collect::<VkResult<Vec<_>>>()?;
let frames = VecDeque::new();
let command_pool = unsafe {
device.create_command_pool(
&vk::CommandPoolCreateInfo::default()
.flags(vk::CommandPoolCreateFlags::TRANSIENT)
.queue_family_index(device.main_queue_family_idx),
None,
)?
};
let memory_reqs = unsafe { device.get_image_memory_requirements(images[0]) };
let image_dimensions =
ImageDimensions::new(extent.width as _, extent.height as _, memory_reqs.alignment);
Ok(Self {
images,
views,
frames,
command_pool,
current_image: 0,
image_dimensions,
format: *format,
extent,
inner: swapchain,
loader: swapchain_loader,
device: device.clone(),
})
}
pub fn destroy(&self) {
for view in self.views.iter() {
unsafe { self.device.destroy_image_view(*view, None) };
}
unsafe { self.loader.destroy_swapchain(self.inner, None) };
}
pub fn recreate(&mut self, device: &Device, surface: &Surface) -> VkResult<()> {
let info = surface.info(device);
let capabilities = info.capabilities;
for view in self.views.iter() {
unsafe { self.device.destroy_image_view(*view, None) };
}
let old_swapchain = self.inner;
let queue_family_index = [device.main_queue_family_idx];
let extent = capabilities.current_extent;
self.extent.width = extent.width.min(capabilities.max_image_extent.width);
self.extent.height = extent.height.min(capabilities.max_image_extent.height);
let swapchain_create_info = vk::SwapchainCreateInfoKHR::default()
.surface(**surface)
.old_swapchain(old_swapchain)
.image_format(self.format.format)
.image_usage(vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::TRANSFER_SRC)
.image_extent(self.extent)
.image_color_space(self.format.color_space)
.min_image_count(self.images.len() as u32)
.image_array_layers(capabilities.max_image_array_layers)
.queue_family_indices(&queue_family_index)
.image_sharing_mode(vk::SharingMode::EXCLUSIVE)
.pre_transform(vk::SurfaceTransformFlagsKHR::IDENTITY)
.composite_alpha(CompositeAlphaFlagsKHR::OPAQUE)
.present_mode(vk::PresentModeKHR::FIFO)
.clipped(true);
self.inner = unsafe { self.loader.create_swapchain(&swapchain_create_info, None)? };
unsafe { self.loader.destroy_swapchain(old_swapchain, None) };
self.images = unsafe { self.loader.get_swapchain_images(self.inner)? };
self.views = self
.images
.iter()
.map(|img| device.create_2d_view(img, self.format.format))
.collect::<VkResult<Vec<_>>>()?;
let memory_reqs = unsafe { device.get_image_memory_requirements(self.images[0]) };
self.image_dimensions =
ImageDimensions::new(extent.width as _, extent.height as _, memory_reqs.alignment);
Ok(())
}
pub fn get_current_frame(&self) -> Option<&Frame> {
self.frames.back()
}
pub fn get_current_image(&self) -> &vk::Image {
&self.images[self.current_image]
}
pub fn get_current_image_view(&self) -> &vk::ImageView {
&self.views[self.current_image]
}
pub fn acquire_next_image(&mut self) -> VkResult<FrameGuard> {
self.frames.retain_mut(|frame| {
let status = unsafe { self.device.get_fence_status(frame.present_finished) };
if status == Ok(true) {
frame.destroy(&self.command_pool);
false
} else {
true
}
});
let mut frame = Frame::new(&self.device, &self.command_pool)?;
let idx = match unsafe {
self.loader.acquire_next_image(
self.inner,
u64::MAX,
frame.image_available_semaphore,
vk::Fence::null(),
)
} {
Ok((idx, false)) => idx,
Ok((_, true)) | Err(vk::Result::ERROR_OUT_OF_DATE_KHR) => {
frame.destroy(&self.command_pool);
return VkResult::Err(vk::Result::ERROR_OUT_OF_DATE_KHR);
}
Err(e) => return Err(e),
};
self.current_image = idx as usize;
unsafe {
self.device.begin_command_buffer(
frame.command_buffer,
&vk::CommandBufferBeginInfo::default()
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT),
)?
};
let image_barrier = vk::ImageMemoryBarrier2::default()
.src_stage_mask(vk::PipelineStageFlags2::COLOR_ATTACHMENT_OUTPUT)
.dst_stage_mask(vk::PipelineStageFlags2::COLOR_ATTACHMENT_OUTPUT)
.src_access_mask(vk::AccessFlags2::COLOR_ATTACHMENT_WRITE)
.subresource_range(Self::SUBRANGE)
.image(self.images[self.current_image])
.old_layout(vk::ImageLayout::UNDEFINED)
.new_layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL);
let dependency_info =
vk::DependencyInfo::default().image_memory_barriers(slice::from_ref(&image_barrier));
unsafe {
self.device
.cmd_pipeline_barrier2(frame.command_buffer, &dependency_info)
};
Ok(FrameGuard {
frame,
extent: self.extent,
image_idx: self.current_image,
device: self.device.clone(),
})
}
pub fn submit_image(&mut self, queue: &vk::Queue, frame_guard: FrameGuard) -> VkResult<()> {
let frame = frame_guard.frame;
let image_barrier = vk::ImageMemoryBarrier2::default()
.src_stage_mask(vk::PipelineStageFlags2::COLOR_ATTACHMENT_OUTPUT)
.dst_stage_mask(vk::PipelineStageFlags2::BOTTOM_OF_PIPE)
.src_access_mask(vk::AccessFlags2::COLOR_ATTACHMENT_WRITE)
.subresource_range(Self::SUBRANGE)
.image(self.images[frame_guard.image_idx])
.old_layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL)
.new_layout(vk::ImageLayout::PRESENT_SRC_KHR);
let dependency_info =
vk::DependencyInfo::default().image_memory_barriers(slice::from_ref(&image_barrier));
unsafe {
self.device
.cmd_pipeline_barrier2(frame.command_buffer, &dependency_info)
};
unsafe { self.device.end_command_buffer(frame.command_buffer) }?;
let wait_semaphores = [frame.image_available_semaphore];
let wait_stages = [vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT];
let signal_semaphores = [frame.render_finished_semaphore];
let submit_info = vk::SubmitInfo::default()
.wait_semaphores(&wait_semaphores)
.wait_dst_stage_mask(&wait_stages)
.command_buffers(slice::from_ref(&frame.command_buffer))
.signal_semaphores(&signal_semaphores);
unsafe {
self.device
.queue_submit(*queue, &[submit_info], frame.present_finished)?
};
self.frames.push_back(frame);
let image_indices = [frame_guard.image_idx as u32];
let present_info = vk::PresentInfoKHR::default()
.wait_semaphores(&signal_semaphores)
.swapchains(slice::from_ref(&self.inner))
.image_indices(&image_indices);
match unsafe { self.loader.queue_present(*queue, &present_info) } {
Ok(false) => Ok(()),
Ok(true) | Err(vk::Result::ERROR_OUT_OF_DATE_KHR) => {
VkResult::Err(vk::Result::ERROR_OUT_OF_DATE_KHR)
}
Err(e) => Err(e),
}
}
}
impl Drop for Swapchain {
fn drop(&mut self) {
unsafe {
for view in self.views.iter() {
self.device.destroy_image_view(*view, None);
}
self.loader.destroy_swapchain(self.inner, None);
self.frames
.iter_mut()
.for_each(|f| f.destroy(&self.command_pool));
self.device.destroy_command_pool(self.command_pool, None);
}
}
}
impl FrameGuard {
pub fn command_buffer(&self) -> &vk::CommandBuffer {
&self.frame.command_buffer
}
pub fn begin_rendering(&mut self, view: &vk::ImageView, color: [f32; 4]) {
let clear_color = vk::ClearValue {
color: vk::ClearColorValue { float32: color },
};
let color_attachments = [vk::RenderingAttachmentInfo::default()
.image_view(*view)
.image_layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL)
.resolve_image_layout(vk::ImageLayout::PRESENT_SRC_KHR)
.load_op(vk::AttachmentLoadOp::CLEAR)
.store_op(vk::AttachmentStoreOp::STORE)
.clear_value(clear_color)];
let rendering_info = vk::RenderingInfo::default()
.render_area(self.extent.into())
.layer_count(1)
.color_attachments(&color_attachments);
unsafe {
self.device
.dynamic_rendering
.cmd_begin_rendering(self.frame.command_buffer, &rendering_info)
};
let viewport = vk::Viewport {
x: 0.0,
y: self.extent.height as f32,
width: self.extent.width as f32,
height: -(self.extent.height as f32),
min_depth: 0.0,
max_depth: 1.0,
};
self.set_viewports(&[viewport]);
self.set_scissors(&[vk::Rect2D {
offset: vk::Offset2D { x: 0, y: 0 },
extent: self.extent,
}]);
}
pub fn draw(
&mut self,
vertex_count: u32,
first_vertex: u32,
instance_count: u32,
first_instance: u32,
) {
unsafe {
self.device.cmd_draw(
self.frame.command_buffer,
vertex_count,
instance_count,
first_vertex,
first_instance,
)
};
}
pub fn draw_indexed(
&mut self,
index_count: u32,
first_index: u32,
vertex_offset: i32,
instance_count: u32,
first_instance: u32,
) {
unsafe {
self.device.cmd_draw_indexed(
self.frame.command_buffer,
index_count,
instance_count,
first_index,
vertex_offset,
first_instance,
)
};
}
pub fn bind_index_buffer(&self, buffer: vk::Buffer, offset: u64) {
unsafe {
self.device.cmd_bind_index_buffer(
self.frame.command_buffer,
buffer,
offset,
vk::IndexType::UINT32,
)
};
}
pub fn bind_vertex_buffer(&self, buffer: vk::Buffer) {
let buffers = [buffer];
let offsets = [0];
unsafe {
self.device
.cmd_bind_vertex_buffers(self.frame.command_buffer, 0, &buffers, &offsets)
};
}
pub fn bind_descriptor_sets(
&self,
bind_point: vk::PipelineBindPoint,
pipeline_layout: vk::PipelineLayout,
descriptor_sets: &[vk::DescriptorSet],
) {
unsafe {
self.device.cmd_bind_descriptor_sets(
self.frame.command_buffer,
bind_point,
pipeline_layout,
0,
descriptor_sets,
&[],
)
};
}
pub fn push_constant<T>(
&self,
pipeline_layout: vk::PipelineLayout,
stages: vk::ShaderStageFlags,
data: &[T],
) {
let ptr = core::ptr::from_ref(data);
let bytes = unsafe { core::slice::from_raw_parts(ptr.cast(), std::mem::size_of_val(data)) };
unsafe {
self.device.cmd_push_constants(
self.frame.command_buffer,
pipeline_layout,
stages,
0,
bytes,
)
};
}
pub fn set_viewports(&self, viewports: &[vk::Viewport]) {
unsafe {
self.device
.cmd_set_viewport(self.frame.command_buffer, 0, viewports)
}
}
pub fn set_scissors(&self, viewports: &[vk::Rect2D]) {
unsafe {
self.device
.cmd_set_scissor(self.frame.command_buffer, 0, viewports)
}
}
pub fn bind_pipeline(&self, bind_point: vk::PipelineBindPoint, &pipeline: &vk::Pipeline) {
unsafe {
self.device
.cmd_bind_pipeline(self.frame.command_buffer, bind_point, pipeline)
}
}
pub fn dispatch(&self, x: u32, y: u32, z: u32) {
unsafe { self.device.cmd_dispatch(self.frame.command_buffer, x, y, z) };
}
pub fn end_rendering(&mut self) {
unsafe {
self.device
.dynamic_rendering
.cmd_end_rendering(self.frame.command_buffer)
};
}
}
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/pipeline_arena.rs | src/pipeline_arena.rs | use ahash::{AHashMap, AHashSet};
use anyhow::Result;
use either::Either;
use slotmap::SlotMap;
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use ash::{
prelude::VkResult,
vk::{self},
};
use crate::{Device, ShaderCompiler, ShaderKind, ShaderSource, Watcher};
pub struct ComputePipeline {
pub layout: vk::PipelineLayout,
pub pipeline: vk::Pipeline,
shader_path: PathBuf,
device: Arc<Device>,
}
impl Drop for ComputePipeline {
fn drop(&mut self) {
unsafe {
self.device.destroy_pipeline(self.pipeline, None);
self.device.destroy_pipeline_layout(self.layout, None);
}
}
}
impl ComputePipeline {
fn new(
device: &Arc<Device>,
shader_compiler: &ShaderCompiler,
shader_path: impl AsRef<Path>,
push_constant_ranges: &[vk::PushConstantRange],
descriptor_set_layouts: &[vk::DescriptorSetLayout],
) -> Result<Self> {
let cs_bytes = shader_compiler.compile(&shader_path, shaderc::ShaderKind::Compute)?;
let pipeline_layout = unsafe {
device.create_pipeline_layout(
&vk::PipelineLayoutCreateInfo::default()
.set_layouts(descriptor_set_layouts)
.push_constant_ranges(push_constant_ranges),
None,
)?
};
let mut shader_module = vk::ShaderModuleCreateInfo::default().code(cs_bytes.as_binary());
let shader_stage = vk::PipelineShaderStageCreateInfo::default()
.stage(vk::ShaderStageFlags::COMPUTE)
.name(c"main")
.push_next(&mut shader_module);
let create_info = vk::ComputePipelineCreateInfo::default()
.layout(pipeline_layout)
.stage(shader_stage);
let pipeline = unsafe {
device.create_compute_pipelines(vk::PipelineCache::null(), &[create_info], None)
};
let pipeline = pipeline.map_err(|(_, err)| err)?[0];
Ok(Self {
pipeline,
shader_path: shader_path.as_ref().to_path_buf(),
layout: pipeline_layout,
device: device.clone(),
})
}
pub fn reload(&mut self, shader_compiler: &ShaderCompiler) -> Result<()> {
let cs_bytes = shader_compiler.compile(&self.shader_path, shaderc::ShaderKind::Compute)?;
unsafe { self.device.destroy_pipeline(self.pipeline, None) }
let mut shader_module = vk::ShaderModuleCreateInfo::default().code(cs_bytes.as_binary());
let shader_stage = vk::PipelineShaderStageCreateInfo::default()
.stage(vk::ShaderStageFlags::COMPUTE)
.name(c"main")
.push_next(&mut shader_module);
let create_info = vk::ComputePipelineCreateInfo::default()
.layout(self.layout)
.stage(shader_stage);
let pipeline = unsafe {
self.device
.create_compute_pipelines(vk::PipelineCache::null(), &[create_info], None)
};
let pipeline = pipeline.map_err(|(_, err)| err)?[0];
self.pipeline = pipeline;
Ok(())
}
}
pub struct VertexInputDesc {
pub primitive_topology: vk::PrimitiveTopology,
pub primitive_restart: bool,
}
impl Default for VertexInputDesc {
fn default() -> Self {
Self {
primitive_topology: vk::PrimitiveTopology::TRIANGLE_LIST,
primitive_restart: false,
}
}
}
pub struct VertexShaderDesc {
pub shader_path: PathBuf,
pub dynamic_state: Vec<vk::DynamicState>,
pub line_width: f32,
pub polygon_mode: vk::PolygonMode,
pub cull_mode: vk::CullModeFlags,
pub front_face: vk::FrontFace,
pub viewport_count: u32,
pub scissot_count: u32,
}
impl Default for VertexShaderDesc {
fn default() -> Self {
Self {
shader_path: PathBuf::new(),
dynamic_state: vec![vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR],
line_width: 1.0,
polygon_mode: vk::PolygonMode::FILL,
cull_mode: vk::CullModeFlags::BACK,
front_face: vk::FrontFace::COUNTER_CLOCKWISE,
viewport_count: 1,
scissot_count: 1,
}
}
}
pub struct FragmentShaderDesc {
pub shader_path: PathBuf,
}
pub struct FragmentOutputDesc {
pub surface_format: vk::Format,
pub multisample_state: vk::SampleCountFlags,
}
impl Default for FragmentOutputDesc {
fn default() -> Self {
Self {
surface_format: vk::Format::B8G8R8A8_SRGB,
multisample_state: vk::SampleCountFlags::TYPE_1,
}
}
}
pub struct RenderPipeline {
pub layout: vk::PipelineLayout,
pub pipeline: vk::Pipeline,
vertex_input_lib: vk::Pipeline,
vertex_shader_lib: vk::Pipeline,
fragment_shader_lib: vk::Pipeline,
fragment_output_lib: vk::Pipeline,
device: Arc<Device>,
}
impl RenderPipeline {
pub fn new(
device: &Arc<Device>,
shader_compiler: &ShaderCompiler,
vertex_input_desc: &VertexInputDesc,
vertex_shader_desc: &VertexShaderDesc,
fragment_shader_desc: &FragmentShaderDesc,
fragment_output_desc: &FragmentOutputDesc,
push_constant_ranges: &[vk::PushConstantRange],
descriptor_set_layouts: &[vk::DescriptorSetLayout],
) -> Result<Self> {
let vs_bytes = shader_compiler
.compile(&vertex_shader_desc.shader_path, shaderc::ShaderKind::Vertex)?;
let fs_bytes = shader_compiler.compile(
&fragment_shader_desc.shader_path,
shaderc::ShaderKind::Fragment,
)?;
let pipeline_layout = unsafe {
device.create_pipeline_layout(
&vk::PipelineLayoutCreateInfo::default()
.set_layouts(descriptor_set_layouts)
.push_constant_ranges(push_constant_ranges),
None,
)?
};
use vk::GraphicsPipelineLibraryFlagsEXT as GPF;
let vertex_input_lib = {
let input_ass = vk::PipelineInputAssemblyStateCreateInfo::default()
.topology(vertex_input_desc.primitive_topology)
.primitive_restart_enable(vertex_input_desc.primitive_restart);
let vertex_input = vk::PipelineVertexInputStateCreateInfo::default();
create_library(device, GPF::VERTEX_INPUT_INTERFACE, |desc| {
desc.vertex_input_state(&vertex_input)
.input_assembly_state(&input_ass)
})?
};
let vertex_shader_lib = {
let mut shader_module =
vk::ShaderModuleCreateInfo::default().code(vs_bytes.as_binary());
let shader_stage = vk::PipelineShaderStageCreateInfo::default()
.stage(vk::ShaderStageFlags::VERTEX)
.name(c"main")
.push_next(&mut shader_module);
let dynamic_state = vk::PipelineDynamicStateCreateInfo::default()
.dynamic_states(&vertex_shader_desc.dynamic_state);
let rasterization_state = vk::PipelineRasterizationStateCreateInfo::default()
.line_width(vertex_shader_desc.line_width)
.polygon_mode(vertex_shader_desc.polygon_mode)
.cull_mode(vertex_shader_desc.cull_mode)
.front_face(vertex_shader_desc.front_face);
let viewport_state = vk::PipelineViewportStateCreateInfo::default()
.viewport_count(vertex_shader_desc.viewport_count)
.scissor_count(vertex_shader_desc.scissot_count);
create_library(device, GPF::PRE_RASTERIZATION_SHADERS, |desc| {
desc.layout(pipeline_layout)
.stages(std::slice::from_ref(&shader_stage))
.dynamic_state(&dynamic_state)
.viewport_state(&viewport_state)
.rasterization_state(&rasterization_state)
})?
};
let fragment_shader_lib = {
let mut shader_module =
vk::ShaderModuleCreateInfo::default().code(fs_bytes.as_binary());
let shader_stage = vk::PipelineShaderStageCreateInfo::default()
.stage(vk::ShaderStageFlags::FRAGMENT)
.name(c"main")
.push_next(&mut shader_module);
let depth_stencil_state = vk::PipelineDepthStencilStateCreateInfo::default();
create_library(device, GPF::FRAGMENT_SHADER, |desc| {
desc.layout(pipeline_layout)
.stages(std::slice::from_ref(&shader_stage))
.depth_stencil_state(&depth_stencil_state)
})?
};
let fragment_output_lib = {
let color_attachment_formats = [fragment_output_desc.surface_format];
let mut dyn_render = vk::PipelineRenderingCreateInfo::default()
.color_attachment_formats(&color_attachment_formats);
let multisample_state = vk::PipelineMultisampleStateCreateInfo::default()
.rasterization_samples(vk::SampleCountFlags::TYPE_1);
create_library(device, GPF::FRAGMENT_OUTPUT_INTERFACE, |desc| {
desc.multisample_state(&multisample_state)
.push_next(&mut dyn_render)
})?
};
let pipeline = Self::link_libraries(
device,
&pipeline_layout,
&vertex_input_lib,
&vertex_shader_lib,
&fragment_shader_lib,
&fragment_output_lib,
)?;
Ok(Self {
device: device.clone(),
layout: pipeline_layout,
pipeline,
vertex_input_lib,
vertex_shader_lib,
fragment_shader_lib,
fragment_output_lib,
})
}
pub fn reload_vertex_lib(
&mut self,
shader_compiler: &ShaderCompiler,
shader_path: impl AsRef<Path>,
) -> Result<()> {
let vs_bytes = shader_compiler.compile(shader_path, shaderc::ShaderKind::Vertex)?;
unsafe { self.device.destroy_pipeline(self.vertex_shader_lib, None) };
let mut shader_module = vk::ShaderModuleCreateInfo::default().code(vs_bytes.as_binary());
let shader_stage = vk::PipelineShaderStageCreateInfo::default()
.stage(vk::ShaderStageFlags::VERTEX)
.name(c"main")
.push_next(&mut shader_module);
let dynamic_state = vk::PipelineDynamicStateCreateInfo::default()
.dynamic_states(&[vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR]);
let rasterization_state = vk::PipelineRasterizationStateCreateInfo::default()
.line_width(1.0)
.polygon_mode(vk::PolygonMode::FILL)
.cull_mode(vk::CullModeFlags::BACK)
.front_face(vk::FrontFace::COUNTER_CLOCKWISE);
let viewport_state = vk::PipelineViewportStateCreateInfo::default()
.viewport_count(1)
.scissor_count(1);
let vertex_shader_lib = create_library(
&self.device,
vk::GraphicsPipelineLibraryFlagsEXT::PRE_RASTERIZATION_SHADERS,
|desc| {
desc.layout(self.layout)
.stages(std::slice::from_ref(&shader_stage))
.dynamic_state(&dynamic_state)
.viewport_state(&viewport_state)
.rasterization_state(&rasterization_state)
},
)?;
self.vertex_shader_lib = vertex_shader_lib;
Ok(())
}
pub fn reload_fragment_lib(
&mut self,
shader_compiler: &ShaderCompiler,
shader_path: impl AsRef<Path>,
) -> Result<()> {
let fs_bytes = shader_compiler.compile(shader_path, shaderc::ShaderKind::Fragment)?;
unsafe { self.device.destroy_pipeline(self.fragment_shader_lib, None) };
let mut shader_module = vk::ShaderModuleCreateInfo::default().code(fs_bytes.as_binary());
let shader_stage = vk::PipelineShaderStageCreateInfo::default()
.stage(vk::ShaderStageFlags::FRAGMENT)
.name(c"main")
.push_next(&mut shader_module);
let depth_stencil_state = vk::PipelineDepthStencilStateCreateInfo::default();
let fragment_shader_lib = create_library(
&self.device,
vk::GraphicsPipelineLibraryFlagsEXT::FRAGMENT_SHADER,
|desc| {
desc.layout(self.layout)
.stages(std::slice::from_ref(&shader_stage))
.depth_stencil_state(&depth_stencil_state)
},
)?;
self.fragment_shader_lib = fragment_shader_lib;
Ok(())
}
pub fn link(&mut self) -> Result<()> {
unsafe { self.device.destroy_pipeline(self.pipeline, None) };
self.pipeline = Self::link_libraries(
&self.device,
&self.layout,
&self.vertex_input_lib,
&self.vertex_shader_lib,
&self.fragment_shader_lib,
&self.fragment_output_lib,
)?;
Ok(())
}
fn link_libraries(
device: &ash::Device,
layout: &vk::PipelineLayout,
vertex_input_lib: &vk::Pipeline,
vertex_shader_lib: &vk::Pipeline,
fragment_shader_lib: &vk::Pipeline,
fragment_output_lib: &vk::Pipeline,
) -> Result<vk::Pipeline> {
let libraries = [
*vertex_input_lib,
*vertex_shader_lib,
*fragment_shader_lib,
*fragment_output_lib,
];
let pipeline = {
let mut linking_info =
vk::PipelineLibraryCreateInfoKHR::default().libraries(&libraries);
let pipeline_info = vk::GraphicsPipelineCreateInfo::default()
.flags(vk::PipelineCreateFlags::LINK_TIME_OPTIMIZATION_EXT)
.layout(*layout)
.push_next(&mut linking_info);
let pipeline = unsafe {
device.create_graphics_pipelines(vk::PipelineCache::null(), &[pipeline_info], None)
};
pipeline.map_err(|(_, err)| err)?[0]
};
Ok(pipeline)
}
}
impl Drop for RenderPipeline {
fn drop(&mut self) {
unsafe {
self.device.destroy_pipeline(self.vertex_input_lib, None);
self.device.destroy_pipeline(self.vertex_shader_lib, None);
self.device.destroy_pipeline(self.fragment_shader_lib, None);
self.device.destroy_pipeline(self.fragment_output_lib, None);
self.device.destroy_pipeline(self.pipeline, None);
self.device.destroy_pipeline_layout(self.layout, None);
}
}
}
fn create_library<'a, F>(
device: &ash::Device,
kind: vk::GraphicsPipelineLibraryFlagsEXT,
f: F,
) -> VkResult<vk::Pipeline>
where
F: FnOnce(vk::GraphicsPipelineCreateInfo<'a>) -> vk::GraphicsPipelineCreateInfo<'a>,
{
let mut library_type = vk::GraphicsPipelineLibraryCreateInfoEXT::default().flags(kind);
let pipeline = unsafe {
let pipeline_info = vk::GraphicsPipelineCreateInfo::default().flags(
vk::PipelineCreateFlags::LIBRARY_KHR
| vk::PipelineCreateFlags::RETAIN_LINK_TIME_OPTIMIZATION_INFO_EXT,
);
// WARN: `let` introduces implicit copy on the struct that contains pointers
let pipeline_info = f(pipeline_info).push_next(&mut library_type);
device.create_graphics_pipelines(
vk::PipelineCache::null(),
std::slice::from_ref(&pipeline_info),
None,
)
};
Ok(pipeline.map_err(|(_, err)| err)?[0])
}
slotmap::new_key_type! {
pub struct RenderHandle;
pub struct ComputeHandle;
}
pub struct PipelineArena {
pub render: RenderArena,
pub compute: ComputeArena,
pub path_mapping: AHashMap<PathBuf, AHashSet<Either<RenderHandle, ComputeHandle>>>,
pub shader_compiler: ShaderCompiler,
file_watcher: Watcher,
device: Arc<Device>,
}
impl PipelineArena {
pub fn new(device: &Arc<Device>, file_watcher: Watcher) -> Result<Self> {
Ok(Self {
render: RenderArena {
pipelines: SlotMap::with_key(),
},
compute: ComputeArena {
pipelines: SlotMap::with_key(),
},
shader_compiler: ShaderCompiler::new(&file_watcher)?,
file_watcher,
path_mapping: AHashMap::new(),
device: device.clone(),
})
}
pub fn create_compute_pipeline(
&mut self,
shader_path: impl AsRef<Path>,
push_constant_ranges: &[vk::PushConstantRange],
descriptor_set_layouts: &[vk::DescriptorSetLayout],
) -> Result<ComputeHandle> {
let path = shader_path.as_ref().canonicalize()?;
{
self.file_watcher.watch_file(&path)?;
let mut mapping = self.file_watcher.include_mapping.lock();
mapping
.entry(path.clone())
.or_default()
.insert(ShaderSource {
path: path.clone(),
kind: ShaderKind::Compute,
});
}
let pipeline = ComputePipeline::new(
&self.device,
&self.shader_compiler,
&path,
push_constant_ranges,
descriptor_set_layouts,
)?;
let handle = self.compute.pipelines.insert(pipeline);
self.path_mapping
.entry(path)
.or_default()
.insert(Either::Right(handle));
Ok(handle)
}
pub fn create_render_pipeline(
&mut self,
vertex_input_desc: &VertexInputDesc,
vertex_shader_desc: &VertexShaderDesc,
fragment_shader_desc: &FragmentShaderDesc,
fragment_output_desc: &FragmentOutputDesc,
push_constant_ranges: &[vk::PushConstantRange],
descriptor_set_layouts: &[vk::DescriptorSetLayout],
) -> Result<RenderHandle> {
let vs_path = vertex_shader_desc.shader_path.canonicalize()?;
let fs_path = fragment_shader_desc.shader_path.canonicalize()?;
for (path, kind) in [
(vs_path.clone(), ShaderKind::Vertex),
(fs_path.clone(), ShaderKind::Fragment),
] {
self.file_watcher.watch_file(&path)?;
let mut mapping = self.file_watcher.include_mapping.lock();
mapping
.entry(path.clone())
.or_default()
.insert(ShaderSource { path, kind });
}
let pipeline = RenderPipeline::new(
&self.device,
&self.shader_compiler,
vertex_input_desc,
vertex_shader_desc,
fragment_shader_desc,
fragment_output_desc,
push_constant_ranges,
descriptor_set_layouts,
)?;
let handle = self.render.pipelines.insert(pipeline);
self.path_mapping
.entry(vs_path)
.or_default()
.insert(Either::Left(handle));
self.path_mapping
.entry(fs_path)
.or_default()
.insert(Either::Left(handle));
Ok(handle)
}
pub fn get_pipeline<H: Handle>(&self, handle: H) -> &H::Pipeline {
handle.get_pipeline(self)
}
pub fn get_pipeline_mut<H: Handle>(&mut self, handle: H) -> &mut H::Pipeline {
handle.get_pipeline_mut(self)
}
}
pub struct RenderArena {
pub pipelines: SlotMap<RenderHandle, RenderPipeline>,
}
pub struct ComputeArena {
pub pipelines: SlotMap<ComputeHandle, ComputePipeline>,
}
pub trait Handle {
type Pipeline;
fn get_pipeline(self, arena: &PipelineArena) -> &Self::Pipeline;
fn get_pipeline_mut(self, arena: &mut PipelineArena) -> &mut Self::Pipeline;
}
impl Handle for RenderHandle {
type Pipeline = RenderPipeline;
fn get_pipeline(self, arena: &PipelineArena) -> &Self::Pipeline {
&arena.render.pipelines[self]
}
fn get_pipeline_mut(self, arena: &mut PipelineArena) -> &mut Self::Pipeline {
&mut arena.render.pipelines[self]
}
}
impl Handle for ComputeHandle {
type Pipeline = ComputePipeline;
fn get_pipeline(self, arena: &PipelineArena) -> &Self::Pipeline {
&arena.compute.pipelines[self]
}
fn get_pipeline_mut(self, arena: &mut PipelineArena) -> &mut Self::Pipeline {
&mut arena.compute.pipelines[self]
}
}
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/lib.rs | src/lib.rs | #![allow(clippy::new_without_default)]
#![allow(clippy::too_many_arguments)]
pub mod default_shaders;
mod device;
mod input;
mod instance;
mod pipeline_arena;
mod recorder;
mod shader_compiler;
mod surface;
mod swapchain;
mod texture_arena;
mod watcher;
use std::{
fs::File,
io,
mem::ManuallyDrop,
ops::{Add, BitAnd, Not, Sub},
path::Path,
sync::Arc,
time::Duration,
};
pub use self::{
device::{Device, HostBufferTyped},
input::Input,
instance::Instance,
pipeline_arena::*,
recorder::{RecordEvent, Recorder},
shader_compiler::ShaderCompiler,
surface::Surface,
swapchain::Swapchain,
texture_arena::*,
watcher::Watcher,
};
use anyhow::{bail, Context};
use ash::vk::{self, DeviceMemory};
use gpu_alloc::{GpuAllocator, MapError, MemoryBlock};
use gpu_alloc_ash::AshMemoryDevice;
use parking_lot::Mutex;
pub const SHADER_DUMP_FOLDER: &str = "shader_dump";
pub const SHADER_FOLDER: &str = "shaders";
pub const VIDEO_FOLDER: &str = "recordings";
pub const SCREENSHOT_FOLDER: &str = "screenshots";
pub const COLOR_SUBRESOURCE_MASK: vk::ImageSubresourceRange = vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: vk::REMAINING_MIP_LEVELS,
base_array_layer: 0,
layer_count: vk::REMAINING_ARRAY_LAYERS,
};
pub fn align_to<T>(value: T, alignment: T) -> T
where
T: Add<Output = T> + Copy + One + Not<Output = T> + BitAnd<Output = T> + Sub<Output = T>,
{
(value + alignment - T::one()) & !(alignment - T::one())
}
pub trait One {
fn one() -> Self;
}
macro_rules! impl_one {
( $($t:ty),+) => {
$(impl One for $t { fn one() -> $t { 1 } })*
}
}
impl_one!(i32, u32, i64, u64, usize);
pub fn dispatch_optimal(len: u32, subgroup_size: u32) -> u32 {
let padded_size = (subgroup_size - len % subgroup_size) % subgroup_size;
(len + padded_size) / subgroup_size
}
pub fn create_folder<P: AsRef<Path>>(name: P) -> io::Result<()> {
match std::fs::create_dir(name) {
Ok(_) => {}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(e),
}
Ok(())
}
pub fn print_help() {
println!();
println!("- `F1`: Print help");
println!("- `F2`: Toggle play/pause");
println!("- `F3`: Pause and step back one frame");
println!("- `F4`: Pause and step forward one frame");
println!("- `F5`: Restart playback at frame 0 (`Time` and `Pos` = 0)");
println!("- `F6`: Print parameters");
println!("- `F10`: Save shaders");
println!("- `F11`: Take Screenshot");
println!("- `F12`: Start/Stop record video");
println!("- `ESC`: Exit the application");
println!("- `Arrows`: Change `Pos`\n");
}
#[derive(Debug)]
pub struct Args {
pub inner_size: Option<(u32, u32)>,
pub record_time: Option<Duration>,
}
pub fn parse_args() -> anyhow::Result<Args> {
let mut inner_size = None;
let mut record_time = None;
let args = std::env::args().skip(1).step_by(2);
for (flag, value) in args.zip(std::env::args().skip(2).step_by(2)) {
match flag.trim() {
"--record" => {
let time = match value.split_once('.') {
Some((sec, ms)) => {
let seconds = sec.parse()?;
let millis: u32 = ms.parse()?;
Duration::new(seconds, millis * 1_000_000)
}
None => Duration::from_secs(value.parse()?),
};
record_time = Some(time)
}
"--size" => {
let (w, h) = value
.split_once('x')
.context("Failed to parse window size: Missing 'x' delimiter")?;
inner_size = Some((w.parse()?, h.parse()?));
}
_ => {}
}
}
Ok(Args {
record_time,
inner_size,
})
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct PushConstant {
pub pos: [f32; 3],
pub time: f32,
pub wh: [f32; 2],
pub mouse: [f32; 2],
pub mouse_pressed: u32,
pub frame: u32,
pub time_delta: f32,
pub record_time: f32,
}
impl Default for PushConstant {
fn default() -> Self {
Self {
pos: [0.; 3],
time: 0.,
wh: [1920.0, 1020.],
mouse: [0.; 2],
mouse_pressed: false as _,
frame: 0,
time_delta: 1. / 60.,
record_time: 10.,
}
}
}
impl std::fmt::Display for PushConstant {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let time = Duration::from_secs_f32(self.time);
let time_delta = Duration::from_secs_f32(self.time_delta);
write!(
f,
"position:\t{:?}\n\
time:\t\t{:#.2?}\n\
time delta:\t{:#.3?}, fps: {:#.2?}\n\
width, height:\t{:?}\nmouse:\t\t{:.2?}\n\
frame:\t\t{}\nrecord_period:\t{}\n",
self.pos,
time,
time_delta,
1. / self.time_delta,
self.wh,
self.mouse,
self.frame,
self.record_time
)
}
}
pub fn save_shaders<P: AsRef<Path>>(path: P) -> anyhow::Result<()> {
let dump_folder = Path::new(SHADER_DUMP_FOLDER);
create_folder(dump_folder)?;
let dump_folder =
dump_folder.join(chrono::Local::now().format("%Y-%m-%d_%H-%M-%S").to_string());
create_folder(&dump_folder)?;
let dump_folder = dump_folder.join(SHADER_FOLDER);
create_folder(&dump_folder)?;
if !path.as_ref().is_dir() {
bail!("Folder wasn't supplied");
}
let shaders = path.as_ref().read_dir()?;
for shader in shaders {
let shader = shader?.path();
let to = dump_folder.join(shader.file_name().and_then(|s| s.to_str()).unwrap());
if !to.exists() {
std::fs::create_dir_all(&to.parent().unwrap().canonicalize()?)?;
File::create(&to)?;
}
std::fs::copy(shader, &to)?;
println!("Saved: {}", &to.display());
}
Ok(())
}
#[derive(Debug)]
pub enum UserEvent {
Glsl { path: std::path::PathBuf },
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct ShaderSource {
pub path: std::path::PathBuf,
pub kind: ShaderKind,
}
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub enum ShaderKind {
Fragment,
Vertex,
Compute,
}
impl From<ShaderKind> for shaderc::ShaderKind {
fn from(value: ShaderKind) -> Self {
match value {
ShaderKind::Compute => shaderc::ShaderKind::Compute,
ShaderKind::Vertex => shaderc::ShaderKind::Vertex,
ShaderKind::Fragment => shaderc::ShaderKind::Fragment,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct ImageDimensions {
pub width: usize,
pub height: usize,
pub padded_bytes_per_row: usize,
pub unpadded_bytes_per_row: usize,
}
impl ImageDimensions {
pub fn new(width: usize, height: usize, alignment: u64) -> Self {
let channel_width = std::mem::size_of::<[u8; 4]>();
let unpadded_bytes_per_row = width * channel_width;
let padded_bytes_per_row = align_to(unpadded_bytes_per_row, alignment as usize);
Self {
width,
height,
unpadded_bytes_per_row,
padded_bytes_per_row,
}
}
}
pub struct ManagedImage {
pub image: vk::Image,
pub memory: ManuallyDrop<MemoryBlock<DeviceMemory>>,
pub image_dimensions: ImageDimensions,
pub data: Option<&'static mut [u8]>,
pub format: vk::Format,
device: Arc<Device>,
allocator: Arc<Mutex<GpuAllocator<DeviceMemory>>>,
}
impl ManagedImage {
pub fn new(
device: &Arc<Device>,
info: &vk::ImageCreateInfo,
usage: gpu_alloc::UsageFlags,
) -> anyhow::Result<Self> {
let image = unsafe { device.create_image(info, None)? };
let memory_reqs = unsafe { device.get_image_memory_requirements(image) };
let memory = device.alloc_memory(memory_reqs, usage)?;
unsafe { device.bind_image_memory(image, *memory.memory(), memory.offset()) }?;
let image_dimensions = ImageDimensions::new(
info.extent.width as _,
info.extent.height as _,
memory_reqs.alignment,
);
Ok(Self {
image,
memory: ManuallyDrop::new(memory),
image_dimensions,
format: info.format,
data: None,
device: device.clone(),
allocator: device.allocator.clone(),
})
}
pub fn map_memory(&mut self) -> Result<&mut [u8], MapError> {
if self.data.is_some() {
return Err(MapError::AlreadyMapped);
}
let size = self.memory.size() as usize;
let offset = self.memory.offset();
let ptr = unsafe {
self.memory
.map(AshMemoryDevice::wrap(&self.device), offset, size)?
};
let data = unsafe { std::slice::from_raw_parts_mut(ptr.as_ptr().cast(), size) };
self.data = Some(data);
Ok(self.data.as_mut().unwrap())
}
}
impl Drop for ManagedImage {
fn drop(&mut self) {
unsafe {
self.device.destroy_image(self.image, None);
{
let mut allocator = self.allocator.lock();
let memory = ManuallyDrop::take(&mut self.memory);
allocator.dealloc(AshMemoryDevice::wrap(&self.device), memory);
}
}
}
}
pub fn find_memory_type_index(
memory_prop: &vk::PhysicalDeviceMemoryProperties,
memory_type_bits: u32,
flags: vk::MemoryPropertyFlags,
) -> Option<u32> {
memory_prop.memory_types[..memory_prop.memory_type_count as _]
.iter()
.enumerate()
.find(|(index, memory_type)| {
(1 << index) & memory_type_bits != 0 && (memory_type.property_flags & flags) == flags
})
.map(|(index, _memory_type)| index as _)
}
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/device.rs | src/device.rs | use anyhow::Result;
use gpu_alloc::{GpuAllocator, MemoryBlock, Request, UsageFlags};
use gpu_alloc_ash::AshMemoryDevice;
use parking_lot::Mutex;
use std::{
ffi::{CStr, CString},
mem::ManuallyDrop,
sync::Arc,
};
use ash::{
ext, khr,
prelude::VkResult,
vk::{self, DeviceMemory, Handle},
};
use crate::{align_to, ManagedImage, COLOR_SUBRESOURCE_MASK};
pub struct Device {
pub physical_device: vk::PhysicalDevice,
pub memory_properties: vk::PhysicalDeviceMemoryProperties,
pub device_properties: vk::PhysicalDeviceProperties,
pub descriptor_indexing_props: vk::PhysicalDeviceDescriptorIndexingProperties<'static>,
pub command_pool: vk::CommandPool,
pub main_queue_family_idx: u32,
pub transfer_queue_family_idx: u32,
pub allocator: Arc<Mutex<GpuAllocator<DeviceMemory>>>,
pub device: ash::Device,
pub dynamic_rendering: khr::dynamic_rendering::Device,
pub(crate) dbg_utils: ext::debug_utils::Device,
}
impl std::ops::Deref for Device {
type Target = ash::Device;
fn deref(&self) -> &Self::Target {
&self.device
}
}
impl Device {
pub fn name_object(&self, handle: impl Handle, name: &str) {
let name = CString::new(name).unwrap();
let _ = unsafe {
self.dbg_utils.set_debug_utils_object_name(
&vk::DebugUtilsObjectNameInfoEXT::default()
.object_handle(handle)
.object_name(&name),
)
};
}
pub fn create_2d_view(&self, image: &vk::Image, format: vk::Format) -> VkResult<vk::ImageView> {
let view = unsafe {
self.create_image_view(
&vk::ImageViewCreateInfo::default()
.view_type(vk::ImageViewType::TYPE_2D)
.image(*image)
.format(format)
.subresource_range(
vk::ImageSubresourceRange::default()
.aspect_mask(vk::ImageAspectFlags::COLOR)
.base_mip_level(0)
.level_count(1)
.base_array_layer(0)
.layer_count(1),
),
None,
)?
};
Ok(view)
}
pub fn one_time_submit(
&self,
queue: &vk::Queue,
callbk: impl FnOnce(&Self, vk::CommandBuffer),
) -> VkResult<()> {
let fence = unsafe { self.create_fence(&vk::FenceCreateInfo::default(), None)? };
let command_buffer = unsafe {
self.allocate_command_buffers(
&vk::CommandBufferAllocateInfo::default()
.command_pool(self.command_pool)
.command_buffer_count(1)
.level(vk::CommandBufferLevel::PRIMARY),
)?[0]
};
unsafe {
self.begin_command_buffer(
command_buffer,
&vk::CommandBufferBeginInfo::default()
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT),
)?;
callbk(self, command_buffer);
self.end_command_buffer(command_buffer)?;
let submit_info =
vk::SubmitInfo::default().command_buffers(std::slice::from_ref(&command_buffer));
self.queue_submit(*queue, &[submit_info], fence)?;
self.wait_for_fences(&[fence], true, u64::MAX)?;
self.destroy_fence(fence, None);
self.free_command_buffers(self.command_pool, &[command_buffer]);
}
Ok(())
}
pub fn alloc_memory(
&self,
memory_reqs: vk::MemoryRequirements,
usage: UsageFlags,
) -> Result<gpu_alloc::MemoryBlock<DeviceMemory>, gpu_alloc::AllocationError> {
let mut allocator = self.allocator.lock();
let memory_block = unsafe {
allocator.alloc(
AshMemoryDevice::wrap(self),
Request {
size: memory_reqs.size,
align_mask: memory_reqs.alignment - 1,
usage: usage | UsageFlags::DEVICE_ADDRESS,
memory_types: memory_reqs.memory_type_bits,
},
)
};
memory_block
}
pub fn dealloc_memory(&self, block: MemoryBlock<DeviceMemory>) {
let mut allocator = self.allocator.lock();
unsafe { allocator.dealloc(AshMemoryDevice::wrap(self), block) };
}
pub fn blit_image(
&self,
command_buffer: &vk::CommandBuffer,
src_image: &vk::Image,
src_extent: vk::Extent2D,
src_orig_layout: vk::ImageLayout,
dst_image: &vk::Image,
dst_extent: vk::Extent2D,
dst_orig_layout: vk::ImageLayout,
) {
let src_barrier = vk::ImageMemoryBarrier2::default()
.subresource_range(COLOR_SUBRESOURCE_MASK)
.image(*src_image)
.src_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS)
.dst_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS)
.dst_access_mask(vk::AccessFlags2::MEMORY_READ)
.old_layout(src_orig_layout)
.new_layout(vk::ImageLayout::TRANSFER_SRC_OPTIMAL);
let dst_barrier = vk::ImageMemoryBarrier2::default()
.subresource_range(COLOR_SUBRESOURCE_MASK)
.image(*dst_image)
.src_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS)
.dst_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS)
.dst_access_mask(vk::AccessFlags2::MEMORY_WRITE)
.old_layout(dst_orig_layout)
.new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL);
let image_memory_barriers = &[src_barrier, dst_barrier];
let dependency_info =
vk::DependencyInfo::default().image_memory_barriers(image_memory_barriers);
unsafe { self.cmd_pipeline_barrier2(*command_buffer, &dependency_info) };
let src_offsets = [
vk::Offset3D { x: 0, y: 0, z: 0 },
vk::Offset3D {
x: src_extent.width as _,
y: src_extent.height as _,
z: 1,
},
];
let dst_offsets = [
vk::Offset3D { x: 0, y: 0, z: 0 },
vk::Offset3D {
x: dst_extent.width as _,
y: dst_extent.height as _,
z: 1,
},
];
let subresource_layer = vk::ImageSubresourceLayers {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_array_layer: 0,
layer_count: 1,
mip_level: 0,
};
let regions = [vk::ImageBlit2::default()
.src_offsets(src_offsets)
.dst_offsets(dst_offsets)
.src_subresource(subresource_layer)
.dst_subresource(subresource_layer)];
let blit_info = vk::BlitImageInfo2::default()
.src_image(*src_image)
.src_image_layout(vk::ImageLayout::TRANSFER_SRC_OPTIMAL)
.dst_image(*dst_image)
.dst_image_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
.regions(®ions)
.filter(vk::Filter::NEAREST);
unsafe { self.cmd_blit_image2(*command_buffer, &blit_info) };
let src_barrier = src_barrier
.src_access_mask(vk::AccessFlags2::MEMORY_READ)
.old_layout(vk::ImageLayout::TRANSFER_SRC_OPTIMAL)
.new_layout(src_orig_layout);
let dst_barrier = dst_barrier
.src_access_mask(vk::AccessFlags2::MEMORY_WRITE)
.old_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
.new_layout(match dst_orig_layout {
vk::ImageLayout::UNDEFINED => vk::ImageLayout::GENERAL,
_ => dst_orig_layout,
});
let image_memory_barriers = &[src_barrier, dst_barrier];
let dependency_info =
vk::DependencyInfo::default().image_memory_barriers(image_memory_barriers);
unsafe { self.cmd_pipeline_barrier2(*command_buffer, &dependency_info) };
}
pub fn capture_image_data(
self: &Arc<Self>,
queue: &vk::Queue,
src_image: &vk::Image,
extent: vk::Extent2D,
callback: impl FnOnce(ManagedImage),
) -> Result<()> {
let dst_image = ManagedImage::new(
self,
&vk::ImageCreateInfo::default()
.extent(vk::Extent3D {
width: align_to(extent.width, 2),
height: align_to(extent.height, 2),
depth: 1,
})
.image_type(vk::ImageType::TYPE_2D)
.format(vk::Format::R8G8B8A8_SRGB)
.usage(vk::ImageUsageFlags::TRANSFER_DST)
.samples(vk::SampleCountFlags::TYPE_1)
.mip_levels(1)
.array_layers(1)
.tiling(vk::ImageTiling::LINEAR),
UsageFlags::DOWNLOAD,
)?;
self.one_time_submit(queue, |device, command_buffer| {
device.blit_image(
&command_buffer,
src_image,
extent,
vk::ImageLayout::PRESENT_SRC_KHR,
&dst_image.image,
extent,
vk::ImageLayout::UNDEFINED,
);
})?;
callback(dst_image);
Ok(())
}
pub fn create_host_buffer(
self: &Arc<Self>,
size: u64,
usage: vk::BufferUsageFlags,
memory_usage: gpu_alloc::UsageFlags,
) -> Result<HostBuffer> {
let buffer = unsafe {
self.create_buffer(
&vk::BufferCreateInfo::default()
.size(size)
.usage(usage | vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS),
None,
)?
};
let mem_requirements = unsafe { self.get_buffer_memory_requirements(buffer) };
let mut memory =
self.alloc_memory(mem_requirements, memory_usage | UsageFlags::HOST_ACCESS)?;
unsafe { self.bind_buffer_memory(buffer, *memory.memory(), memory.offset()) }?;
let address = unsafe {
self.get_buffer_device_address(&vk::BufferDeviceAddressInfo::default().buffer(buffer))
};
let ptr = unsafe {
memory.map(
AshMemoryDevice::wrap(self),
memory.offset(),
memory.size() as usize,
)?
};
let data = unsafe { std::slice::from_raw_parts_mut(ptr.as_ptr(), size as _) };
Ok(HostBuffer {
address,
size,
buffer,
memory: ManuallyDrop::new(memory),
data,
device: self.clone(),
})
}
pub fn create_host_buffer_typed<T>(
self: Arc<Self>,
usage: vk::BufferUsageFlags,
memory_usage: gpu_alloc::UsageFlags,
) -> Result<HostBufferTyped<T>> {
let byte_size = (size_of::<T>()) as vk::DeviceSize;
let buffer = unsafe {
self.device.create_buffer(
&vk::BufferCreateInfo::default()
.size(byte_size)
.usage(usage | vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS),
None,
)?
};
let mem_requirements = unsafe { self.get_buffer_memory_requirements(buffer) };
let mut memory =
self.alloc_memory(mem_requirements, memory_usage | UsageFlags::HOST_ACCESS)?;
unsafe { self.bind_buffer_memory(buffer, *memory.memory(), memory.offset()) }?;
let address = unsafe {
self.get_buffer_device_address(&vk::BufferDeviceAddressInfo::default().buffer(buffer))
};
self.name_object(
buffer,
&format!("HostBuffer<{}>", pretty_type_name::pretty_type_name::<T>()),
);
let ptr = unsafe {
memory.map(
AshMemoryDevice::wrap(&self.device),
memory.offset(),
memory.size() as usize,
)?
};
let data = unsafe { &mut *ptr.as_ptr().cast::<T>() };
Ok(HostBufferTyped {
address,
buffer,
memory: ManuallyDrop::new(memory),
data,
device: self.clone(),
})
}
pub fn get_info(&self) -> RendererInfo {
RendererInfo {
device_name: self.get_device_name().unwrap().to_string(),
device_type: self.get_device_type().to_string(),
vendor_name: self.get_vendor_name().to_string(),
}
}
pub fn get_device_name(&self) -> Result<&str, std::str::Utf8Error> {
unsafe { CStr::from_ptr(self.device_properties.device_name.as_ptr()) }.to_str()
}
pub fn get_device_type(&self) -> &str {
match self.device_properties.device_type {
vk::PhysicalDeviceType::CPU => "CPU",
vk::PhysicalDeviceType::INTEGRATED_GPU => "INTEGRATED_GPU",
vk::PhysicalDeviceType::DISCRETE_GPU => "DISCRETE_GPU",
vk::PhysicalDeviceType::VIRTUAL_GPU => "VIRTUAL_GPU",
_ => "OTHER",
}
}
pub fn get_vendor_name(&self) -> &str {
match self.device_properties.vendor_id {
0x1002 => "AMD",
0x1010 => "ImgTec",
0x10DE => "NVIDIA Corporation",
0x13B5 => "ARM",
0x5143 => "Qualcomm",
0x8086 => "INTEL Corporation",
_ => "Unknown vendor",
}
}
}
impl Drop for Device {
fn drop(&mut self) {
unsafe {
self.device.destroy_command_pool(self.command_pool, None);
{
let mut allocator = self.allocator.lock();
allocator.cleanup(AshMemoryDevice::wrap(&self.device));
}
self.device.destroy_device(None);
}
}
}
pub struct HostBuffer {
pub address: u64,
pub size: u64,
pub buffer: vk::Buffer,
pub memory: ManuallyDrop<MemoryBlock<DeviceMemory>>,
pub data: &'static mut [u8],
device: Arc<Device>,
}
impl std::ops::Deref for HostBuffer {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.data
}
}
impl std::ops::DerefMut for HostBuffer {
fn deref_mut(&mut self) -> &mut Self::Target {
self.data
}
}
impl Drop for HostBuffer {
fn drop(&mut self) {
unsafe {
self.device.destroy_buffer(self.buffer, None);
let memory = ManuallyDrop::take(&mut self.memory);
self.device.dealloc_memory(memory);
}
}
}
pub struct HostBufferTyped<T: 'static> {
pub address: u64,
pub buffer: vk::Buffer,
pub memory: ManuallyDrop<MemoryBlock<DeviceMemory>>,
pub data: &'static mut T,
device: Arc<Device>,
}
impl<T> std::ops::Deref for HostBufferTyped<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.data
}
}
impl<T> std::ops::DerefMut for HostBufferTyped<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.data
}
}
impl<T> Drop for HostBufferTyped<T> {
fn drop(&mut self) {
unsafe {
self.device.destroy_buffer(self.buffer, None);
let memory = ManuallyDrop::take(&mut self.memory);
self.device.dealloc_memory(memory);
}
}
}
#[derive(Debug)]
pub struct RendererInfo {
pub device_name: String,
pub device_type: String,
pub vendor_name: String,
}
impl std::fmt::Display for RendererInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "Vendor name: {}", self.vendor_name)?;
writeln!(f, "Device name: {}", self.device_name)?;
writeln!(f, "Device type: {}", self.device_type)?;
Ok(())
}
}
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/shader_compiler.rs | src/shader_compiler.rs | use std::path::Path;
use crate::{Watcher, SHADER_FOLDER};
use anyhow::{Context, Result};
use shaderc::{CompilationArtifact, IncludeType, ShaderKind};
pub struct ShaderCompiler {
compiler: shaderc::Compiler,
options: shaderc::CompileOptions<'static>,
}
impl ShaderCompiler {
pub fn new(watcher: &Watcher) -> Result<Self> {
let mut options =
shaderc::CompileOptions::new().context("Failed to create shader compiler options")?;
options.set_target_env(
shaderc::TargetEnv::Vulkan,
shaderc::EnvVersion::Vulkan1_3 as u32,
);
options.set_optimization_level(shaderc::OptimizationLevel::Performance);
options.set_target_spirv(shaderc::SpirvVersion::V1_6);
options.set_generate_debug_info();
let watcher_copy = watcher.clone();
options.set_include_callback(move |name, include_type, source_file, _depth| {
let path = match include_type {
IncludeType::Relative => Path::new(source_file).parent().unwrap().join(name),
IncludeType::Standard => Path::new(SHADER_FOLDER).join(name),
};
// TODO: recreate dependencies in case someone removes includes
match std::fs::read_to_string(&path) {
Ok(glsl_code) => {
let include_path = path.canonicalize().unwrap();
{
let mut watcher = watcher_copy.watcher.lock();
let _ = watcher
.watcher()
.watch(&include_path, notify::RecursiveMode::NonRecursive);
}
let source_path = Path::new(SHADER_FOLDER)
.join(source_file)
.canonicalize()
.unwrap();
{
let mut mapping = watcher_copy.include_mapping.lock();
let sources: Vec<_> = mapping[&source_path].iter().cloned().collect();
for source in sources {
mapping
.entry(include_path.clone())
.or_default()
.insert(source);
}
}
Ok(shaderc::ResolvedInclude {
resolved_name: String::from(name),
content: glsl_code,
})
}
Err(err) => Err(format!(
"Failed to resolve include to {} in {} (was looking for {:?}): {}",
name, source_file, path, err
)),
}
});
Ok(Self {
compiler: shaderc::Compiler::new().unwrap(),
options,
})
}
pub fn compile(&self, path: impl AsRef<Path>, kind: ShaderKind) -> Result<CompilationArtifact> {
let source = std::fs::read_to_string(path.as_ref())?;
Ok(self.compiler.compile_into_spirv(
&source,
kind,
path.as_ref().file_name().and_then(|s| s.to_str()).unwrap(),
"main",
Some(&self.options),
)?)
}
}
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/surface.rs | src/surface.rs | use std::ops::Deref;
use anyhow::Result;
use ash::{khr, vk};
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use crate::device::Device;
pub struct Surface {
loader: khr::surface::Instance,
inner: vk::SurfaceKHR,
}
impl Deref for Surface {
type Target = vk::SurfaceKHR;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
#[derive(Debug, Clone)]
pub struct SurfaceInfo {
pub capabilities: vk::SurfaceCapabilitiesKHR,
pub formats: Vec<vk::SurfaceFormatKHR>,
pub present_modes: Vec<vk::PresentModeKHR>,
}
impl Surface {
pub fn new(
entry: &ash::Entry,
instance: &ash::Instance,
handle: &(impl HasDisplayHandle + HasWindowHandle),
) -> Result<Self> {
let inner = unsafe {
ash_window::create_surface(
entry,
instance,
handle.display_handle()?.as_raw(),
handle.window_handle()?.as_raw(),
None,
)?
};
let loader = khr::surface::Instance::new(entry, instance);
Ok(Surface { inner, loader })
}
pub fn get_device_capabilities(&self, device: &Device) -> vk::SurfaceCapabilitiesKHR {
unsafe {
self.loader
.get_physical_device_surface_capabilities(device.physical_device, self.inner)
.unwrap()
}
}
pub fn get_device_surface_support(
&self,
physical_device: vk::PhysicalDevice,
queue_family_index: u32,
) -> bool {
unsafe {
self.loader
.get_physical_device_surface_support(
physical_device,
queue_family_index,
self.inner,
)
.unwrap()
}
}
pub fn info(&self, device: &Device) -> SurfaceInfo {
let physical_device = device.physical_device;
let formats = unsafe {
self.loader
.get_physical_device_surface_formats(physical_device, self.inner)
.unwrap()
};
let capabilities = unsafe {
self.loader
.get_physical_device_surface_capabilities(physical_device, self.inner)
.unwrap()
};
let present_modes = unsafe {
self.loader
.get_physical_device_surface_present_modes(physical_device, self.inner)
.unwrap()
};
SurfaceInfo {
capabilities,
formats,
present_modes,
}
}
}
impl Drop for Surface {
fn drop(&mut self) {
unsafe { self.loader.destroy_surface(self.inner, None) };
}
}
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/watcher.rs | src/watcher.rs | use ahash::{AHashMap, AHashSet};
use anyhow::Result;
use notify_debouncer_mini::{DebounceEventResult, DebouncedEventKind};
use winit::event_loop::EventLoopProxy;
use std::{
ffi::OsStr,
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
use crate::{ShaderSource, UserEvent};
use parking_lot::Mutex;
#[derive(Clone)]
pub struct Watcher {
pub watcher: Arc<Mutex<notify_debouncer_mini::Debouncer<notify::RecommendedWatcher>>>,
pub include_mapping: Arc<Mutex<AHashMap<PathBuf, AHashSet<ShaderSource>>>>,
}
impl Watcher {
pub fn new(proxy: EventLoopProxy<UserEvent>) -> Result<Self> {
let watcher = notify_debouncer_mini::new_debouncer(
Duration::from_millis(350),
watch_callback(proxy),
)?;
Ok(Self {
watcher: Arc::new(Mutex::new(watcher)),
include_mapping: Arc::new(Mutex::new(AHashMap::new())),
})
}
pub fn unwatch_file(&mut self, path: impl AsRef<Path>) -> Result<()> {
let mut watcher = self.watcher.lock();
watcher.watcher().unwatch(path.as_ref())?;
Ok(())
}
pub fn watch_file(&mut self, path: impl AsRef<Path>) -> Result<()> {
let mut watcher = self.watcher.lock();
watcher
.watcher()
.watch(path.as_ref(), notify::RecursiveMode::NonRecursive)?;
Ok(())
}
}
fn watch_callback(proxy: EventLoopProxy<UserEvent>) -> impl FnMut(DebounceEventResult) {
move |event| match event {
Ok(events) => {
if let Some(path) = events
.into_iter()
.filter(|e| e.kind == DebouncedEventKind::Any)
.map(|event| event.path)
.next()
{
if path.extension() == Some(OsStr::new("glsl"))
|| path.extension() == Some(OsStr::new("frag"))
|| path.extension() == Some(OsStr::new("vert"))
|| path.extension() == Some(OsStr::new("comp"))
{
let _ = proxy
.send_event(UserEvent::Glsl {
path: path.canonicalize().unwrap(),
})
.map_err(|err| log::error!("Event Loop has been dropped: {err}"));
}
}
}
Err(errors) => log::error!("File watcher error: {errors}"),
}
}
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/recorder.rs | src/recorder.rs | use anyhow::{Context, Result};
use std::{
fs::File,
io::{BufWriter, Write},
path::Path,
process::{Child, Command, Stdio},
thread::JoinHandle,
time::Instant,
};
use crate::{create_folder, ImageDimensions, ManagedImage, SCREENSHOT_FOLDER, VIDEO_FOLDER};
use crossbeam_channel::{Receiver, Sender};
pub enum RecordEvent {
Start(ImageDimensions),
Record(ManagedImage),
Finish,
Screenshot(ManagedImage),
CloseThread,
}
pub struct Recorder {
pub sender: Sender<RecordEvent>,
ffmpeg_installed: bool,
pub ffmpeg_version: String,
pub thread_handle: Option<JoinHandle<()>>,
is_active: bool,
}
impl Recorder {
pub fn new() -> Self {
let mut command = Command::new("ffmpeg");
command.arg("-version");
let (version, installed) = match command.output() {
Ok(output) => (
String::from_utf8(output.stdout)
.unwrap()
.lines()
.next()
.unwrap()
.to_string(),
true,
),
Err(e) => (e.to_string(), false),
};
let (tx, rx) = crossbeam_channel::unbounded();
let thread_handle = std::thread::spawn(move || record_thread(rx));
Self {
sender: tx,
ffmpeg_installed: installed,
ffmpeg_version: version,
thread_handle: Some(thread_handle),
is_active: false,
}
}
pub fn is_active(&self) -> bool {
self.is_active
}
pub fn ffmpeg_installed(&self) -> bool {
self.ffmpeg_installed
}
pub fn screenshot(&self, image: ManagedImage) {
let _ = self
.sender
.send(RecordEvent::Screenshot(image))
.context("Failed to send screenshot");
}
pub fn start(&mut self, dims: ImageDimensions) {
self.is_active = true;
self.send(RecordEvent::Start(dims));
}
pub fn record(&self, image: ManagedImage) {
self.send(RecordEvent::Record(image));
}
pub fn finish(&mut self) {
self.is_active = false;
self.send(RecordEvent::Finish);
}
pub fn close_thread(&self) {
self.sender.send(RecordEvent::CloseThread).unwrap();
}
pub fn send(&self, event: RecordEvent) {
if !(self.ffmpeg_installed || matches!(event, RecordEvent::Screenshot(_))) {
return;
}
self.sender.send(event).unwrap()
}
}
struct RecorderThread {
process: Child,
}
fn new_ffmpeg_command(image_dimensions: ImageDimensions, filename: &str) -> Result<RecorderThread> {
#[rustfmt::skip]
let args = [
"-framerate", "60",
"-pix_fmt", "rgba",
"-f", "rawvideo",
// "-vcodec", "rawvideo",
"-i", "pipe:",
"-c:v", "libx264",
"-crf", "23",
// "-preset", "ultrafast",
// "-tune", "animation",
// "-color_primaries", "bt709",
// "-color_trc", "bt709",
// "-colorspace", "bt709",
"-color_range", "tv",
"-chroma_sample_location", "center",
// "-pix_fmt", "yuv420p",
"-movflags", "+faststart",
"-vf", "scale=sws_flags=lanczos:in_color_matrix=bt709,format=yuv444p",
// "-y",
];
let mut command = Command::new("ffmpeg");
command
.arg("-video_size")
.arg(format!(
"{}x{}",
image_dimensions.width, image_dimensions.height
))
.args(args)
.arg(filename)
.stdin(Stdio::piped())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
let child = command.spawn()?;
Ok(RecorderThread { process: child })
}
fn record_thread(rx: Receiver<RecordEvent>) {
let mut recorder = None;
while let Ok(event) = rx.recv() {
match event {
RecordEvent::Start(image_dimensions) => {
create_folder(VIDEO_FOLDER).unwrap();
let dir_path = Path::new(VIDEO_FOLDER);
let filename = dir_path.join(format!(
"record-{}.mp4",
chrono::Local::now().format("%Y-%m-%d_%H-%M-%S")
));
recorder =
Some(new_ffmpeg_command(image_dimensions, filename.to_str().unwrap()).unwrap());
}
RecordEvent::Record(mut frame) => {
if let Some(ref mut recorder) = recorder {
let writer = recorder.process.stdin.as_mut().unwrap();
let mut writer = BufWriter::new(writer);
let padded_bytes = frame.image_dimensions.padded_bytes_per_row as _;
let unpadded_bytes = frame.image_dimensions.unpadded_bytes_per_row as _;
let data = match frame.map_memory() {
Ok(data) => data,
Err(err) => {
log::error!("Failed to map memory: {err}");
continue;
}
};
for chunk in data
.chunks(padded_bytes)
.map(|chunk| &chunk[..unpadded_bytes])
{
let _ = writer.write_all(chunk);
}
let _ = writer.flush();
}
}
RecordEvent::Finish => {
if let Some(ref mut p) = recorder {
p.process.wait().unwrap();
}
recorder = None;
println!("Recording finished");
}
RecordEvent::Screenshot(mut frame) => {
let image_dimensions = frame.image_dimensions;
let data = match frame.map_memory() {
Ok(data) => data,
Err(err) => {
log::error!("Failed to map memory: {err}");
continue;
}
};
let _ = save_screenshot(data, image_dimensions).map_err(|err| log::error!("{err}"));
}
RecordEvent::CloseThread => {
return;
}
}
}
}
pub fn save_screenshot(frame: &[u8], image_dimensions: ImageDimensions) -> Result<()> {
let now = Instant::now();
let screenshots_folder = Path::new(SCREENSHOT_FOLDER);
create_folder(screenshots_folder)?;
let path = screenshots_folder.join(format!(
"screenshot-{}.png",
chrono::Local::now().format("%Y-%m-%d_%H-%M-%S%.9f")
));
let file = File::create(path)?;
let w = BufWriter::new(file);
let mut encoder =
png::Encoder::new(w, image_dimensions.width as _, image_dimensions.height as _);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let padded_bytes = image_dimensions.padded_bytes_per_row;
let unpadded_bytes = image_dimensions.unpadded_bytes_per_row;
let mut writer = encoder
.write_header()?
.into_stream_writer_with_size(unpadded_bytes)?;
writer.set_filter(png::FilterType::Paeth);
writer.set_adaptive_filter(png::AdaptiveFilterType::Adaptive);
for chunk in frame
.chunks(padded_bytes)
.map(|chunk| &chunk[..unpadded_bytes])
{
writer.write_all(chunk)?;
}
writer.finish()?;
println!("Encode image: {:#.2?}", now.elapsed());
Ok(())
}
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/main.rs | src/main.rs | use core::panic;
use std::{
io::Write,
path::{Path, PathBuf},
sync::Arc,
time::{Duration, Instant},
};
use anyhow::{bail, Result};
use ash::{khr, vk};
use either::Either;
use pilka::{
align_to, default_shaders, dispatch_optimal, parse_args, print_help, save_shaders, Args,
ComputeHandle, Device, FragmentOutputDesc, FragmentShaderDesc, Input, Instance, PipelineArena,
PushConstant, Recorder, RenderHandle, ShaderKind, ShaderSource, Surface, Swapchain,
TextureArena, UserEvent, VertexInputDesc, VertexShaderDesc, Watcher, COLOR_SUBRESOURCE_MASK,
PREV_FRAME_IMAGE_IDX, SCREENSIZED_IMAGE_INDICES, SHADER_FOLDER,
};
use winit::{
application::ApplicationHandler,
dpi::{LogicalSize, PhysicalPosition, PhysicalSize},
event::{ElementState, KeyEvent, MouseButton, StartCause, WindowEvent},
event_loop::EventLoopProxy,
keyboard::{Key, NamedKey},
window::{Window, WindowAttributes},
};
pub const UPDATES_PER_SECOND: u32 = 60;
pub const FIXED_TIME_STEP: f64 = 1. / UPDATES_PER_SECOND as f64;
pub const MAX_FRAME_TIME: f64 = 15. * FIXED_TIME_STEP; // 0.25;
#[allow(dead_code)]
struct AppInit {
window: Window,
input: Input,
pause: bool,
timeline: Instant,
backup_time: Duration,
frame_instant: Instant,
frame_accumulated_time: f64,
texture_arena: TextureArena,
file_watcher: Watcher,
recorder: Recorder,
video_recording: bool,
record_time: Option<Duration>,
push_constant: PushConstant,
render_pipeline: RenderHandle,
compute_pipeline: ComputeHandle,
pipeline_arena: PipelineArena,
queue: vk::Queue,
transfer_queue: vk::Queue,
swapchain: Swapchain,
surface: Surface,
device: Arc<Device>,
instance: Instance,
}
impl AppInit {
fn new(
event_loop: &winit::event_loop::ActiveEventLoop,
proxy: EventLoopProxy<UserEvent>,
window_attributes: WindowAttributes,
record_time: Option<Duration>,
) -> Result<Self> {
let window = event_loop.create_window(window_attributes)?;
let watcher = Watcher::new(proxy)?;
let mut recorder = Recorder::new();
let instance = Instance::new(Some(&window))?;
let surface = instance.create_surface(&window)?;
let (device, queue, transfer_queue) = instance.create_device_and_queues(&surface)?;
let device = Arc::new(device);
let swapchain_loader = khr::swapchain::Device::new(&instance, &device);
let swapchain = Swapchain::new(&device, &surface, swapchain_loader)?;
let mut pipeline_arena = PipelineArena::new(&device, watcher.clone())?;
let extent = swapchain.extent();
let video_recording = record_time.is_some();
let push_constant = PushConstant {
wh: [extent.width as f32, extent.height as f32],
record_time: record_time.map(|t| t.as_secs_f32()).unwrap_or(10.),
..Default::default()
};
let texture_arena = TextureArena::new(&device, &queue, swapchain.extent())?;
let vertex_shader_desc = VertexShaderDesc {
shader_path: "shaders/shader.vert".into(),
..Default::default()
};
let fragment_shader_desc = FragmentShaderDesc {
shader_path: "shaders/shader.frag".into(),
};
let fragment_output_desc = FragmentOutputDesc {
surface_format: swapchain.format(),
..Default::default()
};
let push_constant_range = vk::PushConstantRange::default()
.size(size_of::<PushConstant>() as _)
.stage_flags(
vk::ShaderStageFlags::VERTEX
| vk::ShaderStageFlags::FRAGMENT
| vk::ShaderStageFlags::COMPUTE,
);
let render_pipeline = pipeline_arena.create_render_pipeline(
&VertexInputDesc::default(),
&vertex_shader_desc,
&fragment_shader_desc,
&fragment_output_desc,
&[push_constant_range],
&[texture_arena.images_set_layout],
)?;
let compute_pipeline = pipeline_arena.create_compute_pipeline(
"shaders/shader.comp",
&[push_constant_range],
&[texture_arena.images_set_layout],
)?;
if record_time.is_some() {
let mut image_dimensions = swapchain.image_dimensions;
image_dimensions.width = align_to(image_dimensions.width, 2);
image_dimensions.height = align_to(image_dimensions.height, 2);
recorder.start(image_dimensions);
}
Ok(Self {
window,
input: Input::default(),
pause: false,
timeline: Instant::now(),
backup_time: Duration::from_secs(0),
frame_instant: Instant::now(),
frame_accumulated_time: 0.,
texture_arena,
file_watcher: watcher,
video_recording,
record_time,
recorder,
push_constant,
render_pipeline,
compute_pipeline,
pipeline_arena,
queue,
transfer_queue,
surface,
swapchain,
device,
instance,
})
}
fn update(&mut self) {
self.input.process_position(&mut self.push_constant);
}
fn reload_shaders(&mut self, path: PathBuf) -> Result<()> {
if let Some(frame) = self.swapchain.get_current_frame() {
let fences = std::slice::from_ref(&frame.present_finished);
unsafe { self.device.wait_for_fences(fences, true, u64::MAX)? };
}
let resolved = {
let mapping = self.file_watcher.include_mapping.lock();
mapping[&path].clone()
};
for ShaderSource { path, kind } in resolved {
let handles = &self.pipeline_arena.path_mapping[&path];
for handle in handles {
let compiler = &self.pipeline_arena.shader_compiler;
match handle {
Either::Left(handle) => {
let pipeline = &mut self.pipeline_arena.render.pipelines[*handle];
match kind {
ShaderKind::Vertex => pipeline.reload_vertex_lib(compiler, &path),
ShaderKind::Fragment => pipeline.reload_fragment_lib(compiler, &path),
ShaderKind::Compute => {
bail!("Supplied compute shader into the render pipeline!")
}
}?;
pipeline.link()?;
}
Either::Right(handle) => {
let pipeline = &mut self.pipeline_arena.compute.pipelines[*handle];
pipeline.reload(compiler)?;
}
}
}
}
Ok(())
}
fn recreate_swapchain(&mut self) -> Result<()> {
if let Some(frame) = self.swapchain.get_current_frame() {
let fences = std::slice::from_ref(&frame.present_finished);
unsafe { self.device.wait_for_fences(fences, true, u64::MAX)? };
}
self.swapchain
.recreate(&self.device, &self.surface)
.expect("Failed to recreate swapchain");
let extent = self.swapchain.extent();
self.push_constant.wh = [extent.width as f32, extent.height as f32];
for i in SCREENSIZED_IMAGE_INDICES {
self.texture_arena.image_infos[i].extent = vk::Extent3D {
width: extent.width,
height: extent.height,
depth: 1,
};
}
self.texture_arena
.update_images(&SCREENSIZED_IMAGE_INDICES)?;
Ok(())
}
}
impl ApplicationHandler<UserEvent> for AppInit {
fn new_events(
&mut self,
event_loop: &winit::event_loop::ActiveEventLoop,
cause: winit::event::StartCause,
) {
self.push_constant.time = if !self.pause {
self.timeline.elapsed().as_secs_f32()
} else {
self.backup_time.as_secs_f32()
};
if let StartCause::WaitCancelled { .. } = cause {
let new_instant = Instant::now();
let frame_time = new_instant
.duration_since(self.frame_instant)
.as_secs_f64()
.min(MAX_FRAME_TIME);
self.frame_instant = new_instant;
self.push_constant.time_delta = frame_time as _;
self.frame_accumulated_time += frame_time;
while self.frame_accumulated_time >= FIXED_TIME_STEP {
self.update();
self.frame_accumulated_time -= FIXED_TIME_STEP;
}
}
if let Some(limit) = self.record_time {
if self.timeline.elapsed() >= limit && self.recorder.is_active() {
self.recorder.finish();
event_loop.exit();
}
}
}
fn device_event(
&mut self,
_event_loop: &winit::event_loop::ActiveEventLoop,
_device_id: winit::event::DeviceId,
event: winit::event::DeviceEvent,
) {
if let winit::event::DeviceEvent::Key(key_event) = event {
self.input.update_device_input(key_event);
}
}
fn window_event(
&mut self,
event_loop: &winit::event_loop::ActiveEventLoop,
_window_id: winit::window::WindowId,
event: WindowEvent,
) {
match event {
WindowEvent::CloseRequested
| WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key: Key::Named(NamedKey::Escape),
state: ElementState::Pressed,
..
},
..
} => event_loop.exit(),
WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key: Key::Named(key),
state: ElementState::Pressed,
repeat: false,
..
},
..
} => {
let dt = Duration::from_secs_f32(1. / 60.);
match key {
NamedKey::F1 => print_help(),
NamedKey::F2 => {
if !self.pause {
self.backup_time = self.timeline.elapsed();
} else {
self.timeline = Instant::now() - self.backup_time;
}
self.pause = !self.pause;
}
NamedKey::F3 => {
if !self.pause {
self.backup_time = self.timeline.elapsed();
self.pause = true;
}
self.backup_time = self.backup_time.saturating_sub(dt);
}
NamedKey::F4 => {
if !self.pause {
self.backup_time = self.timeline.elapsed();
self.pause = true;
}
self.backup_time += dt;
}
NamedKey::F5 => {
self.push_constant.pos = [0.; 3];
self.push_constant.time = 0.;
self.push_constant.frame = 0;
self.timeline = Instant::now();
self.backup_time = self.timeline.elapsed();
}
NamedKey::F6 => {
println!("{}", self.push_constant);
}
NamedKey::F10 => {
let _ = save_shaders(SHADER_FOLDER).map_err(|err| log::error!("{err}"));
}
NamedKey::F11 => {
let _ = self
.device
.capture_image_data(
&self.queue,
self.swapchain.get_current_image(),
self.swapchain.extent(),
|tex| self.recorder.screenshot(tex),
)
.map_err(|err| log::error!("{err}"));
}
NamedKey::F12 => {
if !self.video_recording {
let mut image_dimensions = self.swapchain.image_dimensions;
image_dimensions.width = align_to(image_dimensions.width, 2);
image_dimensions.height = align_to(image_dimensions.height, 2);
self.recorder.start(image_dimensions);
} else {
self.recorder.finish();
}
self.video_recording = !self.video_recording;
}
_ => {}
}
}
WindowEvent::KeyboardInput { event, .. } => {
self.input.update_window_input(&event);
}
WindowEvent::MouseInput {
state,
button: MouseButton::Left,
..
} => {
self.push_constant.mouse_pressed = (ElementState::Pressed == state) as u32;
}
WindowEvent::CursorMoved {
position: PhysicalPosition { x, y },
..
} => {
if !self.pause {
let PhysicalSize { width, height } = self.window.inner_size();
let x = (x as f32 / width as f32 - 0.5) * 2.;
let y = -(y as f32 / height as f32 - 0.5) * 2.;
self.push_constant.mouse = [x, y];
}
}
WindowEvent::RedrawRequested => {
let mut frame = match self.swapchain.acquire_next_image() {
Ok(frame) => frame,
Err(vk::Result::ERROR_OUT_OF_DATE_KHR) => {
let _ = self.recreate_swapchain().map_err(|err| log::warn!("{err}"));
self.window.request_redraw();
return;
}
Err(e) => panic!("error: {e}\n"),
};
let stages = vk::ShaderStageFlags::VERTEX
| vk::ShaderStageFlags::FRAGMENT
| vk::ShaderStageFlags::COMPUTE;
let pipeline = self.pipeline_arena.get_pipeline(self.compute_pipeline);
frame.push_constant(pipeline.layout, stages, &[self.push_constant]);
frame.bind_descriptor_sets(
vk::PipelineBindPoint::COMPUTE,
pipeline.layout,
&[self.texture_arena.images_set],
);
frame.bind_pipeline(vk::PipelineBindPoint::COMPUTE, &pipeline.pipeline);
const SUBGROUP_SIZE: u32 = 16;
let extent = self.swapchain.extent();
frame.dispatch(
dispatch_optimal(extent.width, SUBGROUP_SIZE),
dispatch_optimal(extent.height, SUBGROUP_SIZE),
1,
);
unsafe {
let image_barrier = vk::ImageMemoryBarrier2::default()
.subresource_range(COLOR_SUBRESOURCE_MASK)
.src_stage_mask(vk::PipelineStageFlags2::COMPUTE_SHADER)
.dst_stage_mask(vk::PipelineStageFlags2::ALL_GRAPHICS)
.image(self.texture_arena.images[PREV_FRAME_IMAGE_IDX].image);
self.device.cmd_pipeline_barrier2(
*frame.command_buffer(),
&vk::DependencyInfo::default()
.image_memory_barriers(std::slice::from_ref(&image_barrier)),
)
};
frame.begin_rendering(
self.swapchain.get_current_image_view(),
[0., 0.025, 0.025, 1.0],
);
let pipeline = self.pipeline_arena.get_pipeline(self.render_pipeline);
frame.push_constant(pipeline.layout, stages, &[self.push_constant]);
frame.bind_descriptor_sets(
vk::PipelineBindPoint::GRAPHICS,
pipeline.layout,
&[self.texture_arena.images_set],
);
frame.bind_pipeline(vk::PipelineBindPoint::GRAPHICS, &pipeline.pipeline);
frame.draw(3, 0, 1, 0);
frame.end_rendering();
self.device.blit_image(
frame.command_buffer(),
self.swapchain.get_current_image(),
self.swapchain.extent(),
vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL,
&self.texture_arena.images[PREV_FRAME_IMAGE_IDX].image,
self.swapchain.extent(),
vk::ImageLayout::UNDEFINED,
);
match self.swapchain.submit_image(&self.queue, frame) {
Ok(_) => {}
Err(vk::Result::ERROR_OUT_OF_DATE_KHR) => {
let _ = self.recreate_swapchain().map_err(|err| log::warn!("{err}"));
}
Err(e) => panic!("error: {e}\n"),
}
self.window.request_redraw();
if self.video_recording && self.recorder.ffmpeg_installed() {
let res = self.device.capture_image_data(
&self.queue,
self.swapchain.get_current_image(),
self.swapchain.extent(),
|tex| self.recorder.record(tex),
);
if let Err(err) = res {
log::error!("{err}");
self.video_recording = false;
}
}
self.push_constant.frame = self.push_constant.frame.saturating_add(1);
}
_ => {}
}
}
fn user_event(&mut self, _event_loop: &winit::event_loop::ActiveEventLoop, event: UserEvent) {
match event {
UserEvent::Glsl { path } => {
match self.reload_shaders(path) {
Err(err) => eprintln!("{err}"),
Ok(()) => {
const ESC: &str = "\x1B[";
const RESET: &str = "\x1B[0m";
eprint!("\r{}42m{}K{}\r", ESC, ESC, RESET);
std::io::stdout().flush().unwrap();
std::thread::spawn(|| {
std::thread::sleep(std::time::Duration::from_millis(50));
eprint!("\r{}40m{}K{}\r", ESC, ESC, RESET);
std::io::stdout().flush().unwrap();
});
}
};
}
}
}
fn exiting(&mut self, _event_loop: &winit::event_loop::ActiveEventLoop) {
self.recorder.close_thread();
if let Some(handle) = self.recorder.thread_handle.take() {
let _ = handle.join();
}
let _ = unsafe { self.device.device_wait_idle() };
println!("// End from the loop. Bye bye~⏎ ");
}
fn resumed(&mut self, _event_loop: &winit::event_loop::ActiveEventLoop) {
panic!("On native platforms `resumed` can be called only once.")
}
}
fn main() -> Result<()> {
env_logger::init();
let event_loop = winit::event_loop::EventLoop::with_user_event().build()?;
let Args {
record_time,
inner_size,
} = parse_args()?;
let shader_dir = PathBuf::new().join(SHADER_FOLDER);
if !shader_dir.is_dir() {
default_shaders::create_default_shaders(&shader_dir)?;
}
let mut app = App::new(event_loop.create_proxy(), record_time, inner_size);
event_loop.run_app(&mut app)?;
Ok(())
}
struct App {
proxy: EventLoopProxy<UserEvent>,
record_time: Option<Duration>,
initial_window_size: Option<(u32, u32)>,
inner: AppEnum,
}
impl App {
fn new(
proxy: EventLoopProxy<UserEvent>,
record_time: Option<Duration>,
inner_size: Option<(u32, u32)>,
) -> Self {
Self {
proxy,
record_time,
initial_window_size: inner_size,
inner: AppEnum::Uninitialized,
}
}
}
#[derive(Default)]
enum AppEnum {
#[default]
Uninitialized,
Init(AppInit),
}
impl ApplicationHandler<UserEvent> for App {
fn resumed(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
let mut window_attributes = WindowAttributes::default().with_title("myndgera");
if let Some(size) = self.initial_window_size {
window_attributes = window_attributes
.with_resizable(false)
.with_inner_size(LogicalSize::<u32>::from(size));
}
match self.inner {
AppEnum::Uninitialized => {
let app = AppInit::new(
event_loop,
self.proxy.clone(),
window_attributes,
self.record_time,
)
.expect("Failed to create application");
println!("{}", app.device.get_info());
println!("{}", app.recorder.ffmpeg_version);
println!(
"Default shader path:\n\t{}",
Path::new(SHADER_FOLDER).canonicalize().unwrap().display()
);
print_help();
println!("// Set up our new world⏎ ");
println!("// And let's begin the⏎ ");
println!("\tSIMULATION⏎ \n");
self.inner = AppEnum::Init(app);
}
AppEnum::Init(_) => {}
}
}
fn window_event(
&mut self,
event_loop: &winit::event_loop::ActiveEventLoop,
window_id: winit::window::WindowId,
event: WindowEvent,
) {
if let AppEnum::Init(app) = &mut self.inner {
app.window_event(event_loop, window_id, event);
}
}
fn new_events(
&mut self,
event_loop: &winit::event_loop::ActiveEventLoop,
cause: winit::event::StartCause,
) {
if let AppEnum::Init(app) = &mut self.inner {
app.new_events(event_loop, cause);
}
}
fn user_event(&mut self, event_loop: &winit::event_loop::ActiveEventLoop, event: UserEvent) {
if let AppEnum::Init(app) = &mut self.inner {
app.user_event(event_loop, event)
}
}
fn device_event(
&mut self,
event_loop: &winit::event_loop::ActiveEventLoop,
device_id: winit::event::DeviceId,
event: winit::event::DeviceEvent,
) {
if let AppEnum::Init(app) = &mut self.inner {
app.device_event(event_loop, device_id, event)
}
}
fn about_to_wait(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
if let AppEnum::Init(app) = &mut self.inner {
app.about_to_wait(event_loop)
}
}
fn suspended(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
if let AppEnum::Init(app) = &mut self.inner {
app.suspended(event_loop)
}
}
fn exiting(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
if let AppEnum::Init(app) = &mut self.inner {
app.exiting(event_loop)
}
}
fn memory_warning(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
if let AppEnum::Init(app) = &mut self.inner {
app.memory_warning(event_loop)
}
}
}
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/texture_arena.rs | src/texture_arena.rs | use std::{mem::ManuallyDrop, sync::Arc};
use anyhow::Result;
use ash::{
prelude::VkResult,
vk::{self, DeviceMemory},
};
use gpu_alloc::{MemoryBlock, UsageFlags};
use crate::{Device, ImageDimensions, COLOR_SUBRESOURCE_MASK};
pub const LINEAR_SAMPLER_IDX: usize = 0;
pub const NEAREST_SAMPLER_IDX: usize = 1;
pub const PREV_FRAME_IMAGE_IDX: usize = 0;
pub const GENERIC_IMAGE1_IDX: usize = 1;
pub const GENERIC_IMAGE2_IDX: usize = 2;
pub const DITHER_IMAGE_IDX: usize = 3;
pub const NOISE_IMAGE_IDX: usize = 4;
pub const BLUE_IMAGE_IDX: usize = 5;
pub const SCREENSIZED_IMAGE_INDICES: [usize; 3] =
[PREV_FRAME_IMAGE_IDX, GENERIC_IMAGE1_IDX, GENERIC_IMAGE2_IDX];
pub struct Image {
pub image: vk::Image,
pub memory: ManuallyDrop<MemoryBlock<DeviceMemory>>,
pub image_dimensions: ImageDimensions,
}
impl Image {
pub fn new(
device: &Device,
info: &vk::ImageCreateInfo,
usage: gpu_alloc::UsageFlags,
) -> Result<Self> {
let image = unsafe { device.create_image(info, None)? };
let memory_reqs = unsafe { device.get_image_memory_requirements(image) };
let memory = device.alloc_memory(memory_reqs, usage)?;
unsafe { device.bind_image_memory(image, *memory.memory(), memory.offset()) }?;
let image_dimensions = ImageDimensions::new(
info.extent.width as _,
info.extent.height as _,
memory_reqs.alignment,
);
Ok(Self {
image,
memory: ManuallyDrop::new(memory),
image_dimensions,
})
}
fn desctroy(&mut self, device: &Device) {
unsafe {
let memory = ManuallyDrop::take(&mut self.memory);
device.dealloc_memory(memory);
device.destroy_image(self.image, None)
}
}
}
const IMAGES_COUNT: u32 = 2048;
const SAMPLER_COUNT: u32 = 8;
pub struct TextureArena {
pub images: Vec<Image>,
pub image_infos: Vec<vk::ImageCreateInfo<'static>>,
pub views: Vec<vk::ImageView>,
pub samplers: [vk::Sampler; SAMPLER_COUNT as usize],
descriptor_pool: vk::DescriptorPool,
pub images_set: vk::DescriptorSet,
pub images_set_layout: vk::DescriptorSetLayout,
device: Arc<Device>,
}
impl TextureArena {
pub fn image_count(&self) -> usize {
self.images.len()
}
pub fn new(device: &Arc<Device>, queue: &vk::Queue, extent: vk::Extent2D) -> Result<Self> {
let pool_sizes = [
vk::DescriptorPoolSize::default()
.ty(vk::DescriptorType::SAMPLED_IMAGE)
.descriptor_count(IMAGES_COUNT),
vk::DescriptorPoolSize::default()
.ty(vk::DescriptorType::SAMPLER)
.descriptor_count(SAMPLER_COUNT),
];
let descriptor_pool = unsafe {
device.create_descriptor_pool(
&vk::DescriptorPoolCreateInfo::default()
.flags(
vk::DescriptorPoolCreateFlags::UPDATE_AFTER_BIND
| vk::DescriptorPoolCreateFlags::FREE_DESCRIPTOR_SET,
)
.pool_sizes(&pool_sizes)
.max_sets(1),
None,
)?
};
let binding_flags = vk::DescriptorBindingFlags::PARTIALLY_BOUND
| vk::DescriptorBindingFlags::UPDATE_AFTER_BIND
| vk::DescriptorBindingFlags::UPDATE_UNUSED_WHILE_PENDING;
let binding_flags = [
binding_flags,
binding_flags | vk::DescriptorBindingFlags::VARIABLE_DESCRIPTOR_COUNT,
];
let mut binding_flags =
vk::DescriptorSetLayoutBindingFlagsCreateInfo::default().binding_flags(&binding_flags);
let sampler_set_layout_binding = vk::DescriptorSetLayoutBinding::default()
.binding(0)
.descriptor_type(vk::DescriptorType::SAMPLER)
.stage_flags(vk::ShaderStageFlags::ALL_GRAPHICS | vk::ShaderStageFlags::COMPUTE)
.descriptor_count(
device
.descriptor_indexing_props
.max_descriptor_set_update_after_bind_samplers,
);
let image_set_layout_binding = vk::DescriptorSetLayoutBinding::default()
.binding(1)
.descriptor_type(vk::DescriptorType::SAMPLED_IMAGE)
.stage_flags(vk::ShaderStageFlags::ALL_GRAPHICS | vk::ShaderStageFlags::COMPUTE)
.descriptor_count(
device
.descriptor_indexing_props
.max_descriptor_set_update_after_bind_sampled_images,
);
let bindings = [sampler_set_layout_binding, image_set_layout_binding];
let images_set_layout = unsafe {
device.create_descriptor_set_layout(
&vk::DescriptorSetLayoutCreateInfo::default()
.bindings(&bindings)
.flags(vk::DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND_POOL)
.push_next(&mut binding_flags),
None,
)?
};
let mut variable_info = vk::DescriptorSetVariableDescriptorCountAllocateInfo::default()
.descriptor_counts(&[IMAGES_COUNT]);
let allocate_info = vk::DescriptorSetAllocateInfo::default()
.descriptor_pool(descriptor_pool)
.set_layouts(std::slice::from_ref(&images_set_layout))
.push_next(&mut variable_info);
let images_set = unsafe { device.allocate_descriptor_sets(&allocate_info)? }[0];
let image_infos: [_; 3] = std::array::from_fn(|_| {
vk::ImageCreateInfo::default()
.extent(vk::Extent3D {
width: extent.width,
height: extent.height,
depth: 1,
})
.image_type(vk::ImageType::TYPE_2D)
.format(vk::Format::R8G8B8A8_SRGB)
.usage(vk::ImageUsageFlags::SAMPLED | vk::ImageUsageFlags::TRANSFER_DST)
.samples(vk::SampleCountFlags::TYPE_1)
.mip_levels(1)
.array_layers(1)
.tiling(vk::ImageTiling::OPTIMAL)
});
let images = image_infos
.iter()
.map(|info| Image::new(device, info, gpu_alloc::UsageFlags::FAST_DEVICE_ACCESS))
.collect::<Result<Vec<_>>>()?;
let views = images
.iter()
.zip(image_infos)
.map(|(image, info)| device.create_2d_view(&image.image, info.format))
.collect::<VkResult<Vec<_>>>()?;
for (i, view) in views.iter().enumerate() {
let image_info = vk::DescriptorImageInfo::default()
.image_view(*view)
.image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL);
let write = vk::WriteDescriptorSet::default()
.dst_set(images_set)
.descriptor_type(vk::DescriptorType::SAMPLED_IMAGE)
.dst_binding(1)
.image_info(std::slice::from_ref(&image_info))
.dst_array_element(i as _);
unsafe { device.update_descriptor_sets(&[write], &[]) };
}
let mut samplers = [vk::Sampler::null(); SAMPLER_COUNT as usize];
let mut sampler_create_info = vk::SamplerCreateInfo::default()
.min_filter(vk::Filter::LINEAR)
.mag_filter(vk::Filter::LINEAR)
.mipmap_mode(vk::SamplerMipmapMode::NEAREST)
.address_mode_u(vk::SamplerAddressMode::MIRRORED_REPEAT)
.address_mode_v(vk::SamplerAddressMode::MIRRORED_REPEAT)
.address_mode_w(vk::SamplerAddressMode::MIRRORED_REPEAT)
.max_lod(vk::LOD_CLAMP_NONE);
let sampler = unsafe { device.create_sampler(&sampler_create_info, None)? };
let descriptor_image_info = vk::DescriptorImageInfo::default().sampler(sampler);
let mut desc_write = vk::WriteDescriptorSet::default()
.descriptor_type(vk::DescriptorType::SAMPLER)
.dst_set(images_set)
.dst_binding(0)
.image_info(std::slice::from_ref(&descriptor_image_info))
.dst_array_element(0);
unsafe { device.update_descriptor_sets(&[desc_write], &[]) };
samplers[0] = sampler;
sampler_create_info = sampler_create_info
.mag_filter(vk::Filter::NEAREST)
.min_filter(vk::Filter::NEAREST);
let sampler = unsafe { device.create_sampler(&sampler_create_info, None)? };
let descriptor_image_info = vk::DescriptorImageInfo::default().sampler(sampler);
desc_write = desc_write.image_info(std::slice::from_ref(&descriptor_image_info));
unsafe { device.update_descriptor_sets(&[desc_write], &[]) };
samplers[1] = sampler;
let mut texture_arena = Self {
images,
image_infos: image_infos.to_vec(),
views,
samplers,
descriptor_pool,
images_set,
images_set_layout,
device: device.clone(),
};
texture_arena.device.name_object(
texture_arena.images[PREV_FRAME_IMAGE_IDX].image,
"Previous Frame Image",
);
texture_arena.device.name_object(
texture_arena.views[PREV_FRAME_IMAGE_IDX],
"Previous Frame Image View",
);
let bytes = include_bytes!("../assets/dither.dds");
let dds = ddsfile::Dds::read(&bytes[..])?;
let mut extent = vk::Extent3D {
width: dds.get_width(),
height: dds.get_height(),
depth: 1,
};
let mut info = vk::ImageCreateInfo::default()
.extent(extent)
.image_type(vk::ImageType::TYPE_2D)
.format(vk::Format::R8G8B8A8_UNORM)
.usage(vk::ImageUsageFlags::SAMPLED | vk::ImageUsageFlags::TRANSFER_DST)
.samples(vk::SampleCountFlags::TYPE_1)
.mip_levels(1)
.array_layers(1)
.tiling(vk::ImageTiling::OPTIMAL);
texture_arena.push_image(device, queue, info, dds.get_data(0)?)?;
texture_arena
.device
.name_object(texture_arena.images[DITHER_IMAGE_IDX].image, "Dither Image");
texture_arena
.device
.name_object(texture_arena.views[DITHER_IMAGE_IDX], "Dither Image View");
let bytes = include_bytes!("../assets/noise.dds");
let dds = ddsfile::Dds::read(&bytes[..])?;
extent.width = dds.get_width();
extent.height = dds.get_height();
info.extent = extent;
texture_arena.push_image(device, queue, info, dds.get_data(0)?)?;
texture_arena
.device
.name_object(texture_arena.images[NOISE_IMAGE_IDX].image, "Noise Image");
texture_arena
.device
.name_object(texture_arena.views[NOISE_IMAGE_IDX], "Noise Image View");
let bytes = include_bytes!("../assets/BLUE_RGBA_0.dds");
let dds = ddsfile::Dds::read(&bytes[..])?;
extent.width = dds.get_width();
extent.height = dds.get_height();
info.extent = extent;
texture_arena.push_image(device, queue, info, dds.get_data(0)?)?;
texture_arena.device.name_object(
texture_arena.images[BLUE_IMAGE_IDX].image,
"Blue Noise Image",
);
texture_arena
.device
.name_object(texture_arena.views[BLUE_IMAGE_IDX], "Blue Noise Image View");
Ok(texture_arena)
}
pub fn push_image(
&mut self,
device: &Arc<Device>,
queue: &vk::Queue,
info: vk::ImageCreateInfo,
data: &[u8],
) -> Result<u32> {
let image = { Image::new(device, &info, UsageFlags::FAST_DEVICE_ACCESS)? };
let mut staging = device.create_host_buffer(
image.memory.size(),
vk::BufferUsageFlags::TRANSFER_SRC,
UsageFlags::UPLOAD,
)?;
staging[..data.len()].copy_from_slice(data);
device.one_time_submit(queue, |device, cbuff| unsafe {
let mut image_barrier = vk::ImageMemoryBarrier2::default()
.subresource_range(COLOR_SUBRESOURCE_MASK)
.old_layout(vk::ImageLayout::UNDEFINED)
.new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
.image(image.image);
let dependency_info = vk::DependencyInfo::default()
.image_memory_barriers(std::slice::from_ref(&image_barrier));
device.cmd_pipeline_barrier2(cbuff, &dependency_info);
let regions = vk::BufferImageCopy::default()
.image_extent(info.extent)
.image_subresource(vk::ImageSubresourceLayers {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_array_layer: 0,
layer_count: 1,
mip_level: 0,
});
device.cmd_copy_buffer_to_image(
cbuff,
staging.buffer,
image.image,
vk::ImageLayout::TRANSFER_DST_OPTIMAL,
&[regions],
);
image_barrier.old_layout = vk::ImageLayout::TRANSFER_DST_OPTIMAL;
image_barrier.new_layout = vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL;
let dependency_info = vk::DependencyInfo::default()
.image_memory_barriers(std::slice::from_ref(&image_barrier));
device.cmd_pipeline_barrier2(cbuff, &dependency_info);
})?;
let view = self.device.create_2d_view(&image.image, info.format)?;
let idx = self.images.len() as u32;
let image_info = vk::DescriptorImageInfo::default()
.image_view(view)
.image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL);
let write = vk::WriteDescriptorSet::default()
.dst_set(self.images_set)
.descriptor_type(vk::DescriptorType::SAMPLED_IMAGE)
.dst_binding(1)
.image_info(std::slice::from_ref(&image_info))
.dst_array_element(idx);
unsafe { device.update_descriptor_sets(&[write], &[]) };
self.images.push(image);
self.views.push(view);
Ok(idx)
}
pub fn update_images(&mut self, indices: &[usize]) -> Result<()> {
for (i, info) in indices.iter().map(|&i| (i, &self.image_infos[i])) {
let image = Image::new(
&self.device,
info,
gpu_alloc::UsageFlags::FAST_DEVICE_ACCESS,
)?;
let view = self.device.create_2d_view(&image.image, info.format)?;
let image_info = vk::DescriptorImageInfo::default()
.image_view(view)
.image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL);
let write = vk::WriteDescriptorSet::default()
.dst_set(self.images_set)
.descriptor_type(vk::DescriptorType::SAMPLED_IMAGE)
.dst_binding(1)
.image_info(std::slice::from_ref(&image_info))
.dst_array_element(i as _);
unsafe { self.device.update_descriptor_sets(&[write], &[]) };
self.images[i].desctroy(&self.device);
unsafe { self.device.destroy_image_view(self.views[i], None) };
self.images[i] = image;
self.views[i] = view;
}
Ok(())
}
}
impl Drop for TextureArena {
fn drop(&mut self) {
unsafe {
self.images.iter_mut().for_each(|image| {
image.desctroy(&self.device);
});
self.views
.iter()
.for_each(|&view| self.device.destroy_image_view(view, None));
self.samplers
.iter()
.for_each(|&sampler| self.device.destroy_sampler(sampler, None));
let _ = self
.device
.free_descriptor_sets(self.descriptor_pool, &[self.images_set]);
self.device
.destroy_descriptor_set_layout(self.images_set_layout, None);
self.device
.destroy_descriptor_pool(self.descriptor_pool, None);
}
}
}
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/input.rs | src/input.rs | use super::PushConstant;
use winit::{
event::{ElementState, KeyEvent, RawKeyEvent},
keyboard::{KeyCode, PhysicalKey},
};
#[derive(Debug, Default)]
pub struct Input {
pub move_forward: bool,
pub move_backward: bool,
pub move_right: bool,
pub move_left: bool,
pub move_up: bool,
pub move_down: bool,
}
impl Input {
pub fn new() -> Self {
Default::default()
}
pub fn update_window_input(&mut self, key_event: &KeyEvent) {
let pressed = key_event.state == ElementState::Pressed;
if let PhysicalKey::Code(key) = key_event.physical_key {
match key {
KeyCode::KeyA => self.move_left = pressed,
KeyCode::KeyD => self.move_right = pressed,
KeyCode::KeyS => self.move_backward = pressed,
KeyCode::KeyW => self.move_forward = pressed,
KeyCode::Period | KeyCode::KeyQ => self.move_down = pressed,
KeyCode::Slash | KeyCode::KeyE => self.move_up = pressed,
_ => {}
}
}
}
pub fn update_device_input(&mut self, key_event: RawKeyEvent) {
let pressed = key_event.state == ElementState::Pressed;
if let PhysicalKey::Code(key) = key_event.physical_key {
match key {
KeyCode::ArrowLeft => self.move_left = pressed,
KeyCode::ArrowRight => self.move_right = pressed,
KeyCode::ArrowDown => self.move_backward = pressed,
KeyCode::ArrowUp => self.move_forward = pressed,
_ => {}
}
}
}
pub fn process_position(&self, push_constant: &mut PushConstant) {
let dx = 0.01;
if self.move_left {
push_constant.pos[0] -= dx;
}
if self.move_right {
push_constant.pos[0] += dx;
}
if self.move_backward {
push_constant.pos[1] -= dx;
}
if self.move_forward {
push_constant.pos[1] += dx;
}
if self.move_down {
push_constant.pos[2] -= dx;
}
if self.move_up {
push_constant.pos[2] += dx;
}
}
}
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/instance.rs | src/instance.rs | use std::{collections::HashSet, ffi::CStr, sync::Arc};
use crate::{device::Device, surface::Surface};
use anyhow::{Context, Result};
use ash::{ext, khr, vk, Entry};
use parking_lot::Mutex;
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
unsafe extern "system" fn vulkan_debug_callback(
message_severity: vk::DebugUtilsMessageSeverityFlagsEXT,
message_type: vk::DebugUtilsMessageTypeFlagsEXT,
p_callback_data: *const vk::DebugUtilsMessengerCallbackDataEXT,
_user_data: *mut std::os::raw::c_void,
) -> vk::Bool32 {
assert!(!p_callback_data.is_null());
let callback_data = &unsafe { *p_callback_data };
let message = unsafe { CStr::from_ptr(callback_data.p_message) }.to_string_lossy();
if message.starts_with("Validation Performance Warning") {
} else if message.starts_with("Validation Warning: [ VUID_Undefined ]") {
log::warn!("{:?}:\n{:?}: {}\n", message_severity, message_type, message,);
} else {
log::error!("{:?}:\n{:?}: {}\n", message_severity, message_type, message,);
}
vk::FALSE
}
pub struct Instance {
pub entry: ash::Entry,
pub inner: ash::Instance,
dbg_loader: ext::debug_utils::Instance,
dbg_callbk: vk::DebugUtilsMessengerEXT,
}
impl std::ops::Deref for Instance {
type Target = ash::Instance;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl Instance {
pub fn new(display_handle: Option<&impl HasDisplayHandle>) -> Result<Self> {
let entry = unsafe { Entry::load() }?;
let layers = [
#[cfg(debug_assertions)]
c"VK_LAYER_KHRONOS_validation".as_ptr(),
];
let mut extensions = vec![
ext::debug_utils::NAME.as_ptr(),
khr::surface::NAME.as_ptr(),
khr::display::NAME.as_ptr(),
khr::get_physical_device_properties2::NAME.as_ptr(),
];
if let Some(handle) = display_handle {
extensions.extend(ash_window::enumerate_required_extensions(
handle.display_handle()?.as_raw(),
)?);
}
let appinfo = vk::ApplicationInfo::default()
.application_name(c"Modern Vulkan")
.api_version(vk::API_VERSION_1_3);
let instance_info = vk::InstanceCreateInfo::default()
.application_info(&appinfo)
.flags(vk::InstanceCreateFlags::default())
.enabled_layer_names(&layers)
.enabled_extension_names(&extensions);
let inner = unsafe { entry.create_instance(&instance_info, None) }?;
let dbg_info = vk::DebugUtilsMessengerCreateInfoEXT::default()
.message_severity(
vk::DebugUtilsMessageSeverityFlagsEXT::ERROR
// | vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE
// | vk::DebugUtilsMessageSeverityFlagsEXT::INFO
| vk::DebugUtilsMessageSeverityFlagsEXT::WARNING,
)
.message_type(
vk::DebugUtilsMessageTypeFlagsEXT::VALIDATION
| vk::DebugUtilsMessageTypeFlagsEXT::DEVICE_ADDRESS_BINDING
| vk::DebugUtilsMessageTypeFlagsEXT::GENERAL
| vk::DebugUtilsMessageTypeFlagsEXT::PERFORMANCE,
)
.pfn_user_callback(Some(vulkan_debug_callback));
let dbg_loader = ext::debug_utils::Instance::new(&entry, &inner);
let dbg_callbk = unsafe { dbg_loader.create_debug_utils_messenger(&dbg_info, None)? };
Ok(Self {
dbg_loader,
dbg_callbk,
entry,
inner,
})
}
pub fn create_device_and_queues(
&self,
surface: &Surface,
) -> Result<(Device, vk::Queue, vk::Queue)> {
let required_device_extensions = [
khr::swapchain::NAME,
ext::graphics_pipeline_library::NAME,
khr::pipeline_library::NAME,
khr::dynamic_rendering::NAME,
ext::extended_dynamic_state2::NAME,
ext::extended_dynamic_state::NAME,
khr::synchronization2::NAME,
khr::buffer_device_address::NAME,
khr::create_renderpass2::NAME,
ext::descriptor_indexing::NAME,
];
let required_device_extensions_set = HashSet::from(required_device_extensions);
let devices = unsafe { self.enumerate_physical_devices() }?;
let (pdevice, main_queue_family_idx, transfer_queue_family_idx) =
devices
.into_iter()
.find_map(|device| {
let extensions =
unsafe { self.enumerate_device_extension_properties(device) }.ok()?;
let extensions: HashSet<_> = extensions
.iter()
.map(|x| x.extension_name_as_c_str().unwrap())
.collect();
let missing = required_device_extensions_set.difference(&extensions);
if missing.count() > 0 {
return None;
}
use vk::QueueFlags as QF;
let queue_properties =
unsafe { self.get_physical_device_queue_family_properties(device) };
let main_queue_idx =
queue_properties
.iter()
.enumerate()
.find_map(|(family_idx, properties)| {
let family_idx = family_idx as u32;
let queue_support =
properties.queue_flags.contains(QF::GRAPHICS | QF::TRANSFER);
let surface_support =
surface.get_device_surface_support(device, family_idx);
(queue_support && surface_support).then_some(family_idx)
});
let transfer_queue_idx = queue_properties.iter().enumerate().find_map(
|(family_idx, properties)| {
let family_idx = family_idx as u32;
let queue_support = properties.queue_flags.contains(QF::TRANSFER)
&& !properties.queue_flags.contains(QF::GRAPHICS);
(Some(family_idx) != main_queue_idx && queue_support)
.then_some(family_idx)
},
)?;
Some((device, main_queue_idx?, transfer_queue_idx))
})
.context("Failed to find suitable device.")?;
let queue_infos = [
vk::DeviceQueueCreateInfo::default()
.queue_family_index(main_queue_family_idx)
.queue_priorities(&[1.0]),
vk::DeviceQueueCreateInfo::default()
.queue_family_index(transfer_queue_family_idx)
.queue_priorities(&[0.5]),
];
let required_device_extensions = required_device_extensions.map(|x| x.as_ptr());
let mut feature_dynamic_state =
vk::PhysicalDeviceExtendedDynamicState2FeaturesEXT::default();
let mut feature_descriptor_indexing =
vk::PhysicalDeviceDescriptorIndexingFeatures::default()
.runtime_descriptor_array(true)
.shader_sampled_image_array_non_uniform_indexing(true)
.shader_storage_image_array_non_uniform_indexing(true)
.shader_storage_buffer_array_non_uniform_indexing(true)
.shader_uniform_buffer_array_non_uniform_indexing(true)
.descriptor_binding_sampled_image_update_after_bind(true)
.descriptor_binding_partially_bound(true)
.descriptor_binding_variable_descriptor_count(true)
.descriptor_binding_update_unused_while_pending(true);
let mut feature_buffer_device_address =
vk::PhysicalDeviceBufferDeviceAddressFeatures::default().buffer_device_address(true);
let mut feature_synchronization2 =
vk::PhysicalDeviceSynchronization2Features::default().synchronization2(true);
let mut feature_pipeline_library =
vk::PhysicalDeviceGraphicsPipelineLibraryFeaturesEXT::default()
.graphics_pipeline_library(true);
let mut feature_dynamic_rendering =
vk::PhysicalDeviceDynamicRenderingFeatures::default().dynamic_rendering(true);
let mut features = vk::PhysicalDeviceFeatures::default().shader_int64(true);
if cfg!(debug_assertions) {
features.robust_buffer_access = 1;
}
let mut default_features = vk::PhysicalDeviceFeatures2::default()
.features(features)
.push_next(&mut feature_descriptor_indexing)
.push_next(&mut feature_buffer_device_address)
.push_next(&mut feature_synchronization2)
.push_next(&mut feature_dynamic_state)
.push_next(&mut feature_pipeline_library)
.push_next(&mut feature_dynamic_rendering);
let device_info = vk::DeviceCreateInfo::default()
.queue_create_infos(&queue_infos)
.enabled_extension_names(&required_device_extensions)
.push_next(&mut default_features);
let device = unsafe { self.inner.create_device(pdevice, &device_info, None) }?;
let memory_properties = unsafe { self.get_physical_device_memory_properties(pdevice) };
let dynamic_rendering = khr::dynamic_rendering::Device::new(self, &device);
let device_alloc_properties =
unsafe { gpu_alloc_ash::device_properties(self, vk::API_VERSION_1_3, pdevice)? };
let allocator =
gpu_alloc::GpuAllocator::new(gpu_alloc::Config::i_am_potato(), device_alloc_properties);
let mut descriptor_indexing_props =
vk::PhysicalDeviceDescriptorIndexingProperties::default();
let mut device_properties =
vk::PhysicalDeviceProperties2::default().push_next(&mut descriptor_indexing_props);
unsafe { self.get_physical_device_properties2(pdevice, &mut device_properties) };
let command_pool = unsafe {
device.create_command_pool(
&vk::CommandPoolCreateInfo::default()
.flags(vk::CommandPoolCreateFlags::TRANSIENT)
.queue_family_index(main_queue_family_idx),
None,
)?
};
{};
let dbg_utils = ext::debug_utils::Device::new(&self.inner, &device);
let device = Device {
physical_device: pdevice,
device_properties: device_properties.properties,
descriptor_indexing_props,
main_queue_family_idx,
transfer_queue_family_idx,
command_pool,
memory_properties,
allocator: Arc::new(Mutex::new(allocator)),
device,
dynamic_rendering,
dbg_utils,
};
let main_queue = unsafe { device.get_device_queue(main_queue_family_idx, 0) };
let transfer_queue = unsafe { device.get_device_queue(transfer_queue_family_idx, 0) };
Ok((device, main_queue, transfer_queue))
}
pub fn create_surface(
&self,
handle: &(impl HasDisplayHandle + HasWindowHandle),
) -> Result<Surface> {
Surface::new(&self.entry, &self.inner, handle)
}
}
impl Drop for Instance {
fn drop(&mut self) {
unsafe {
self.dbg_loader
.destroy_debug_utils_messenger(self.dbg_callbk, None);
self.inner.destroy_instance(None);
}
}
}
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/default_shaders/glsl.rs | src/default_shaders/glsl.rs | pub const FRAG_SHADER: &str = "#version 460
#extension GL_EXT_buffer_reference : require
#extension GL_EXT_nonuniform_qualifier : require
// In the beginning, colours never existed. There's nothing that was done before you...
#include <prelude.glsl>
layout(location = 0) in vec2 in_uv;
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 0) uniform sampler gsamplers[];
layout(set = 0, binding = 1) uniform texture2D gtextures[];
vec4 Tex(uint id) {
return texture(
nonuniformEXT(sampler2D(gtextures[id], gsamplers[LINER_SAMPL])), in_uv);
}
vec4 Tex(uint id, vec2 uv) {
return texture(
nonuniformEXT(sampler2D(gtextures[id], gsamplers[LINER_SAMPL])), uv);
}
layout(std430, push_constant) uniform PushConstant {
vec3 pos;
float time;
vec2 resolution;
vec2 mouse;
bool mouse_pressed;
uint frame;
float time_delta;
float record_time;
}
pc;
void main() {
vec2 uv = (in_uv + -0.5) * vec2(pc.resolution.x / pc.resolution.y, 1);
vec3 col = vec3(uv, 1.);
out_color = vec4(col, 1.0);
}";
pub const VERT_SHADER: &str = "#version 460
#extension GL_EXT_buffer_reference : require
#extension GL_EXT_nonuniform_qualifier : require
layout(set = 0, binding = 0) uniform sampler gsamplers[];
layout(set = 0, binding = 1) uniform texture2D gtextures[];
layout(std430, push_constant) uniform PushConstant {
vec3 pos;
float time;
vec2 resolution;
vec2 mouse;
bool mouse_pressed;
uint frame;
float time_delta;
float record_time;
}
pc;
layout(location = 0) out vec2 out_uv;
void main() {
out_uv = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2);
gl_Position = vec4(out_uv * 2.0f + -1.0f, 0.0, 1.0);
}";
pub const COMP_SHADER: &str = "#version 460
#extension GL_EXT_nonuniform_qualifier : require
#extension GL_EXT_buffer_reference : require
layout(set = 0, binding = 0) uniform sampler gsamplers[];
layout(set = 0, binding = 1) uniform texture2D gtextures[];
layout(std430, push_constant) uniform PushConstant {
vec3 pos;
float time;
vec2 resolution;
vec2 mouse;
bool mouse_pressed;
uint frame;
float time_delta;
float record_time;
}
pc;
layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
void main() {
if (gl_GlobalInvocationID.x >= pc.resolution.x ||
gl_GlobalInvocationID.y >= pc.resolution.y) {
return;
}
}";
pub const PRELUDE: &str = "const float PI = acos(-1.);
const float TAU = 2. * PI;
const uint PREV_TEX = 0;
const uint GENERIC_TEX1 = 1;
const uint GENERIC_TEX2 = 2;
const uint DITHER_TEX = 3;
const uint NOISE_TEX = 4;
const uint BLUE_TEX = 5;
const uint LINER_SAMPL = 0;
const uint NEAREST_SAMPL = 1;
vec4 ASSERT_COL = vec4(0.);
void assert(bool cond, int v) {
if (!(cond)) {
if (v == 0) ASSERT_COL.x = -1.0;
else if (v == 1) ASSERT_COL.y = -1.0;
else if (v == 2) ASSERT_COL.z = -1.0;
else ASSERT_COL.w = -1.0;
}
}
void assert(bool cond) { assert(cond, 0); }
#define catch_assert(out) \
if (ASSERT_COL.x < 0.0) out = vec4(1.0, 0.0, 0.0, 1.0); \
if (ASSERT_COL.y < 0.0) out = vec4(0.0, 1.0, 0.0, 1.0); \
if (ASSERT_COL.z < 0.0) out = vec4(0.0, 0.0, 1.0, 1.0); \
if (ASSERT_COL.w < 0.0) out = vec4(1.0, 1.0, 0.0, 1.0);
float AAstep(float threshold, float val) {
return smoothstep(-.5, .5, (val - threshold) / min(0.005, fwidth(val - threshold)));
}
float AAstep(float val) {
return AAstep(val, 0.);
}
float worldsdf(vec3 rayPos);
vec2 ray_march(vec3 rayPos, vec3 rayDir) {
const vec3 EPS = vec3(0., 0.001, 0.0001);
const float HIT_DIST = EPS.y;
const int MAX_STEPS = 100;
const float MISS_DIST = 10.0;
float dist = 0.0;
for(int i = 0; i < MAX_STEPS; i++) {
vec3 pos = rayPos + (dist * rayDir);
float posToScene = worldsdf(pos);
dist += posToScene;
if(abs(posToScene) < HIT_DIST) return vec2(dist, i);
if(posToScene > MISS_DIST) break;
}
return vec2(-dist, MAX_STEPS);
}
mat2 rotate(float angle) {
float sine = sin(angle);
float cosine = cos(angle);
return mat2(cosine, -sine, sine, cosine);
}
vec3 enlight(in vec3 at, vec3 normal, vec3 diffuse, vec3 l_color, vec3 l_pos) {
vec3 l_dir = l_pos - at;
return diffuse * l_color * max(0., dot(normal, normalize(l_dir))) /
dot(l_dir, l_dir);
}
vec3 wnormal(in vec3 p) {
const vec3 EPS = vec3(0., 0.01, 0.0001);
return normalize(vec3(worldsdf(p + EPS.yxx) - worldsdf(p - EPS.yxx),
worldsdf(p + EPS.xyx) - worldsdf(p - EPS.xyx),
worldsdf(p + EPS.xxy) - worldsdf(p - EPS.xxy)));
}";
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
pannapudi/pilka | https://github.com/pannapudi/pilka/blob/0cd33460bcc9350023a92bb908e910fe147aec8d/src/default_shaders/mod.rs | src/default_shaders/mod.rs | use std::fs::File;
use std::io::Write;
use std::path::Path;
use crate::create_folder;
mod glsl;
pub fn create_default_shaders<P: AsRef<Path>>(name: P) -> std::io::Result<()> {
create_folder(&name)?;
let create_file = |filename: &str, content: &str| -> std::io::Result<()> {
let path = name.as_ref().join(filename);
let mut file = File::create(path)?;
file.write_all(content.as_bytes())
};
create_file("prelude.glsl", glsl::PRELUDE)?;
create_file("shader.frag", glsl::FRAG_SHADER)?;
create_file("shader.vert", glsl::VERT_SHADER)?;
create_file("shader.comp", glsl::COMP_SHADER)?;
Ok(())
}
| rust | MIT | 0cd33460bcc9350023a92bb908e910fe147aec8d | 2026-01-04T20:19:40.382559Z | false |
tatut/pgprolog | https://github.com/tatut/pgprolog/blob/e3629cc2f5a56da98c22939436d9d803e2f9a6d5/src/lib.rs | src/lib.rs | use pgrx::prelude::*;
use pgrx::fcinfo::*;
use pgrx::spi::Spi;
use scryer_prolog::machine;
use scryer_prolog::machine::parsed_results::{
QueryResolution, prolog_value_to_json_string
};
use std::time::{Duration, Instant};
pgrx::pg_module_magic!();
#[pg_extern(sql = "CREATE FUNCTION plprolog_call_handler() RETURNS language_handler LANGUAGE c AS 'MODULE_PATHNAME', '@FUNCTION_NAME@';")]
unsafe fn plprolog_call_handler(fcinfo: pg_sys::FunctionCallInfo) -> pg_sys::Datum {
let str : Option<&str> = pg_getarg(fcinfo, 0);
let mut machine = machine::Machine::new_lib();
// We need procedure OID to get the actual source
let oid : pg_sys::Oid = unsafe {
fcinfo.as_ref().unwrap().flinfo.as_ref().expect("flinfo present").fn_oid
};
// Consult the code as module
let d1 = Instant::now();
let code = get_code(oid);
pgrx::notice!("get code took: {:?}", d1.elapsed());
let d2 = Instant::now();
machine.load_module_string("plprolog_user", code.clone());
pgrx::notice!("consultation took: {:?}", d2.elapsed());
//format!("got code: {0}, arg: {1}", code, str.expect("argument")).into_datum().expect("result")
// Then query handle(In,Out)
let d3 = Instant::now();
let output = machine.run_query(format!("handle({0}, Out).", str.expect("argument present")));
pgrx::notice!("query took: {:?}", d3.elapsed());
let d4 = Instant::now();
let result : Option<pg_sys::Datum> =
match output {
Ok(QueryResolution::Matches(results)) => {
// FIXME: turn bindings into actual table result
let out = results[0].bindings.get("Out").expect("Expected output binding");
let result_str = format!("got results: {0}", prolog_value_to_json_string(out.clone()).as_str());
result_str.into_datum()
},
Ok(b) => format!("got truth: {0}", b.to_string()).into_datum(),
Err(e) => format!("Got error: {0}", e).as_str().into_datum()
};
let final_result = result.expect("output conversion");
pgrx::notice!("output conversion took: {:?}", d4.elapsed());
final_result
}
fn get_code(oid: pg_sys::Oid) -> String {
match Spi::get_one::<&str>(format!("SELECT prosrc FROM pg_proc WHERE oid={0}", oid.as_u32().to_string()).as_str()) {
Ok(Some(code)) => code.to_string(),
Ok(None) => panic!("Code for procedure not found"),
Err(err) => panic!("SPI error: {0}", err)
}
}
| rust | BSD-3-Clause | e3629cc2f5a56da98c22939436d9d803e2f9a6d5 | 2026-01-04T20:19:48.438076Z | false |
smallnest/rpcx-rs | https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/build.rs | build.rs | [package]
name = "rpcx-rs"
version = "0.1.0"
authors = ["The rpcx-rs Project Developers", "smallnest@gmail.com"]
license = "MIT"
readme = "README.md"
repository = "https://github.com/smallnest/rust-rs"
documentation = "https://docs.rs/rust-rs/"
homepage = "https://crates.io/crates/rust-rs"
keywords = ["rpc", "network", "microservice"]
categories = ["network-programming"]
autobenches = true
edition = "2018"
[workspace]
members = [
"rpcx_protocol",
"rpcx_derive",
"rpcx_client",
"rpcx_server",
"examples/client_call_mul",
"examples/client_call_mul_async",
]
[profile.release]
debug = true
[profile.bench]
debug = true
| rust | Apache-2.0 | 09578e704de21af635da8357d36be468f10df27b | 2026-01-04T20:19:51.398380Z | false |
smallnest/rpcx-rs | https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/rpcx_server/src/lib.rs | rpcx_server/src/lib.rs | use std::{
boxed::Box,
collections::HashMap,
sync::{Arc, RwLock},
};
use std::net::SocketAddr;
use rpcx_protocol::*;
use std::{
io::{BufReader, BufWriter, Write},
net::{Shutdown, TcpListener, TcpStream},
};
use std::{
os::unix::io::{AsRawFd, RawFd},
thread,
};
use scoped_threadpool::Pool;
pub mod plugin;
pub use plugin::*;
pub type RpcxFn = fn(&[u8], SerializeType) -> Result<Vec<u8>>;
pub struct Server {
pub addr: String,
raw_fd: Option<RawFd>,
pub services: Arc<RwLock<HashMap<String, Box<RpcxFn>>>>,
thread_number: u32,
register_plugins: Arc<RwLock<Vec<Box<dyn RegisterPlugin + Send + Sync>>>>,
connect_plugins: Arc<RwLock<Vec<Box<dyn ConnectPlugin + Send + Sync>>>>,
}
impl Server {
pub fn new(s: String, n: u32) -> Self {
let mut thread_number = n;
if n == 0 {
thread_number = num_cpus::get() as u32;
thread_number *= 2;
}
Server {
addr: s,
services: Arc::new(RwLock::new(HashMap::new())),
thread_number,
register_plugins: Arc::new(RwLock::new(Vec::new())),
connect_plugins: Arc::new(RwLock::new(Vec::new())),
raw_fd: None,
}
}
pub fn register_fn(
&mut self,
service_path: String,
service_method: String,
meta: String,
f: RpcxFn,
) {
// invoke register plugins
let mut plugins = self.register_plugins.write().unwrap();
for p in plugins.iter_mut() {
let pp = &mut **p;
match pp.register_fn(
service_path.as_str(),
service_method.as_str(),
meta.clone(),
f,
) {
Ok(_) => {}
Err(err) => eprintln!("{}", err),
}
}
// invoke service
let key = format!("{}.{}", service_path, service_method);
let services = self.services.clone();
let mut map = services.write().unwrap();
map.insert(key, Box::new(f));
}
pub fn get_fn(&self, service_path: String, service_method: String) -> Option<RpcxFn> {
let key = format!("{}.{}", service_path, service_method);
let map = self.services.read().unwrap();
let box_fn = map.get(&key)?;
Some(**box_fn)
}
pub fn start_with_listener(&self, listener: TcpListener) -> Result<()> {
let thread_number = self.thread_number;
'accept_loop: for stream in listener.incoming() {
match stream {
Ok(stream) => {
let services_cloned = self.services.clone();
thread::spawn(move || {
Server::process(thread_number, services_cloned, stream);
});
}
Err(e) => {
//println!("Unable to accept: {}", e);
return Err(Error::new(ErrorKind::Network, e));
}
}
}
Ok(())
}
pub fn start(&mut self) -> Result<()> {
let addr = self
.addr
.parse::<SocketAddr>()
.map_err(|err| Error::new(ErrorKind::Other, err))?;
let listener = TcpListener::bind(&addr)?;
println!("Listening on: {}", addr);
self.raw_fd = Some(listener.as_raw_fd());
self.start_with_listener(listener)
}
pub fn close(&self) {
if let Some(raw_fd) = self.raw_fd {
unsafe {
libc::close(raw_fd);
}
}
}
fn process(
thread_number: u32,
service: Arc<RwLock<HashMap<String, Box<RpcxFn>>>>,
stream: TcpStream,
) {
let services_cloned = service;
let local_stream = stream.try_clone().unwrap();
let mut pool = Pool::new(thread_number);
pool.scoped(|scoped| {
let mut reader = BufReader::new(stream.try_clone().unwrap());
loop {
let mut msg = Message::new();
match msg.decode(&mut reader) {
Ok(()) => {
let service_path = &msg.service_path;
let service_method = &msg.service_method;
let key = format!("{}.{}", service_path, service_method);
let map = &services_cloned.read().unwrap();
match map.get(&key) {
Some(box_fn) => {
let f = **box_fn;
let local_stream_in_child = local_stream.try_clone().unwrap();
scoped.execute(move || {
invoke_fn(local_stream_in_child.try_clone().unwrap(), msg, f)
});
}
None => {
let err = format!("service {} not found", key);
let reply_msg = msg.get_reply().unwrap();
let mut metadata = reply_msg.metadata.borrow_mut();
(*metadata).insert(SERVICE_ERROR.to_string(), err);
drop(metadata);
let data = reply_msg.encode();
let mut writer = BufWriter::new(local_stream.try_clone().unwrap());
writer.write_all(&data).unwrap();
writer.flush().unwrap();
}
}
}
Err(err) => {
eprintln!("failed to read: {}", err.to_string());
match local_stream.shutdown(Shutdown::Both) {
Ok(()) => {
if let Ok(sa) = local_stream.peer_addr() {
println!("client {} is closed", sa)
}
}
Err(e) => {
if let Ok(sa) = local_stream.peer_addr() {
println!("client {} is closed. err: {}", sa, e)
}
}
}
return;
}
}
}
});
}
}
fn invoke_fn(stream: TcpStream, msg: Message, f: RpcxFn) {
let mut reply_msg = msg.get_reply().unwrap();
let reply = f(&msg.payload, msg.get_serialize_type().unwrap()).unwrap();
reply_msg.payload = reply;
let data = reply_msg.encode();
let mut writer = BufWriter::new(stream.try_clone().unwrap());
match writer.write_all(&data) {
Ok(()) => {}
Err(_err) => {}
}
match writer.flush() {
Ok(()) => {}
Err(_err) => {}
}
}
#[macro_export]
macro_rules! register_func {
($rpc_server:expr, $service_path:expr, $service_method:expr, $service_fn:expr, $meta:expr, $arg_type:ty, $reply_type:ty) => {{
let f: RpcxFn = |x, st| {
// TODO change ProtoArgs to $arg_typ
let mut args: $arg_type = Default::default();
args.from_slice(st, x)?;
let reply: $reply_type = $service_fn(args);
reply.into_bytes(st)
};
$rpc_server.register_fn(
$service_path.to_string(),
$service_method.to_string(),
$meta,
f,
);
}};
}
| rust | Apache-2.0 | 09578e704de21af635da8357d36be468f10df27b | 2026-01-04T20:19:51.398380Z | false |
smallnest/rpcx-rs | https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/rpcx_server/src/plugin.rs | rpcx_server/src/plugin.rs | use super::{RpcxFn, Server};
#[allow(unused_imports)]
use rpcx_protocol::*;
use std::net::TcpStream;
impl Server {
pub fn add_register_plugin(&mut self, p: Box<dyn RegisterPlugin + Send + Sync>) {
let mut plugins = self.register_plugins.write().unwrap();
plugins.push(p);
}
pub fn add_connect_plugin(&mut self, p: Box<dyn ConnectPlugin + Send + Sync>) {
let mut plugins = self.connect_plugins.write().unwrap();
plugins.push(p);
}
}
pub trait RegisterPlugin {
fn register_fn(
&mut self,
service_path: &str,
service_method: &str,
meta: String,
f: RpcxFn,
) -> Result<()>;
}
pub trait ConnectPlugin {
fn connected(&mut self, conn: &TcpStream) -> Result<()>;
}
| rust | Apache-2.0 | 09578e704de21af635da8357d36be468f10df27b | 2026-01-04T20:19:51.398380Z | false |
smallnest/rpcx-rs | https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/rpcx_client/src/discovery.rs | rpcx_client/src/discovery.rs | use super::selector::ClientSelector;
use std::{
collections::HashMap,
ops::Deref,
sync::{Arc, RwLock},
};
pub trait Discovery<'a> {
fn get_services(&self) -> HashMap<String, String>;
fn add_selector(&'a self, s: &'a (dyn ClientSelector + Sync + Send + 'static));
fn close(&self);
}
#[derive(Default)]
pub struct StaticDiscovery<'a> {
servers: HashMap<String, String>,
selectors: Arc<RwLock<Vec<&'a (dyn ClientSelector + Sync + Send + 'static)>>>,
}
impl<'a> StaticDiscovery<'a> {
pub fn new() -> StaticDiscovery<'a> {
StaticDiscovery {
servers: HashMap::new(),
selectors: Arc::new(RwLock::new(Vec::new())),
}
}
pub fn update_servers(&self, servers: &HashMap<String, String>) {
let selectors = (*self).selectors.write().unwrap();
let v = selectors.deref();
for s in v {
s.update_server(servers);
}
}
}
impl<'a> Discovery<'a> for StaticDiscovery<'a> {
fn get_services(&self) -> HashMap<String, String> {
let mut servers = HashMap::new();
for (k, v) in &self.servers {
servers.insert(k.clone(), v.clone());
}
servers
}
fn add_selector(&'a self, s: &'a (dyn ClientSelector + Sync + Send + 'static)) {
let mut selectors = (*self).selectors.write().unwrap();
selectors.push(s);
}
fn close(&self) {}
}
| rust | Apache-2.0 | 09578e704de21af635da8357d36be468f10df27b | 2026-01-04T20:19:51.398380Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.