mirror of
https://github.com/storytold/artcraft.git
synced 2026-10-25 03:09:30 -04:00
Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48f80f201b | ||
|
|
86c77e9625 | ||
|
|
776312ef6e | ||
|
|
7da40d5177 | ||
|
|
f06b5098e2 | ||
|
|
eac503af46 | ||
|
|
16932374f5 | ||
|
|
35940a4a63 | ||
|
|
55543b3735 | ||
|
|
3d44e6e29e | ||
|
|
3244b802fa | ||
|
|
5e7a5d2cff | ||
|
|
ecb73e4f80 | ||
|
|
39092fa866 | ||
|
|
ca80275d28 | ||
|
|
8c192b17f1 | ||
|
|
40da6f6500 | ||
|
|
2a3982aa5a | ||
|
|
a1c2b4f5c8 | ||
|
|
213d3f7bd2 | ||
|
|
0788e98b54 | ||
|
|
65c8ddfa91 | ||
|
|
a60e20c0b4 | ||
|
|
54d417f4c5 | ||
|
|
98a74e3a96 | ||
|
|
b537223ffa | ||
|
|
8001f24195 | ||
|
|
778a4e72c8 | ||
|
|
083680232c | ||
|
|
b1b44ceb60 | ||
|
|
d988acbf6e | ||
|
|
6e05b7a1b5 | ||
|
|
8a364605cf | ||
|
|
30a8e72efe | ||
|
|
ff1a83898b | ||
|
|
f1b9299e46 | ||
|
|
2eefaaf7a1 | ||
|
|
a21b4a4275 | ||
|
|
e4c561eb41 | ||
|
|
420a23d359 | ||
|
|
9cd3b493c6 | ||
|
|
bbd5953000 |
Generated
+101
-4
@@ -840,11 +840,14 @@ version = "0.4.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc2d0cfb2a7388d34f590e76686704c494ed7aaceed62ee1ba35cbf363abc2a5"
|
||||
dependencies = [
|
||||
"brotli 3.5.0",
|
||||
"flate2",
|
||||
"futures-core",
|
||||
"memchr",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"zstd 0.13.1",
|
||||
"zstd-safe 7.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2877,6 +2880,12 @@ version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e962a19be5cfc3f3bf6dd8f61eb50107f356ad6270fbb3ed41476571db78be5"
|
||||
|
||||
[[package]]
|
||||
name = "data-url"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c297a1c74b71ae29df00c3e22dd9534821d60eb9af5a0192823fa2acea70c2a"
|
||||
|
||||
[[package]]
|
||||
name = "datetimes"
|
||||
version = "0.0.1"
|
||||
@@ -5339,6 +5348,7 @@ dependencies = [
|
||||
"hyper 1.6.0",
|
||||
"hyper-util",
|
||||
"rustls 0.23.13",
|
||||
"rustls-native-certs",
|
||||
"rustls-pki-types",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
@@ -6784,6 +6794,15 @@ dependencies = [
|
||||
"workspace-build-acceleration",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memory_store"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"errors",
|
||||
"workspace-build-acceleration",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "metal"
|
||||
version = "0.27.0"
|
||||
@@ -9638,6 +9657,7 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
"quinn",
|
||||
"rustls 0.23.13",
|
||||
"rustls-native-certs",
|
||||
"rustls-pemfile 2.1.2",
|
||||
"rustls-pki-types",
|
||||
"serde",
|
||||
@@ -9648,6 +9668,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-rustls",
|
||||
"tokio-socks",
|
||||
"tokio-util",
|
||||
"tower 0.5.2",
|
||||
"tower-service",
|
||||
@@ -9975,6 +9996,19 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-native-certs"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fcaf18a4f2be7326cd874a5fa579fae794320a0f388d365dca7e480e55f83f8a"
|
||||
dependencies = [
|
||||
"openssl-probe",
|
||||
"rustls-pemfile 2.1.2",
|
||||
"rustls-pki-types",
|
||||
"schannel",
|
||||
"security-framework",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pemfile"
|
||||
version = "1.0.4"
|
||||
@@ -11280,9 +11314,11 @@ dependencies = [
|
||||
"anyhow",
|
||||
"backoff",
|
||||
"chrono",
|
||||
"cookie 0.18.1",
|
||||
"enums",
|
||||
"enums_public",
|
||||
"errors",
|
||||
"idempotency",
|
||||
"log",
|
||||
"reqwest 0.12.15",
|
||||
"serde",
|
||||
@@ -11291,6 +11327,7 @@ dependencies = [
|
||||
"tokens",
|
||||
"tokio",
|
||||
"url",
|
||||
"uuid 1.8.0",
|
||||
"workspace-build-acceleration",
|
||||
]
|
||||
|
||||
@@ -12070,6 +12107,7 @@ dependencies = [
|
||||
"libloading 0.8.6",
|
||||
"log",
|
||||
"memory_caching",
|
||||
"memory_store",
|
||||
"once_cell",
|
||||
"openai_sora_client",
|
||||
"primitives",
|
||||
@@ -12084,6 +12122,7 @@ dependencies = [
|
||||
"subprocess_common",
|
||||
"tauri",
|
||||
"tauri-build",
|
||||
"tauri-plugin-http",
|
||||
"tauri-plugin-log",
|
||||
"tempdir",
|
||||
"tempfile",
|
||||
@@ -12158,9 +12197,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin"
|
||||
version = "2.1.1"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4190775d6ff73fe66d9af44c012739a2659720efd9c0e1e56a918678038699d"
|
||||
checksum = "37a5ebe6a610d1b78a94650896e6f7c9796323f408800cef436e0fa0539de601"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"glob",
|
||||
@@ -12173,6 +12212,52 @@ dependencies = [
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-fs"
|
||||
version = "2.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "88371e340ad2f07409a3b68294abe73f20bc9c1bc1b631a31dc37a3d0161f682"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"dunce",
|
||||
"glob",
|
||||
"percent-encoding",
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_repr",
|
||||
"tauri",
|
||||
"tauri-plugin",
|
||||
"tauri-utils",
|
||||
"thiserror 2.0.12",
|
||||
"toml 0.8.20",
|
||||
"url",
|
||||
"uuid 1.8.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-http"
|
||||
version = "2.4.3"
|
||||
dependencies = [
|
||||
"bytes 1.10.0",
|
||||
"cookie_store",
|
||||
"data-url",
|
||||
"http 1.1.0",
|
||||
"regex",
|
||||
"reqwest 0.12.15",
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"tauri-plugin",
|
||||
"tauri-plugin-fs",
|
||||
"thiserror 2.0.12",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"url",
|
||||
"urlpattern",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-log"
|
||||
version = "2.3.1"
|
||||
@@ -12285,9 +12370,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-utils"
|
||||
version = "2.3.1"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1f037e66c7638cc0a2213f61566932b9a06882b8346486579c90e4b019bac447"
|
||||
checksum = "b2900399c239a471bcff7f15c4399eb1a8c4fe511ba2853e07c996d771a5e0a4"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"brotli 7.0.0",
|
||||
@@ -12770,6 +12855,18 @@ dependencies = [
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-socks"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d4770b8024672c1101b3f6733eab95b18007dbe0847a8afe341fcf79e06043f"
|
||||
dependencies = [
|
||||
"either",
|
||||
"futures-util",
|
||||
"thiserror 1.0.63",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-stream"
|
||||
version = "0.1.16"
|
||||
|
||||
@@ -39,6 +39,7 @@ members = [
|
||||
"crates/lib/bootstrap",
|
||||
"crates/lib/bucket_paths",
|
||||
"crates/lib/caching/memory_caching",
|
||||
"crates/lib/caching/memory_store",
|
||||
"crates/lib/caching/redis_caching",
|
||||
"crates/lib/concurrency",
|
||||
"crates/lib/cookies",
|
||||
@@ -117,6 +118,7 @@ members = [
|
||||
"crates/vendor/candle/candle-transformers",
|
||||
"crates/vendor/candle/tensor-tools",
|
||||
"crates/vendor/limitation",
|
||||
"crates/vendor/tauri-plugin-http",
|
||||
# NB(bt,2023-12-12): Newrelic keeps breaking with upgrades. Kill for now.
|
||||
#"crates/vendor/newrelic-telemetry-sdk-rust",
|
||||
|
||||
@@ -172,6 +174,7 @@ serde_derive = "1.0.219"
|
||||
serde_json = "1.0.140"
|
||||
serde_yaml = "0.9.1"
|
||||
sha3 = "0.10.8"
|
||||
tauri = { version = "2.4.1", features = ["unstable"] }
|
||||
thiserror = "2.0.12"
|
||||
toml = "0.8.20"
|
||||
url = { version = "2.5.4", features = ["serde"] }
|
||||
@@ -182,8 +185,10 @@ enums = { path = "crates/_types/enums" }
|
||||
enums_public = { path = "crates/_types/enums_public" }
|
||||
errors = { path = "crates/lib/errors" }
|
||||
filesys = { path = "crates/lib/files/filesys" }
|
||||
idempotency = { path = "crates/lib/idempotency" }
|
||||
images = { path = "crates/lib/files/images" }
|
||||
memory_caching = { path = "crates/lib/caching/memory_caching" }
|
||||
memory_store = { path = "crates/lib/caching/memory_store" }
|
||||
mimetypes = { path = "crates/lib/files/mimetypes" }
|
||||
openai_sora_client = { path = "crates/lib/api_clients/openai_sora_client" }
|
||||
primitives = { path = "crates/lib/data/primitives" }
|
||||
|
||||
@@ -27,6 +27,7 @@ crockford = { workspace = true }
|
||||
errors = { workspace = true }
|
||||
filesys = { workspace = true }
|
||||
memory_caching = { workspace = true }
|
||||
memory_store = { workspace = true }
|
||||
openai_sora_client = { workspace = true }
|
||||
primitives = { workspace = true }
|
||||
storyteller_client = { workspace = true }
|
||||
@@ -52,13 +53,16 @@ serde = { workspace = true }
|
||||
serde_derive = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
serde_yaml = { workspace = true }
|
||||
tauri = { version = "2.4.1", features = ["unstable"] }
|
||||
tauri = { workspace = true }
|
||||
tauri-plugin-log = "2.3.1"
|
||||
tempdir = "0.3.7"
|
||||
tempfile = "3.18.0"
|
||||
tokio = { version = "1.42", features = ["rt", "rt-multi-thread", "fs"] }
|
||||
tokio-util = { version = "0.7", features = ["codec"] }
|
||||
|
||||
# NB: We need to vendor this in so that we can access the cookies inside via the private API
|
||||
tauri-plugin-http = { path = "../../vendor/tauri-plugin-http" }
|
||||
|
||||
# NB: The version of the `discord-rich-presence` crate (0.2.5) last published has non-Send/Sync error
|
||||
# types and can't do threading. We need to wait for a new version to unpin from Git.
|
||||
discord-rich-presence = { git = "https://github.com/vionya/discord-rich-presence" }
|
||||
|
||||
@@ -7,6 +7,14 @@
|
||||
],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"log:default"
|
||||
"log:default",
|
||||
{
|
||||
"identifier": "http:default",
|
||||
"allow": [
|
||||
{ "url": "https://*.storyteller.ai" },
|
||||
{ "url": "https://*.fakeyou.com" }
|
||||
],
|
||||
"deny": [{ "url": "https://private.tauri.app" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod flip_image;
|
||||
pub mod platform_info_command;
|
||||
pub mod sora;
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
use crate::state::os_platform::OsPlatform;
|
||||
use base64::prelude::BASE64_STANDARD;
|
||||
use base64::Engine;
|
||||
use image::codecs::png::{CompressionType, FilterType, PngEncoder};
|
||||
use image::ImageReader;
|
||||
use log::info;
|
||||
use serde_derive::Serialize;
|
||||
use std::io::Cursor;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct PlatformInfoResponse {
|
||||
pub os_platform: DetectedOs,
|
||||
pub webview_runtime: WebviewRuntime,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum DetectedOs {
|
||||
Windows,
|
||||
#[serde(rename = "macos")]
|
||||
MacOS,
|
||||
Linux,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum WebviewRuntime {
|
||||
#[serde(rename = "webkit_safari")]
|
||||
WebkitSafari,
|
||||
#[serde(rename = "webkit_gtk")]
|
||||
WebkitGtk,
|
||||
#[serde(rename = "edge_webview_2")]
|
||||
EdgeWebview2,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn platform_info_command() -> Result<PlatformInfoResponse, String> {
|
||||
info!("platform_info_command called...");
|
||||
|
||||
let os_platform = match OsPlatform::maybe_get() {
|
||||
Some(OsPlatform::Linux) => DetectedOs::Linux,
|
||||
Some(OsPlatform::MacOs) => DetectedOs::MacOS,
|
||||
Some(OsPlatform::Windows) => DetectedOs::Windows,
|
||||
None => DetectedOs::Unknown,
|
||||
};
|
||||
|
||||
// These are the webviews that Tauri uses on each OS:
|
||||
// https://tauri.app/reference/webview-versions/
|
||||
let webview_runtime = match os_platform {
|
||||
DetectedOs::Windows => WebviewRuntime::EdgeWebview2,
|
||||
DetectedOs::MacOS => WebviewRuntime::WebkitSafari,
|
||||
DetectedOs::Linux => WebviewRuntime::WebkitGtk,
|
||||
DetectedOs::Unknown => WebviewRuntime::Unknown,
|
||||
};
|
||||
|
||||
Ok(PlatformInfoResponse {
|
||||
os_platform,
|
||||
webview_runtime,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,21 +4,24 @@ pub mod state;
|
||||
pub mod threads;
|
||||
pub mod utils;
|
||||
|
||||
use tauri::{Manager};
|
||||
use tauri::Manager;
|
||||
|
||||
use crate::commands::flip_image::flip_image;
|
||||
use crate::commands::platform_info_command::platform_info_command;
|
||||
use crate::commands::sora::open_sora_login_command::open_sora_login_command;
|
||||
use crate::state::main_window_size::MainWindowSize;
|
||||
use crate::commands::sora::sora_image_generation_command::sora_image_generation_command;
|
||||
use crate::commands::sora::sora_image_remix_command::sora_image_remix_command;
|
||||
use crate::state::app_config::AppConfig;
|
||||
use crate::state::main_window_size::MainWindowSize;
|
||||
use crate::state::sora::sora_credential_manager::SoraCredentialManager;
|
||||
use crate::state::sora::sora_task_queue::SoraTaskQueue;
|
||||
use crate::state::storyteller::storyteller_credential_manager::StorytellerCredentialManager;
|
||||
use crate::threads::discord_presence_thread::discord_presence_thread;
|
||||
use crate::threads::main_window_thread::main_window_thread;
|
||||
use crate::threads::main_window_thread::main_window_thread::main_window_thread;
|
||||
use crate::threads::sora_session_login_thread::sora_session_login_thread;
|
||||
use crate::threads::sora_task_polling_thread::sora_task_polling_thread;
|
||||
|
||||
use tauri_plugin_http;
|
||||
use tauri_plugin_log::Target;
|
||||
use tauri_plugin_log::TargetKind;
|
||||
|
||||
@@ -34,6 +37,10 @@ pub fn run() {
|
||||
let app_data_root = config.app_data_root.clone();
|
||||
let app_data_root_2 = config.app_data_root.clone();
|
||||
|
||||
println!("Attempting to read existing artcraft credentials...");
|
||||
let storyteller_creds_manager = StorytellerCredentialManager::initialize_from_disk_infallible(&app_data_root);
|
||||
let storyteller_creds_manager_2 = storyteller_creds_manager.clone();
|
||||
|
||||
println!("Attempting to read existing credentials...");
|
||||
let sora_creds_manager = SoraCredentialManager::initialize_from_disk_infallible(&app_data_root);
|
||||
let sora_creds_manager_2 = sora_creds_manager.clone();
|
||||
@@ -45,6 +52,7 @@ pub fn run() {
|
||||
println!("Initializing backend runtime...");
|
||||
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_http::init())
|
||||
.plugin(tauri_plugin_log::Builder::new()
|
||||
.level(log::LevelFilter::Info)
|
||||
.targets(vec![
|
||||
@@ -54,7 +62,7 @@ pub fn run() {
|
||||
}),
|
||||
])
|
||||
.build())
|
||||
.setup(|app| {
|
||||
.setup(move |app| {
|
||||
// TODO(bt): This is broken on windows
|
||||
// log_environment_details();
|
||||
|
||||
@@ -72,6 +80,7 @@ pub fn run() {
|
||||
let app_data_root_3 = app_data_root_2.clone();
|
||||
let app_data_root_4 = app_data_root_2.clone();
|
||||
let sora_creds_manager_3 = sora_creds_manager_2.clone();
|
||||
let storyteller_creds_manager_3 = storyteller_creds_manager.clone();
|
||||
|
||||
match MainWindowSize::from_filesystem_configs(&app_data_root_3) {
|
||||
Ok(None) => {}
|
||||
@@ -88,8 +97,8 @@ pub fn run() {
|
||||
}
|
||||
|
||||
tauri::async_runtime::spawn(sora_session_login_thread(app_2, app_data_root_2, sora_creds_manager_2));
|
||||
tauri::async_runtime::spawn(main_window_thread(app_3, app_data_root_3));
|
||||
tauri::async_runtime::spawn(sora_task_polling_thread(app_data_root_4, sora_creds_manager_3, sora_task_queue_2));
|
||||
tauri::async_runtime::spawn(main_window_thread(app_3, app_data_root_3, storyteller_creds_manager_2));
|
||||
tauri::async_runtime::spawn(sora_task_polling_thread(app_data_root_4, sora_creds_manager_3, storyteller_creds_manager_3, sora_task_queue_2));
|
||||
tauri::async_runtime::spawn(discord_presence_thread());
|
||||
|
||||
Ok(())
|
||||
@@ -101,6 +110,7 @@ pub fn run() {
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
flip_image,
|
||||
open_sora_login_command,
|
||||
platform_info_command,
|
||||
sora_image_generation_command,
|
||||
sora_image_remix_command,
|
||||
])
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
|
||||
pub struct AppStartupTime {
|
||||
startup_time: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl AppStartupTime {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
startup_time: Utc::now(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_startup_time(&self) -> DateTime<Utc> {
|
||||
self.startup_time
|
||||
}
|
||||
|
||||
pub fn time_delta_since(&self) -> TimeDelta {
|
||||
let now = Utc::now();
|
||||
now.signed_duration_since(self.startup_time)
|
||||
}
|
||||
}
|
||||
@@ -32,4 +32,12 @@ impl AppCredentialsDir {
|
||||
pub fn get_sora_sentinel_file_path(&self) -> PathBuf {
|
||||
self.path.join("sora_sentinel.txt")
|
||||
}
|
||||
|
||||
pub fn get_storyteller_avt_cookie_file_path(&self) -> PathBuf {
|
||||
self.path.join("artcraft_avt.txt")
|
||||
}
|
||||
|
||||
pub fn get_storyteller_session_cookie_file_path(&self) -> PathBuf {
|
||||
self.path.join("artcraft_session.txt")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod app_config;
|
||||
pub mod app_startup_time;
|
||||
pub mod data_dir;
|
||||
pub mod expanduser;
|
||||
pub mod main_window_size;
|
||||
|
||||
@@ -7,14 +7,18 @@ pub enum OsPlatform {
|
||||
}
|
||||
|
||||
impl OsPlatform {
|
||||
pub fn get() -> OsPlatform {
|
||||
pub fn maybe_get() -> Option<Self> {
|
||||
// Totally scientific.
|
||||
// https://doc.rust-lang.org/std/env/consts/constant.OS.html
|
||||
match std::env::consts::OS {
|
||||
"linux" => OsPlatform::Linux,
|
||||
"windows" => OsPlatform::Windows,
|
||||
"macos" | "apple" => OsPlatform::MacOs,
|
||||
_ => OsPlatform::Linux,
|
||||
"linux" => Some(Self::Linux),
|
||||
"windows" => Some(Self::Windows),
|
||||
"macos" | "apple" => Some(Self::MacOs),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get() -> Self {
|
||||
Self::maybe_get().unwrap_or(Self::Linux)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod read_storyteller_credentials_from_disk;
|
||||
pub mod storyteller_credential_holder;
|
||||
pub mod storyteller_credential_manager;
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
use crate::state::data_dir::app_data_root::AppDataRoot;
|
||||
use errors::AnyhowResult;
|
||||
use std::fs::read_to_string;
|
||||
use storyteller_client::credentials::storyteller_avt_cookie::StorytellerAvtCookie;
|
||||
use storyteller_client::credentials::storyteller_credential_set::StorytellerCredentialSet;
|
||||
use storyteller_client::credentials::storyteller_session_cookie::StorytellerSessionCookie;
|
||||
|
||||
pub fn read_storyteller_credentials_from_disk(app_data_root: &AppDataRoot) -> AnyhowResult<StorytellerCredentialSet> {
|
||||
let creds_dir= app_data_root.credentials_dir();
|
||||
|
||||
let mut avt = None;
|
||||
|
||||
{
|
||||
let avt_file = creds_dir.get_storyteller_avt_cookie_file_path();
|
||||
if avt_file.exists() {
|
||||
let contents = read_to_string(&avt_file)?
|
||||
.trim()
|
||||
.to_string();
|
||||
avt = Some(StorytellerAvtCookie::new(contents));
|
||||
}
|
||||
}
|
||||
|
||||
let mut session = None;
|
||||
|
||||
{
|
||||
let session_file = creds_dir.get_storyteller_session_cookie_file_path();
|
||||
if session_file.exists() {
|
||||
let contents = read_to_string(&session_file)?
|
||||
.trim()
|
||||
.to_string();
|
||||
session = Some(StorytellerSessionCookie::new(contents));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(StorytellerCredentialSet::initialize(
|
||||
avt,
|
||||
session,
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use anyhow::anyhow;
|
||||
use errors::AnyhowResult;
|
||||
use std::sync::{Arc, RwLock};
|
||||
use storyteller_client::credentials::storyteller_credential_set::StorytellerCredentialSet;
|
||||
|
||||
/// Hold credentials for the application.
|
||||
#[derive(Clone)]
|
||||
pub struct StorytellerCredentialHolder {
|
||||
credentials: Arc<RwLock<Option<StorytellerCredentialSet>>>,
|
||||
}
|
||||
|
||||
impl StorytellerCredentialHolder {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
credentials: Arc::new(RwLock::new(None)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_credentials(&self, credentials: &StorytellerCredentialSet) -> AnyhowResult<()> {
|
||||
match self.credentials.write() {
|
||||
Err(err) => Err(anyhow!("Failed to acquire write lock: {:?}", err)),
|
||||
Ok(mut creds) => {
|
||||
*creds = Some(credentials.clone());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_credentials(&self) -> AnyhowResult<()> {
|
||||
match self.credentials.write() {
|
||||
Err(err) => Err(anyhow!("Failed to acquire write lock: {:?}", err)),
|
||||
Ok(mut creds) => {
|
||||
*creds = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_credentials(&self) -> AnyhowResult<Option<StorytellerCredentialSet>> {
|
||||
match self.credentials.read() {
|
||||
Err(err) => Err(anyhow!("Failed to acquire read lock: {:?}", err)),
|
||||
Ok(creds) => {
|
||||
Ok(creds.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_credentials_required(&self) -> AnyhowResult<StorytellerCredentialSet> {
|
||||
match self.credentials.read() {
|
||||
Err(err) => Err(anyhow!("Failed to acquire read lock: {:?}", err)),
|
||||
Ok(creds) => match &*creds {
|
||||
None => Err(anyhow!("Credentials not set")),
|
||||
Some(creds) => Ok(creds.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
use crate::state::data_dir::app_data_root::AppDataRoot;
|
||||
use crate::state::sora::read_sora_credentials_from_disk::read_sora_credentials_from_disk;
|
||||
use crate::state::sora::sora_credential_holder::SoraCredentialHolder;
|
||||
use crate::state::storyteller::read_storyteller_credentials_from_disk::read_storyteller_credentials_from_disk;
|
||||
use crate::state::storyteller::storyteller_credential_holder::StorytellerCredentialHolder;
|
||||
use anyhow::anyhow;
|
||||
use errors::AnyhowResult;
|
||||
use log::{error, info, warn};
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
use storyteller_client::credentials::storyteller_avt_cookie::StorytellerAvtCookie;
|
||||
use storyteller_client::credentials::storyteller_credential_set::StorytellerCredentialSet;
|
||||
use storyteller_client::credentials::storyteller_session_cookie::StorytellerSessionCookie;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct StorytellerCredentialManager {
|
||||
holder: StorytellerCredentialHolder,
|
||||
app_data_root: AppDataRoot,
|
||||
}
|
||||
|
||||
impl StorytellerCredentialManager {
|
||||
|
||||
pub fn initialize_from_disk_infallible(app_data_root: &AppDataRoot) -> Self {
|
||||
let holder = StorytellerCredentialHolder::new();
|
||||
|
||||
match read_storyteller_credentials_from_disk(app_data_root) {
|
||||
Err(err) => warn!("Failed to read credentials from disk: {:?}", err),
|
||||
Ok(creds) => {
|
||||
holder.set_credentials(&creds).expect("Failed to set credentials");
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
holder,
|
||||
app_data_root: app_data_root.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_credentials(&self, creds: &StorytellerCredentialSet) -> AnyhowResult<()> {
|
||||
self.holder.set_credentials(creds)
|
||||
}
|
||||
|
||||
pub fn clear_credentials(&self) -> AnyhowResult<()> {
|
||||
self.holder.clear_credentials()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_credentials(&self) -> AnyhowResult<Option<StorytellerCredentialSet>> {
|
||||
self.holder.get_credentials()
|
||||
}
|
||||
|
||||
pub fn get_credentials_required(&self) -> AnyhowResult<StorytellerCredentialSet> {
|
||||
self.holder.get_credentials_required()
|
||||
}
|
||||
|
||||
pub fn reset_from_disk(&self) -> AnyhowResult<StorytellerCredentialSet> {
|
||||
let creds = read_storyteller_credentials_from_disk(&self.app_data_root)?;
|
||||
self.holder.set_credentials(&creds)?;
|
||||
Ok(creds)
|
||||
}
|
||||
|
||||
pub fn persist_all_to_disk(&self) -> AnyhowResult<()> {
|
||||
let credentials = self.holder.get_credentials_required()?;
|
||||
|
||||
info!("Persisting avt cookie to disk...");
|
||||
if let Some(avt) = credentials.avt.as_ref() {
|
||||
persist_avt_to_disk(&avt, &self.app_data_root)?;
|
||||
}
|
||||
|
||||
info!("Persisting session cookie to disk...");
|
||||
if let Some(session) = credentials.session.as_ref() {
|
||||
persist_session_to_disk(&session, &self.app_data_root)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn persist_session_to_disk(session: &StorytellerSessionCookie, app_data_root: &AppDataRoot) -> AnyhowResult<()> {
|
||||
let creds_dir = app_data_root.credentials_dir();
|
||||
let filename = creds_dir.get_storyteller_session_cookie_file_path();
|
||||
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.truncate(true)
|
||||
.open(filename)?;
|
||||
|
||||
file.write_all(session.as_bytes())?;
|
||||
file.flush()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn persist_avt_to_disk(avt: &StorytellerAvtCookie, app_data_root: &AppDataRoot) -> AnyhowResult<()> {
|
||||
let creds_dir = app_data_root.credentials_dir();
|
||||
let filename = creds_dir.get_storyteller_avt_cookie_file_path();
|
||||
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.truncate(true)
|
||||
.open(filename)?;
|
||||
|
||||
file.write_all(avt.as_bytes())?;
|
||||
file.flush()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
use crate::state::data_dir::app_data_root::AppDataRoot;
|
||||
use crate::state::main_window_size::MainWindowSize;
|
||||
use errors::AnyhowResult;
|
||||
use log::{error, info};
|
||||
use tauri::{AppHandle, Manager, Webview, Window};
|
||||
|
||||
const MAIN_WINDOW_NAME : &str = "main";
|
||||
|
||||
pub async fn main_window_thread(
|
||||
app: AppHandle,
|
||||
app_data_root: AppDataRoot,
|
||||
) -> ! {
|
||||
loop {
|
||||
for (window_name, window) in app.windows() {
|
||||
if window_name == MAIN_WINDOW_NAME {
|
||||
let result = handle_main_window(
|
||||
&window,
|
||||
&app_data_root,
|
||||
).await;
|
||||
if let Err(err) = result {
|
||||
error!("Error handling main window: {:?}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(1_000)).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handle_main_window(
|
||||
window: &Window,
|
||||
app_data_root: &AppDataRoot,
|
||||
) -> AnyhowResult<()> {
|
||||
let mut window_size = MainWindowSize::from_window(window)?;
|
||||
|
||||
loop {
|
||||
let old_size = window_size.to_physical_size();
|
||||
let new_size = window.inner_size()?;
|
||||
|
||||
if !window_size.matches_physical_size(&new_size) {
|
||||
info!("Window size changed from {:?} to {:?}", old_size, new_size);
|
||||
window_size = MainWindowSize::from_window(&window)?;
|
||||
info!("Saving window size configs to disk...");
|
||||
window_size.persist_to_filesystem(app_data_root)?;
|
||||
}
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10_000)).await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
use crate::state::data_dir::app_data_root::AppDataRoot;
|
||||
use crate::state::main_window_size::MainWindowSize;
|
||||
use crate::state::storyteller::storyteller_credential_manager::StorytellerCredentialManager;
|
||||
use crate::threads::main_window_thread::persist_storyteller_cookies_task::persist_storyteller_cookies_task;
|
||||
use crate::threads::main_window_thread::persist_window_resize_task::persist_window_resize_task;
|
||||
use errors::AnyhowResult;
|
||||
use log::{error, info};
|
||||
use memory_store::clone_slot::CloneSlot;
|
||||
use tauri::{AppHandle, Manager, Webview, Window};
|
||||
use crate::state::app_startup_time::AppStartupTime;
|
||||
|
||||
const MAIN_WINDOW_NAME : &str = "main";
|
||||
|
||||
pub async fn main_window_thread(
|
||||
app: AppHandle,
|
||||
app_data_root: AppDataRoot,
|
||||
storyteller_creds_manager: StorytellerCredentialManager,
|
||||
) -> ! {
|
||||
// TODO: Move these into some kind of dependency injection framework
|
||||
let window_size_slot: CloneSlot<MainWindowSize> = CloneSlot::empty();
|
||||
let app_startup_time = AppStartupTime::new();
|
||||
|
||||
loop {
|
||||
for (window_name, window) in app.windows() {
|
||||
if window_name == MAIN_WINDOW_NAME {
|
||||
let result = handle_main_window(
|
||||
&app,
|
||||
&window,
|
||||
&app_data_root,
|
||||
&storyteller_creds_manager,
|
||||
&window_size_slot,
|
||||
&app_startup_time,
|
||||
).await;
|
||||
if let Err(err) = result {
|
||||
error!("Error handling main window: {:?}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(1_000)).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handle_main_window(
|
||||
app: &AppHandle,
|
||||
window: &Window,
|
||||
app_data_root: &AppDataRoot,
|
||||
storyteller_creds_manager: &StorytellerCredentialManager,
|
||||
window_size_slot: &CloneSlot<MainWindowSize>,
|
||||
app_startup_time: &AppStartupTime,
|
||||
) -> AnyhowResult<()> {
|
||||
loop {
|
||||
log_errors(persist_window_resize_task(window, app_data_root, window_size_slot).await);
|
||||
log_errors(persist_storyteller_cookies_task(app, storyteller_creds_manager, app_startup_time).await);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(1_000)).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn log_errors<T>(result: AnyhowResult<T>) {
|
||||
if let Err(err) = result {
|
||||
error!("Error persisting window size: {:?}", err);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod main_window_thread;
|
||||
pub mod persist_storyteller_cookies_task;
|
||||
pub mod persist_window_resize_task;
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
use crate::state::app_startup_time::AppStartupTime;
|
||||
use crate::state::data_dir::app_data_root::AppDataRoot;
|
||||
use crate::state::storyteller::storyteller_credential_manager::StorytellerCredentialManager;
|
||||
use crate::threads::sora_session_login_thread::LOGIN_WINDOW_NAME;
|
||||
use anyhow::anyhow;
|
||||
use chrono::TimeDelta;
|
||||
use errors::AnyhowResult;
|
||||
use log::{debug, error, info};
|
||||
use once_cell::sync::Lazy;
|
||||
use reqwest::Url;
|
||||
use std::fs;
|
||||
use std::sync::LockResult;
|
||||
use storyteller_client::credentials::storyteller_avt_cookie::StorytellerAvtCookie;
|
||||
use storyteller_client::credentials::storyteller_credential_set::StorytellerCredentialSet;
|
||||
use storyteller_client::credentials::storyteller_session_cookie::StorytellerSessionCookie;
|
||||
use tauri::{AppHandle, Manager, Webview, Window};
|
||||
use tauri_plugin_http::reqwest_cookie_store::CookieStore;
|
||||
use tauri_plugin_http::Http;
|
||||
|
||||
const MAIN_WEBVIEW_NAME: &str = "main";
|
||||
|
||||
const STORYTELLER_ROOT_COOKIE_URL_STR: &str = "https://api.storyteller.ai/";
|
||||
|
||||
static STORYTELLER_ROOT_COOKIE_URL: Lazy<Url> = Lazy::new(|| {
|
||||
Url::parse(STORYTELLER_ROOT_COOKIE_URL_STR).expect("URL should parse")
|
||||
});
|
||||
|
||||
const AVT_COOKIE_NAME : &str = "visitor";
|
||||
const SESSION_COOKIE_NAME : &str = "session";
|
||||
|
||||
/// There's some kind of race condition that we need to wait for before inspecting cookies.
|
||||
const RACE_CONDITION_WAIT_TIME: TimeDelta = TimeDelta::milliseconds(5000);
|
||||
|
||||
pub async fn persist_storyteller_cookies_task(
|
||||
app: &AppHandle,
|
||||
storyteller_credential_manager: &StorytellerCredentialManager,
|
||||
app_startup_time: &AppStartupTime,
|
||||
) -> AnyhowResult<()> {
|
||||
|
||||
//if app_startup_time.time_delta_since() < RACE_CONDITION_WAIT_TIME {
|
||||
// // NB: There's an issue when the "main window thread" inquires about the
|
||||
// // webview cookies shortly after app startup. When it attempts to dump the
|
||||
// // cookies within a few milliseconds of app launch, it deadlocks and the
|
||||
// // app never launches correctly. The entire webview goes blank and the app
|
||||
// // freezes. This hack seems to fix the problem.
|
||||
// return Ok(())
|
||||
//}
|
||||
|
||||
let maybe_http = app.try_state::<Http>();
|
||||
|
||||
let http = match maybe_http {
|
||||
None => {
|
||||
error!("No HTTP plugin found");
|
||||
return Err(anyhow!("No HTTP plugin found"));
|
||||
}
|
||||
Some(http) => http,
|
||||
};
|
||||
|
||||
match http.cookies_jar.store.lock() {
|
||||
Err(err) => {
|
||||
error!("Failed to lock cookie jar: {:?}", err);
|
||||
return Err(anyhow!("Failed to lock cookie jar"));
|
||||
}
|
||||
Ok(cookie_jar) => {
|
||||
sync_tauri_credentials(&cookie_jar, storyteller_credential_manager)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sync_tauri_credentials(
|
||||
cookie_store: &CookieStore,
|
||||
storyteller_credential_manager: &StorytellerCredentialManager,
|
||||
) -> AnyhowResult<()> {
|
||||
let current_http_plugin_credentials = get_credentials_from_cookie_store(cookie_store)?;
|
||||
|
||||
let mut replace_credentials = true;
|
||||
|
||||
let maybe_old_credentials = storyteller_credential_manager.get_credentials()?;
|
||||
|
||||
if let Some(old_credentials) = maybe_old_credentials {
|
||||
if old_credentials.equals(¤t_http_plugin_credentials) {
|
||||
replace_credentials = false;
|
||||
}
|
||||
}
|
||||
|
||||
if replace_credentials {
|
||||
info!("Syncing ArtCraft credentials ...");
|
||||
storyteller_credential_manager.set_credentials(¤t_http_plugin_credentials)?;
|
||||
// NB: tauri-plugin-http stores the credentials on disk, so we can defer to that for now.
|
||||
//storyteller_credential_manager.persist_all_to_disk()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_credentials_from_cookie_store(cookie_jar: &CookieStore) -> AnyhowResult<StorytellerCredentialSet> {
|
||||
let mut avt_cookie = None;
|
||||
let mut session_cookie = None;
|
||||
|
||||
for cookie in cookie_jar.iter_unexpired() {
|
||||
if let Some(avt) = StorytellerAvtCookie::maybe_from_cookie(&cookie) {
|
||||
avt_cookie = Some(avt);
|
||||
} else if let Some(session) = StorytellerSessionCookie::maybe_from_cookie(&cookie) {
|
||||
session_cookie = Some(session);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(StorytellerCredentialSet::initialize(
|
||||
avt_cookie,
|
||||
session_cookie,
|
||||
))
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
use crate::state::data_dir::app_data_root::AppDataRoot;
|
||||
use crate::state::main_window_size::MainWindowSize;
|
||||
use errors::AnyhowResult;
|
||||
use log::info;
|
||||
use memory_store::clone_slot::CloneSlot;
|
||||
use tauri::Window;
|
||||
|
||||
pub async fn persist_window_resize_task(
|
||||
window: &Window,
|
||||
app_data_root: &AppDataRoot,
|
||||
window_size_slot: &CloneSlot<MainWindowSize>,
|
||||
) -> AnyhowResult<()> {
|
||||
|
||||
let current_window_size = MainWindowSize::from_window(window)?;
|
||||
let current_physical_size = window.inner_size()?;
|
||||
|
||||
let mut save_size_to_disk = true;
|
||||
|
||||
if let Ok(Some(old_size)) = window_size_slot.get_clone() {
|
||||
if old_size.matches_physical_size(¤t_physical_size) {
|
||||
save_size_to_disk = false;
|
||||
}
|
||||
}
|
||||
|
||||
if save_size_to_disk {
|
||||
info!("Saving window size configs to disk...");
|
||||
current_window_size.persist_to_filesystem(app_data_root)?;
|
||||
window_size_slot.set_clone(¤t_window_size)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::state::data_dir::app_data_root::AppDataRoot;
|
||||
use crate::state::sora::sora_credential_holder::SoraCredentialHolder;
|
||||
use crate::state::sora::sora_credential_manager::SoraCredentialManager;
|
||||
use crate::utils::cookies::sora_webview_cookies::get_all_sora_cookies_as_string;
|
||||
use crate::utils::sora::initialize_sora_jwt_bearer_token::initialize_sora_jwt_bearer_token;
|
||||
use crate::utils::sora_webview_cookies::get_all_sora_cookies_as_string;
|
||||
use anyhow::anyhow;
|
||||
use chrono::{DateTime, NaiveDateTime, TimeDelta};
|
||||
use errors::AnyhowResult;
|
||||
|
||||
@@ -1,19 +1,34 @@
|
||||
use crate::state::data_dir::app_data_root::AppDataRoot;
|
||||
use crate::state::data_dir::trait_data_subdir::DataSubdir;
|
||||
use crate::state::sora::sora_credential_manager::SoraCredentialManager;
|
||||
use crate::state::sora::sora_task_queue::SoraTaskQueue;
|
||||
use crate::state::storyteller::storyteller_credential_manager::StorytellerCredentialManager;
|
||||
use errors::AnyhowResult;
|
||||
use log::{error, info};
|
||||
use openai_sora_client::recipes::list_sora_task_status_with_session_auto_renew::{list_sora_task_status_with_session_auto_renew, StatusRequestArgs};
|
||||
use openai_sora_client::requests::image_gen::image_gen_status::{TaskId, TaskStatus};
|
||||
use openai_sora_client::requests::image_gen::image_gen_status::{Generation, TaskId, TaskStatus};
|
||||
use reqwest::Url;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use tauri::AppHandle;
|
||||
use tempdir::TempDir;
|
||||
use storyteller_client::media_files::upload_image_media_file_from_file::upload_image_media_file_from_file;
|
||||
use storyteller_client::utils::api_host::ApiHost;
|
||||
|
||||
pub async fn sora_task_polling_thread(
|
||||
app_data_root: AppDataRoot,
|
||||
sora_creds_manager: SoraCredentialManager,
|
||||
storyteller_creds_manager: StorytellerCredentialManager,
|
||||
sora_task_queue: SoraTaskQueue,
|
||||
) -> ! {
|
||||
loop {
|
||||
let res = polling_loop(&sora_creds_manager, &sora_task_queue).await;
|
||||
let res = polling_loop(
|
||||
&sora_creds_manager,
|
||||
&storyteller_creds_manager,
|
||||
&sora_task_queue,
|
||||
&app_data_root,
|
||||
).await;
|
||||
if let Err(err) = res {
|
||||
error!("An error occurred: {:?}", err);
|
||||
}
|
||||
@@ -23,7 +38,9 @@ pub async fn sora_task_polling_thread(
|
||||
|
||||
async fn polling_loop(
|
||||
sora_creds_manager: &SoraCredentialManager,
|
||||
storyteller_creds_manager: &StorytellerCredentialManager,
|
||||
sora_task_queue: &SoraTaskQueue,
|
||||
app_data_root: &AppDataRoot,
|
||||
) -> AnyhowResult<()> {
|
||||
loop {
|
||||
if sora_task_queue.is_empty()? {
|
||||
@@ -74,8 +91,26 @@ async fn polling_loop(
|
||||
.collect();
|
||||
|
||||
sora_task_queue.remove_list(&failed_task_ids)?;
|
||||
|
||||
let creds = storyteller_creds_manager.get_credentials_required()?;
|
||||
let api_host = ApiHost::Storyteller;
|
||||
|
||||
// TODO: Handle succeeded tasks.
|
||||
for task in succeeded_tasks.iter() {
|
||||
if !sora_task_queue.contains_key(&task.id)? {
|
||||
continue;
|
||||
}
|
||||
info!("Task succeeded: {:?}", task.id);
|
||||
|
||||
for (i, generation) in task.generations.iter().enumerate() {
|
||||
info!("Downloading generated file...");
|
||||
let download_path = download_generation(generation, &app_data_root).await?;
|
||||
|
||||
info!("Uploading to backend...");
|
||||
let result = upload_image_media_file_from_file(&api_host, Some(&creds), download_path).await?;
|
||||
|
||||
info!("Uploaded to API backend: {:?}", result.media_file_token);
|
||||
}
|
||||
}
|
||||
|
||||
let succeeded_task_ids : Vec<&TaskId> = succeeded_tasks
|
||||
.iter()
|
||||
@@ -87,3 +122,21 @@ async fn polling_loop(
|
||||
tokio::time::sleep(std::time::Duration::from_millis(2_000)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn download_generation(generation: &Generation, app_data_root: &AppDataRoot) -> AnyhowResult<PathBuf> {
|
||||
let url = Url::parse(&generation.url)?;
|
||||
|
||||
let response = reqwest::get(&generation.url).await?;
|
||||
let image_bytes = response.bytes().await?;
|
||||
|
||||
let ext = url.path().split(".").last().unwrap_or("png");
|
||||
|
||||
let tempdir = app_data_root.temp_dir().path();
|
||||
let download_filename = format!("{}.{}", generation.id, ext);
|
||||
let download_path = tempdir.join(download_filename);
|
||||
|
||||
let mut file = File::create(&download_path)?;
|
||||
file.write_all(&image_bytes)?;
|
||||
|
||||
Ok(download_path)
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
pub mod sora_webview_cookies;
|
||||
@@ -1,7 +1,8 @@
|
||||
pub mod clear_all_webview_cookies;
|
||||
pub mod cookies;
|
||||
pub mod get_url_file_extension;
|
||||
pub mod image;
|
||||
pub mod large_file_transfer;
|
||||
pub mod object_store;
|
||||
pub mod simple_http_download;
|
||||
pub mod sora;
|
||||
pub mod sora_webview_cookies;
|
||||
@@ -0,0 +1,5 @@
|
||||
# For some reason, we can't pass json files to the tauri dev command
|
||||
[build]
|
||||
frontendDist = "../../../frontend/apps/editor2d/dist"
|
||||
beforeDevCommand = "echo 'no dev'"
|
||||
devUrl = "http://localhost:5741"
|
||||
@@ -20,7 +20,11 @@
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
"csp": null,
|
||||
"headers": {
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
"Cross-Origin-Embedder-Policy": "require-corp"
|
||||
}
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
|
||||
@@ -20,11 +20,13 @@ workspace-build-acceleration = { workspace = true }
|
||||
enums = { workspace = true }
|
||||
enums_public = { workspace = true }
|
||||
errors = { workspace = true }
|
||||
idempotency = { workspace = true }
|
||||
tokens = { workspace = true }
|
||||
|
||||
# External
|
||||
anyhow = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
cookie = { workspace = true }
|
||||
log = { workspace = true }
|
||||
reqwest = { workspace = true, features = ["multipart", "gzip"] }
|
||||
url = { workspace = true }
|
||||
@@ -35,7 +37,8 @@ serde_derive = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
# HTTP
|
||||
backoff = { version = "0.4.0", features = ["futures"] } # Exponential backoff retry
|
||||
backoff = { version = "0.4.0", features = ["futures"] }
|
||||
uuid = { version = "1.8.0", features = ["v4"] } # Exponential backoff retry
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.38.0", features = ["macros"] }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::error::Error;
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::io;
|
||||
use errors::AnyhowError;
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -33,6 +34,9 @@ pub enum ApiError {
|
||||
|
||||
/// Uncategorized reqwest error.
|
||||
OtherReqwestError(reqwest::Error),
|
||||
|
||||
/// An error doing file I/O (on our side)
|
||||
IoError(io::Error),
|
||||
|
||||
/// Another type of error.
|
||||
Other(AnyhowError),
|
||||
@@ -55,6 +59,8 @@ impl Display for ApiError {
|
||||
// Network errors
|
||||
ApiError::Timeout(msg) => write!(f, "Timeout: {}", msg),
|
||||
ApiError::NetworkError(msg) => write!(f, "Network error: {}", msg),
|
||||
// I/O errors
|
||||
ApiError::IoError(error) => write!(f, "IO error: {}", error),
|
||||
// Other
|
||||
ApiError::OtherReqwestError(error) => write!(f, "Reqwest error: {}", error),
|
||||
ApiError::Other(error) => write!(f, "Other error: {}", error),
|
||||
@@ -79,3 +85,9 @@ impl From<serde_json::Error> for ApiError {
|
||||
ApiError::DeserializationError(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<io::Error> for ApiError {
|
||||
fn from(error: io::Error) -> Self {
|
||||
ApiError::IoError(error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
use cookie::Cookie;
|
||||
|
||||
const AVT_COOKIE_NAME : &str = "visitor";
|
||||
|
||||
/// The "anonymous visitor token" cookie allows users to interact with
|
||||
/// the service in a logged-out state with some continuity.
|
||||
@@ -11,6 +14,14 @@ impl StorytellerAvtCookie {
|
||||
Self { cookie }
|
||||
}
|
||||
|
||||
pub fn maybe_from_cookie(cookie: &Cookie) -> Option<Self> {
|
||||
if cookie.name() == AVT_COOKIE_NAME {
|
||||
Some(Self::new(cookie.value().to_string()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.cookie
|
||||
}
|
||||
@@ -22,4 +33,12 @@ impl StorytellerAvtCookie {
|
||||
pub fn to_string(&self) -> String {
|
||||
self.cookie.clone()
|
||||
}
|
||||
|
||||
pub fn equals(&self, other: &Self) -> bool {
|
||||
self.cookie == other.cookie
|
||||
}
|
||||
|
||||
pub fn as_cookie_header(&self) -> String {
|
||||
format!("{}={}", AVT_COOKIE_NAME, self.cookie)
|
||||
}
|
||||
}
|
||||
|
||||
+111
-6
@@ -3,29 +3,134 @@ use crate::credentials::storyteller_session_cookie::StorytellerSessionCookie;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct StorytellerCredentialSet {
|
||||
pub cookie: Option<StorytellerSessionCookie>,
|
||||
pub avt: Option<StorytellerAvtCookie>,
|
||||
pub session: Option<StorytellerSessionCookie>,
|
||||
}
|
||||
|
||||
impl StorytellerCredentialSet {
|
||||
pub fn empty() -> Self {
|
||||
Self {
|
||||
avt: None,
|
||||
session: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn initialize(
|
||||
cookie: Option<StorytellerSessionCookie>,
|
||||
avt: Option<StorytellerAvtCookie>,
|
||||
session: Option<StorytellerSessionCookie>,
|
||||
) -> Self {
|
||||
Self { cookie, avt }
|
||||
Self {
|
||||
avt,
|
||||
session,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn initialize_with_just_cookie(cookie: StorytellerSessionCookie) -> Self {
|
||||
pub fn initialize_with_just_cookie(session: StorytellerSessionCookie) -> Self {
|
||||
Self {
|
||||
cookie: Some(cookie),
|
||||
avt: None,
|
||||
session: Some(session),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn initialize_with_just_avt(avt: StorytellerAvtCookie) -> Self {
|
||||
Self {
|
||||
cookie: None,
|
||||
avt: Some(avt),
|
||||
session: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.avt.is_none() && self.session.is_none()
|
||||
}
|
||||
|
||||
pub fn equals(&self, other: &Self) -> bool {
|
||||
match (&self.avt, &other.avt) {
|
||||
(None, None) => {} // Fallthrough
|
||||
(Some(avt), Some(other_avt)) => {
|
||||
if !avt.equals(other_avt) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
|
||||
match (&self.session, &other.session) {
|
||||
(None, None) => {} // Fallthrough
|
||||
(Some(session), Some(other_session)) => {
|
||||
if !session.equals(other_session) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
pub fn maybe_as_cookie_header(&self) -> Option<String> {
|
||||
let mut cookies = Vec::new();
|
||||
|
||||
if let Some(avt) = &self.avt {
|
||||
cookies.push(avt.as_cookie_header());
|
||||
}
|
||||
|
||||
if let Some(session) = &self.session {
|
||||
cookies.push(session.as_cookie_header());
|
||||
}
|
||||
|
||||
if cookies.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(cookies.join("; "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::credentials::storyteller_avt_cookie::StorytellerAvtCookie;
|
||||
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
|
||||
use crate::credentials::storyteller_session_cookie::StorytellerSessionCookie;
|
||||
|
||||
mod cookies_header {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn no_cookie() {
|
||||
let creds = StorytellerCredentialSet::empty();
|
||||
let header = creds.maybe_as_cookie_header();
|
||||
assert_eq!(header, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn avt_cookies_header() {
|
||||
let creds = StorytellerCredentialSet::initialize_with_just_avt(
|
||||
StorytellerAvtCookie::new("bob".to_string()),
|
||||
);
|
||||
|
||||
let header = creds.maybe_as_cookie_header();
|
||||
assert_eq!(header, Some("visitor=bob".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_cookies_header() {
|
||||
let creds = StorytellerCredentialSet::initialize_with_just_cookie(
|
||||
StorytellerSessionCookie::new("bob".to_string()),
|
||||
);
|
||||
|
||||
let header = creds.maybe_as_cookie_header();
|
||||
assert_eq!(header, Some("session=bob".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_cookies_header() {
|
||||
let creds = StorytellerCredentialSet::initialize(
|
||||
Some(StorytellerAvtCookie::new("bob".to_string())),
|
||||
Some(StorytellerSessionCookie::new("alice".to_string())),
|
||||
);
|
||||
|
||||
let header = creds.maybe_as_cookie_header();
|
||||
assert_eq!(header, Some("visitor=bob; session=alice".to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+19
@@ -1,3 +1,6 @@
|
||||
use cookie::Cookie;
|
||||
|
||||
const SESSION_COOKIE_NAME : &str = "session";
|
||||
|
||||
/// The primary FakeYou / Storyteller / Artcraft backend session identifier.
|
||||
#[derive(Clone)]
|
||||
@@ -9,6 +12,14 @@ impl StorytellerSessionCookie {
|
||||
pub fn new(cookie: String) -> Self {
|
||||
Self { cookie }
|
||||
}
|
||||
|
||||
pub fn maybe_from_cookie(cookie: &Cookie) -> Option<Self> {
|
||||
if cookie.name() == SESSION_COOKIE_NAME {
|
||||
Some(Self::new(cookie.value().to_string()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.cookie
|
||||
@@ -21,4 +32,12 @@ impl StorytellerSessionCookie {
|
||||
pub fn to_string(&self) -> String {
|
||||
self.cookie.clone()
|
||||
}
|
||||
|
||||
pub fn equals(&self, other: &Self) -> bool {
|
||||
self.cookie == other.cookie
|
||||
}
|
||||
|
||||
pub fn as_cookie_header(&self) -> String {
|
||||
format!("{}={}", SESSION_COOKIE_NAME, self.cookie)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,3 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use log::debug;
|
||||
use serde_derive::{Deserialize};
|
||||
use enums::by_table::media_files::media_file_animation_type::MediaFileAnimationType;
|
||||
use enums::by_table::media_files::media_file_class::MediaFileClass;
|
||||
use enums::by_table::media_files::media_file_engine_category::MediaFileEngineCategory;
|
||||
use enums::by_table::media_files::media_file_type::MediaFileType;
|
||||
use enums::by_table::model_weights::weights_category::WeightsCategory;
|
||||
use enums::common::visibility::Visibility;
|
||||
use enums::no_table::style_transfer::style_transfer_name::StyleTransferName;
|
||||
use enums_public::by_table::model_weights::public_weights_types::PublicWeightsType;
|
||||
use tokens::tokens::batch_generations::BatchGenerationToken;
|
||||
use tokens::tokens::media_files::MediaFileToken;
|
||||
use tokens::tokens::model_weights::ModelWeightToken;
|
||||
use tokens::tokens::prompts::PromptToken;
|
||||
use crate::api_error::ApiError;
|
||||
use crate::shared_response_types::media_file_cover_image_details::MediaFileCoverImageDetails;
|
||||
use crate::shared_response_types::media_links::MediaLinks;
|
||||
@@ -21,6 +6,21 @@ use crate::shared_response_types::user_details_light::UserDetailsLight;
|
||||
use crate::utils::api_host::ApiHost;
|
||||
use crate::utils::filter_bad_response::filter_bad_response;
|
||||
use crate::utils::http_get_anonymous::http_get_anonymous;
|
||||
use chrono::{DateTime, Utc};
|
||||
use enums::by_table::media_files::media_file_animation_type::MediaFileAnimationType;
|
||||
use enums::by_table::media_files::media_file_class::MediaFileClass;
|
||||
use enums::by_table::media_files::media_file_engine_category::MediaFileEngineCategory;
|
||||
use enums::by_table::media_files::media_file_type::MediaFileType;
|
||||
use enums::by_table::model_weights::weights_category::WeightsCategory;
|
||||
use enums::common::visibility::Visibility;
|
||||
use enums::no_table::style_transfer::style_transfer_name::StyleTransferName;
|
||||
use enums_public::by_table::model_weights::public_weights_types::PublicWeightsType;
|
||||
use log::debug;
|
||||
use serde_derive::Deserialize;
|
||||
use tokens::tokens::batch_generations::BatchGenerationToken;
|
||||
use tokens::tokens::media_files::MediaFileToken;
|
||||
use tokens::tokens::model_weights::ModelWeightToken;
|
||||
use tokens::tokens::prompts::PromptToken;
|
||||
|
||||
/// Get details about a media file from our backend
|
||||
pub async fn get_media_file(api_host: &ApiHost, media_file_token: &MediaFileToken) -> Result<GetMediaFileSuccessResponse, ApiError> {
|
||||
@@ -205,9 +205,9 @@ pub struct GetMediaFileModelInfo {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tokens::tokens::media_files::MediaFileToken;
|
||||
use crate::media_files::get_media_file::get_media_file;
|
||||
use crate::utils::api_host::ApiHost;
|
||||
use tokens::tokens::media_files::MediaFileToken;
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore] // Don't run in CI. Requires valid cookie
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
pub mod get_media_file;
|
||||
pub mod get_media_file;
|
||||
pub mod upload_image_media_file_from_file;
|
||||
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
use crate::api_error::ApiError;
|
||||
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
|
||||
use crate::shared_response_types::media_file_cover_image_details::MediaFileCoverImageDetails;
|
||||
use crate::shared_response_types::media_links::MediaLinks;
|
||||
use crate::shared_response_types::simple_entity_stats::SimpleEntityStats;
|
||||
use crate::shared_response_types::user_details_light::UserDetailsLight;
|
||||
use crate::utils::api_host::ApiHost;
|
||||
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
|
||||
use crate::utils::filter_bad_response::filter_bad_response;
|
||||
use crate::utils::http_get_anonymous::http_get_anonymous;
|
||||
use chrono::{DateTime, Utc};
|
||||
use enums::by_table::media_files::media_file_animation_type::MediaFileAnimationType;
|
||||
use enums::by_table::media_files::media_file_class::MediaFileClass;
|
||||
use enums::by_table::media_files::media_file_engine_category::MediaFileEngineCategory;
|
||||
use enums::by_table::media_files::media_file_type::MediaFileType;
|
||||
use enums::by_table::model_weights::weights_category::WeightsCategory;
|
||||
use enums::common::visibility::Visibility;
|
||||
use enums::no_table::style_transfer::style_transfer_name::StyleTransferName;
|
||||
use enums_public::by_table::model_weights::public_weights_types::PublicWeightsType;
|
||||
use idempotency::uuid::generate_random_uuid;
|
||||
use log::debug;
|
||||
use reqwest::multipart::Form;
|
||||
use reqwest::Client;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use tokens::tokens::batch_generations::BatchGenerationToken;
|
||||
use tokens::tokens::media_files::MediaFileToken;
|
||||
use tokens::tokens::model_weights::ModelWeightToken;
|
||||
use tokens::tokens::prompts::PromptToken;
|
||||
use uuid::uuid;
|
||||
|
||||
/// Upload an image media file from a file.
|
||||
pub async fn upload_image_media_file_from_file<P: AsRef<Path>>(
|
||||
api_host: &ApiHost,
|
||||
maybe_creds: Option<&StorytellerCredentialSet>,
|
||||
path: P,
|
||||
) -> Result<UploadImageMediaFileSuccessResponse, ApiError> {
|
||||
|
||||
let url = get_route(api_host);
|
||||
|
||||
debug!("Requesting {:?}", &url);
|
||||
|
||||
//let mut file = File::open(path)?;
|
||||
|
||||
let client = Client::builder()
|
||||
.gzip(true)
|
||||
.build()?;
|
||||
|
||||
let form = Form::new()
|
||||
.text("uuid_idempotency_token", generate_random_uuid())
|
||||
.file("file", path)
|
||||
.await?;
|
||||
|
||||
let mut request_builder = client.post(url)
|
||||
.header("User-Agent", USER_AGENT)
|
||||
.header("Accept", APPLICATION_JSON);
|
||||
|
||||
if let Some(creds) = maybe_creds {
|
||||
if let Some(header) = &creds.maybe_as_cookie_header() {
|
||||
request_builder = request_builder.header("Cookie", header);
|
||||
}
|
||||
}
|
||||
|
||||
let response = request_builder
|
||||
.multipart(form)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let response = filter_bad_response(response).await?;
|
||||
let response_body = &response.text().await?;
|
||||
|
||||
let media_file = serde_json::from_str(&response_body)?;
|
||||
|
||||
Ok(media_file)
|
||||
}
|
||||
|
||||
fn get_route(api_host: &ApiHost) -> String {
|
||||
let api_hostname = api_host.to_api_hostname();
|
||||
format!("https://{}/v1/media_files/upload/image", api_hostname)
|
||||
}
|
||||
|
||||
// TODO(bt,2025-04-22): Share API definitions between client and server in common crate.
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct UploadImageMediaFileSuccessResponse {
|
||||
pub success: bool,
|
||||
pub media_file_token: MediaFileToken,
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
|
||||
pub const USER_AGENT: &str = "storyteller-client/1.0";
|
||||
|
||||
pub const APPLICATION_JSON : &str = "application/json";
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod api_host;
|
||||
pub mod constants;
|
||||
pub mod filter_bad_response;
|
||||
pub mod http_get_anonymous;
|
||||
pub mod status_codes;
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "memory_store"
|
||||
edition = "2018"
|
||||
version = "0.0.1"
|
||||
authors = [
|
||||
"Brandon Thomas <bt@brand.io>",
|
||||
"Brandon Thomas <echelon@gmail.com>",
|
||||
]
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
name = "memory_store"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[package.metadata.cargo-udeps.ignore]
|
||||
normal = ["workspace-build-acceleration"]
|
||||
|
||||
[dependencies]
|
||||
# Workspace hack (faster compile times)
|
||||
workspace-build-acceleration = { workspace = true }
|
||||
|
||||
# Internal
|
||||
errors = { workspace = true }
|
||||
|
||||
# External
|
||||
anyhow = { workspace = true }
|
||||
@@ -0,0 +1,54 @@
|
||||
use anyhow::anyhow;
|
||||
use errors::AnyhowResult;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
/// Store a threadsafe value that can be passed around and cloned.
|
||||
/// The object is interior mutable so it can be changed without mut/&mut references.
|
||||
/// This is useful for storing a value that may or may not be set between threads.
|
||||
///
|
||||
/// Unlike `CloneSlot`, this always holds an object.
|
||||
#[derive(Clone)]
|
||||
pub struct CloneCell<T: Clone> {
|
||||
pub store: Arc<RwLock<T>>,
|
||||
}
|
||||
|
||||
impl <T: Clone> CloneCell<T> {
|
||||
pub fn with_clone(object: &T) -> Self {
|
||||
Self {
|
||||
store: Arc::new(RwLock::new(object.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_owned(object: T) -> Self {
|
||||
Self {
|
||||
store: Arc::new(RwLock::new(object)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_clone(&self) -> AnyhowResult<T> {
|
||||
match self.store.read() {
|
||||
Err(err) => Err(anyhow!("Failed to acquire read lock: {:?}", err)),
|
||||
Ok(store) => Ok(store.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_clone(&self, value: &T) -> AnyhowResult<()> {
|
||||
match self.store.write() {
|
||||
Err(err) => Err(anyhow!("Failed to acquire write lock: {:?}", err)),
|
||||
Ok(mut store) => {
|
||||
*store = value.clone();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_owned(&self, value: T) -> AnyhowResult<()> {
|
||||
match self.store.write() {
|
||||
Err(err) => Err(anyhow!("Failed to acquire write lock: {:?}", err)),
|
||||
Ok(mut store) => {
|
||||
*store = value;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use anyhow::anyhow;
|
||||
use errors::AnyhowResult;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
/// Store a threadsafe value that can be passed around and cloned.
|
||||
/// The object is interior mutable so it can be changed without mut/&mut references.
|
||||
/// This is useful for storing a value that may or may not be set between threads.
|
||||
///
|
||||
/// Unlike `CloneCell`, this holds an optional object.
|
||||
#[derive(Clone)]
|
||||
pub struct CloneSlot<T: Clone> {
|
||||
pub store: Arc<RwLock<Option<T>>>,
|
||||
}
|
||||
|
||||
impl <T: Clone> CloneSlot<T> {
|
||||
pub fn empty() -> Self {
|
||||
Self {
|
||||
store: Arc::new(RwLock::new(None)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_clone(object: &T) -> Self {
|
||||
Self {
|
||||
store: Arc::new(RwLock::new(Some(object.clone()))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_clone(&self) -> AnyhowResult<Option<T>> {
|
||||
match self.store.read() {
|
||||
Err(err) => Err(anyhow!("Failed to acquire read lock: {:?}", err)),
|
||||
Ok(store) => Ok(store.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_clone(&self, value: &T) -> AnyhowResult<()> {
|
||||
match self.store.write() {
|
||||
Err(err) => Err(anyhow!("Failed to acquire write lock: {:?}", err)),
|
||||
Ok(mut store) => {
|
||||
*store = Some(value.clone());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear(&self) -> AnyhowResult<()> {
|
||||
match self.store.write() {
|
||||
Err(err) => Err(anyhow!("Failed to acquire write lock: {:?}", err)),
|
||||
Ok(mut store) => {
|
||||
*store = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take(&self) -> AnyhowResult<Option<T>> {
|
||||
match self.store.write() {
|
||||
Err(err) => Err(anyhow!("Failed to acquire write lock: {:?}", err)),
|
||||
Ok(mut store) => {
|
||||
Ok(store.take())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_some(&self) -> AnyhowResult<bool> {
|
||||
match self.store.read() {
|
||||
Err(err) => Err(anyhow!("Failed to acquire read lock: {:?}", err)),
|
||||
Ok(store) => Ok(store.is_some()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_none(&self) -> AnyhowResult<bool> {
|
||||
match self.store.read() {
|
||||
Err(err) => Err(anyhow!("Failed to acquire read lock: {:?}", err)),
|
||||
Ok(store) => Ok(store.is_none()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod clone_cell;
|
||||
pub mod clone_slot;
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
# Changelog
|
||||
|
||||
## \[2.4.3]
|
||||
|
||||
- [`37c0477a`](https://github.com/tauri-apps/plugins-workspace/commit/37c0477afe926d326573f1827045875ce8bf8187) ([#2561](https://github.com/tauri-apps/plugins-workspace/pull/2561)) Add `zstd` cargo feature flag to enable `reqwest/zstd` flag.
|
||||
- [`9ebbfb2e`](https://github.com/tauri-apps/plugins-workspace/commit/9ebbfb2e3ccef8e0f277a0c02fe6b399b41feeb6) ([#1978](https://github.com/tauri-apps/plugins-workspace/pull/1978)) Persist cookies to disk and load it on next app start.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs-js@2.2.1`
|
||||
|
||||
## \[2.4.2]
|
||||
|
||||
- [`a15eedf3`](https://github.com/tauri-apps/plugins-workspace/commit/a15eedf37854344f7ffbcb0d373d848563817011) ([#2535](https://github.com/tauri-apps/plugins-workspace/pull/2535) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix `fetch` occasionally throwing an error due to trying to close the underline stream twice.
|
||||
|
||||
## \[2.4.1]
|
||||
|
||||
- [`d3183aa9`](https://github.com/tauri-apps/plugins-workspace/commit/d3183aa99da7ca67e627394132ddeb3b85ccef06) ([#2522](https://github.com/tauri-apps/plugins-workspace/pull/2522) by [@adrieljss](https://github.com/tauri-apps/plugins-workspace/../../adrieljss)) Fix `fetch` blocking until the whole response is read even if it was a streaming response.
|
||||
|
||||
## \[2.4.0]
|
||||
|
||||
- [`cb38f54f`](https://github.com/tauri-apps/plugins-workspace/commit/cb38f54f4a4ef30995283cd82166c62da17bac44) ([#2479](https://github.com/tauri-apps/plugins-workspace/pull/2479) by [@adrieljss](https://github.com/tauri-apps/plugins-workspace/../../adrieljss)) Add stream support for HTTP stream responses.
|
||||
|
||||
## \[2.3.0]
|
||||
|
||||
- [`10513649`](https://github.com/tauri-apps/plugins-workspace/commit/105136494c5a5bf4b1f1cc06cc71815412d17ec8) ([#2204](https://github.com/tauri-apps/plugins-workspace/pull/2204) by [@RickeyWard](https://github.com/tauri-apps/plugins-workspace/../../RickeyWard)) Add `dangerous-settings` feature flag and new JS `danger` option to disable tls hostname/certificate validation.
|
||||
|
||||
## \[2.2.0]
|
||||
|
||||
- [`3a79266b`](https://github.com/tauri-apps/plugins-workspace/commit/3a79266b8cf96a55b1ae6339d725567d45a44b1d) ([#2173](https://github.com/tauri-apps/plugins-workspace/pull/2173) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Bumped all plugins to `v2.2.0`. From now, the versions for the Rust and JavaScript packages of each plugin will be in sync with each other.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.2.0`
|
||||
|
||||
## \[2.0.2]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs-js@2.0.4`
|
||||
|
||||
## \[2.0.4]
|
||||
|
||||
- [`a3b553dd`](https://github.com/tauri-apps/plugins-workspace/commit/a3b553ddb403771aa699362c4e69a064b7731da5) ([#2079](https://github.com/tauri-apps/plugins-workspace/pull/2079) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Add tracing logs for requestes and responses behind `tracing` feature flag.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.1.0`
|
||||
|
||||
## \[2.0.3]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.3`
|
||||
|
||||
## \[2.0.1]
|
||||
|
||||
- [`cfd48b3b`](https://github.com/tauri-apps/plugins-workspace/commit/cfd48b3b2ec0fccfc162197518694ed59ceda22c) ([#1941](https://github.com/tauri-apps/plugins-workspace/pull/1941) by [@Nipsuli](https://github.com/tauri-apps/plugins-workspace/../../Nipsuli)) Allow skipping sending `Origin` header in HTTP requests by setting `Origin` header to an empty string when calling `fetch`.
|
||||
- [`9b2840db`](https://github.com/tauri-apps/plugins-workspace/commit/9b2840db9464cf08db75806270e4441f0af81e5d) ([#1884](https://github.com/tauri-apps/plugins-workspace/pull/1884) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Retain headers order.
|
||||
|
||||
## \[2.0.1]
|
||||
|
||||
- [`a1a82208`](https://github.com/tauri-apps/plugins-workspace/commit/a1a82208ed4ab87f83310be0dc95428aec9ab241) ([#1873](https://github.com/tauri-apps/plugins-workspace/pull/1873) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Downgrade MSRV to 1.77.2 to support Windows 7.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.1`
|
||||
|
||||
## \[2.0.0]
|
||||
|
||||
- [`e2c4dfb6`](https://github.com/tauri-apps/plugins-workspace/commit/e2c4dfb6af43e5dd8d9ceba232c315f5febd55c1) Update to tauri v2 stable release.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0`
|
||||
|
||||
## \[2.0.0-rc.6]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-rc.6`
|
||||
|
||||
## \[2.0.0-rc.5]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-rc.5`
|
||||
|
||||
## \[2.0.0-rc.4]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-rc.4`
|
||||
|
||||
## \[2.0.0-rc.3]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-rc.3`
|
||||
|
||||
## \[2.0.0-rc.2]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-rc.2`
|
||||
|
||||
## \[2.0.0-rc.2]
|
||||
|
||||
- [`e2e97db5`](https://github.com/tauri-apps/plugins-workspace/commit/e2e97db51983267f5be84d4f6f0278d58834d1f5) ([#1701](https://github.com/tauri-apps/plugins-workspace/pull/1701) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri 2.0.0-rc.8
|
||||
|
||||
## \[2.0.0-rc.1]
|
||||
|
||||
- [`84f8bd5e`](https://github.com/tauri-apps/plugins-workspace/commit/84f8bd5e1ef22e664267380b5bbf756ebc5389c3) ([#1662](https://github.com/tauri-apps/plugins-workspace/pull/1662) by [@twlite](https://github.com/tauri-apps/plugins-workspace/../../twlite)) Fixed an issue with abort signal not aborting the fetch request.
|
||||
|
||||
## \[2.0.0-rc.0]
|
||||
|
||||
- [`9887d1`](https://github.com/tauri-apps/plugins-workspace/commit/9887d14bd0e971c4c0f5c1188fc4005d3fc2e29e) Update to tauri RC.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-rc.0`
|
||||
|
||||
## \[2.0.0-beta.9]
|
||||
|
||||
- [`99d6ac0f`](https://github.com/tauri-apps/plugins-workspace/commit/99d6ac0f9506a6a4a1aa59c728157190a7441af6) ([#1606](https://github.com/tauri-apps/plugins-workspace/pull/1606) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) The JS packages now specify the *minimum* `@tauri-apps/api` version instead of a single exact version.
|
||||
- [`6de87966`](https://github.com/tauri-apps/plugins-workspace/commit/6de87966ecc00ad9d91c25be452f1f46bd2b7e1f) ([#1597](https://github.com/tauri-apps/plugins-workspace/pull/1597) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Update to tauri beta.25.
|
||||
|
||||
## \[2.0.0-beta.8]
|
||||
|
||||
- [`ac9a25cc`](https://github.com/tauri-apps/plugins-workspace/commit/ac9a25cc12ee2b325f00212ba74316da3369bde5) ([#1395](https://github.com/tauri-apps/plugins-workspace/pull/1395) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix cancelling requests using `AbortSignal`.
|
||||
- [`a6654932`](https://github.com/tauri-apps/plugins-workspace/commit/a66549329c60dea35e3a06a38c357e368c9053a1) ([#1526](https://github.com/tauri-apps/plugins-workspace/pull/1526) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix missing `Set-Cookie` headers in the response which meant `request.headers.getSetCookie()` always returned empty array.
|
||||
- [`22a17980`](https://github.com/tauri-apps/plugins-workspace/commit/22a17980ff4f6f8c40adb1b8f4ffc6dae2fe7e30) ([#1537](https://github.com/tauri-apps/plugins-workspace/pull/1537) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri beta.24.
|
||||
|
||||
## \[2.0.0-beta.7]
|
||||
|
||||
- [`76daee7a`](https://github.com/tauri-apps/plugins-workspace/commit/76daee7aafece34de3092c86e531cf9eb1138989) ([#1512](https://github.com/tauri-apps/plugins-workspace/pull/1512) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Update to tauri beta.23.
|
||||
|
||||
## \[2.0.0-beta.6]
|
||||
|
||||
- [`0f739dbc`](https://github.com/tauri-apps/plugins-workspace/commit/0f739dbc483a1f091977cbe575c3862fd39f8cf1) ([#1392](https://github.com/tauri-apps/plugins-workspace/pull/1392) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Allow setting `Origin` header when `unsafe-headers` feature flag is active.
|
||||
|
||||
## \[2.0.0-beta.5]
|
||||
|
||||
- [`9013854f`](https://github.com/tauri-apps/plugins-workspace/commit/9013854f42a49a230b9dbb9d02774765528a923f)([#1382](https://github.com/tauri-apps/plugins-workspace/pull/1382)) Update to tauri beta.22.
|
||||
|
||||
## \[2.0.0-beta.4]
|
||||
|
||||
- [`9d7ae45b`](https://github.com/tauri-apps/plugins-workspace/commit/9d7ae45b0edf9b22c73e7d7c413a784bb35c3d77)([#1354](https://github.com/tauri-apps/plugins-workspace/pull/1354)) Include headers created by browser if not declared by user, which fixes missing headers like `Content-Type` when using `FormData`.
|
||||
- [`430bd6f4`](https://github.com/tauri-apps/plugins-workspace/commit/430bd6f4f379bee5d232ae6b098ae131db7f178a)([#1363](https://github.com/tauri-apps/plugins-workspace/pull/1363)) Update to tauri beta.20.
|
||||
|
||||
## \[2.0.0-beta.3]
|
||||
|
||||
- [`bd1ed590`](https://github.com/tauri-apps/plugins-workspace/commit/bd1ed5903ffcce5500310dac1e59e8c67674ef1e)([#1237](https://github.com/tauri-apps/plugins-workspace/pull/1237)) Update to tauri beta.17.
|
||||
|
||||
## \[2.0.0-beta.6]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-beta.6`
|
||||
|
||||
## \[2.0.0-beta.5]
|
||||
|
||||
- [`500ff10`](https://github.com/tauri-apps/plugins-workspace/commit/500ff10fbd89fdfc73caf9d153029dad567b4ff1)([#1166](https://github.com/tauri-apps/plugins-workspace/pull/1166)) **Breaking change:** Removed the `default-tls` feature flag. The `rustls-tls`, `http2`, `macos-system-configuration`, and `charset` feature flags are now enabled by default.
|
||||
- [`e3d41f4`](https://github.com/tauri-apps/plugins-workspace/commit/e3d41f4011bd3ea3ce281bb38bbe31d3709f8e0f)([#1191](https://github.com/tauri-apps/plugins-workspace/pull/1191)) Internally use the webview scoped resources table instead of the app one, so other webviews can't access other webviews resources.
|
||||
- [`7e2fcc5`](https://github.com/tauri-apps/plugins-workspace/commit/7e2fcc5e74df7c3c718e40f75bfb0eafc7d69d8d)([#1146](https://github.com/tauri-apps/plugins-workspace/pull/1146)) Update dependencies to align with tauri 2.0.0-beta.14.
|
||||
- [`e3d41f4`](https://github.com/tauri-apps/plugins-workspace/commit/e3d41f4011bd3ea3ce281bb38bbe31d3709f8e0f)([#1191](https://github.com/tauri-apps/plugins-workspace/pull/1191)) Update for tauri 2.0.0-beta.15.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-beta.5`
|
||||
|
||||
## \[2.0.0-beta.4]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-beta.4`
|
||||
|
||||
## \[2.0.0-beta.3]
|
||||
|
||||
- [`c873e4d`](https://github.com/tauri-apps/plugins-workspace/commit/c873e4d6c74e759742f7c9a88e35cff10a75122a)([#1059](https://github.com/tauri-apps/plugins-workspace/pull/1059)) Fixes scope not allowing subpaths, query parameters and hash when those values are empty.
|
||||
- [`a04ea2f`](https://github.com/tauri-apps/plugins-workspace/commit/a04ea2f38294d5a3987578283badc8eec87a7752)([#1071](https://github.com/tauri-apps/plugins-workspace/pull/1071)) The global API script is now only added to the binary when the `withGlobalTauri` config is true.
|
||||
- [`753c7be`](https://github.com/tauri-apps/plugins-workspace/commit/753c7be0a6a78121d2e88ea0efc3040580c885b4)([#1050](https://github.com/tauri-apps/plugins-workspace/pull/1050)) Add `unsafe-headers` cargo feature flag to allow using [forbidden headers](https://fetch.spec.whatwg.org/#terminology-headers).
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-beta.3`
|
||||
|
||||
## \[2.0.0-beta.2]
|
||||
|
||||
- [`ae56b13`](https://github.com/tauri-apps/plugins-workspace/commit/ae56b13a4d49dbf922b8a0fbb0d557bb63c1d72b)([#983](https://github.com/tauri-apps/plugins-workspace/pull/983)) Allow `User-Agent` header to be set.
|
||||
- [`99bea25`](https://github.com/tauri-apps/plugins-workspace/commit/99bea2559c2c0648c2519c50a18cd124dacef57b)([#1005](https://github.com/tauri-apps/plugins-workspace/pull/1005)) Update to tauri beta.8.
|
||||
|
||||
## \[2.0.0-beta.1]
|
||||
|
||||
- [`569defb`](https://github.com/tauri-apps/plugins-workspace/commit/569defbe9492e38938554bb7bdc1be9151456d21) Update to tauri beta.4.
|
||||
|
||||
## \[2.0.0-beta.0]
|
||||
|
||||
- [`d198c01`](https://github.com/tauri-apps/plugins-workspace/commit/d198c014863ee260cb0de88a14b7fc4356ef7474)([#862](https://github.com/tauri-apps/plugins-workspace/pull/862)) Update to tauri beta.
|
||||
- [`1a34720`](https://github.com/tauri-apps/plugins-workspace/commit/1a347203a54eccc954749d11c4ee81fdd9a0cde7)([#858](https://github.com/tauri-apps/plugins-workspace/pull/858)) Fix http fetch client option init with parameter `connectTimeout`
|
||||
|
||||
## \[2.0.0-alpha.9]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-alpha.7`
|
||||
|
||||
## \[2.0.0-alpha.6]
|
||||
|
||||
- [`bfa87da`](https://github.com/tauri-apps/plugins-workspace/commit/bfa87da848f9f1da2abae3354eed632881eddf11)([#824](https://github.com/tauri-apps/plugins-workspace/pull/824)) Add `proxy` field to `fetch` options to configure proxy.
|
||||
|
||||
## \[2.0.0-alpha.5]
|
||||
|
||||
- [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.13.
|
||||
|
||||
## \[2.0.0-alpha.4]
|
||||
|
||||
- [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.12.
|
||||
|
||||
## \[2.0.0-alpha.3]
|
||||
|
||||
- [`e438e0a`](https://github.com/tauri-apps/plugins-workspace/commit/e438e0a62d4b430a5159f05f13ecd397dd891a0d)([#676](https://github.com/tauri-apps/plugins-workspace/pull/676)) Update to @tauri-apps/api v2.0.0-alpha.11.
|
||||
|
||||
## \[2.0.0-alpha.2]
|
||||
|
||||
- [`5c13736`](https://github.com/tauri-apps/plugins-workspace/commit/5c137365c60790e8d4037d449e8237aa3fffdab0)([#673](https://github.com/tauri-apps/plugins-workspace/pull/673)) Update to @tauri-apps/api v2.0.0-alpha.9.
|
||||
|
||||
## \[2.0.0-alpha.3]
|
||||
|
||||
- [`2cb0fa7`](https://github.com/tauri-apps/plugins-workspace/commit/2cb0fa719b8b1f5ac07dada93520dbbcf637d64c)([#587](https://github.com/tauri-apps/plugins-workspace/pull/587)) Remove `cmd` property which breaks invoke call.
|
||||
- [`4e2cef9`](https://github.com/tauri-apps/plugins-workspace/commit/4e2cef9b702bbbb9cf4ee17de50791cb21f1b2a4)([#593](https://github.com/tauri-apps/plugins-workspace/pull/593)) Update to alpha.12.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-alpha.2`
|
||||
|
||||
## \[2.0.0-alpha.2]
|
||||
|
||||
- [`aec17a9`](https://github.com/tauri-apps/plugins-workspace/commit/aec17a90fc365774c70c4876b94a899416120e26)([#558](https://github.com/tauri-apps/plugins-workspace/pull/558)) Improve response performance by using the new IPC streaming data.
|
||||
|
||||
## \[2.0.0-alpha.1]
|
||||
|
||||
- [`7d9df72`](https://github.com/tauri-apps/plugins-workspace/commit/7d9df7297a221a64d9de945ffc2cd8313d3104dc)([#428](https://github.com/tauri-apps/plugins-workspace/pull/428)) Multipart requests are now handled in JavaScript by the `Request` JavaScript class so you just need to use a `FormData` body and not set the content-type header to `multipart/form-data`. `application/x-www-form-urlencoded` requests must be done manually.
|
||||
- [`7d9df72`](https://github.com/tauri-apps/plugins-workspace/commit/7d9df7297a221a64d9de945ffc2cd8313d3104dc)([#428](https://github.com/tauri-apps/plugins-workspace/pull/428)) The http plugin has been rewritten from scratch and now only exposes a `fetch` function in Javascript and Re-exports `reqwest` crate in Rust. The new `fetch` method tries to be as close and compliant to the `fetch` Web API as possible.
|
||||
- [`d74fc0a`](https://github.com/tauri-apps/plugins-workspace/commit/d74fc0a097996e90a37be8f57d50b7d1f6ca616f)([#555](https://github.com/tauri-apps/plugins-workspace/pull/555)) Update to alpha.11.
|
||||
|
||||
## \[2.0.0-alpha.0]
|
||||
|
||||
- [`717ae67`](https://github.com/tauri-apps/plugins-workspace/commit/717ae670978feb4492fac1f295998b93f2b9347f)([#371](https://github.com/tauri-apps/plugins-workspace/pull/371)) First v2 alpha release!
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
# NB(bt): We've made some changes to the packages and directives.
|
||||
# The original values are commented out.
|
||||
|
||||
[package]
|
||||
name = "tauri-plugin-http"
|
||||
version = "2.4.3"
|
||||
description = "Access an HTTP client written in Rust."
|
||||
#edition = { workspace = true }
|
||||
edition = "2021"
|
||||
#authors = { workspace = true }
|
||||
#license = { workspace = true }
|
||||
#rust-version = { workspace = true }
|
||||
rust-version = "1.77.2"
|
||||
#repository = { workspace = true }
|
||||
links = "tauri-plugin-http"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
rustc-args = ["--cfg", "docsrs"]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[package.metadata.platforms.support]
|
||||
windows = { level = "full", notes = "" }
|
||||
linux = { level = "full", notes = "" }
|
||||
macos = { level = "full", notes = "" }
|
||||
android = { level = "full", notes = "" }
|
||||
ios = { level = "full", notes = "" }
|
||||
|
||||
[build-dependencies]
|
||||
#tauri-plugin = { workspace = true, features = ["build"] }
|
||||
tauri-plugin = { version = "2.2.0", features = ["build"] }
|
||||
#schemars = { workspace = true }
|
||||
schemars = { version = "0.8" }
|
||||
serde = { workspace = true }
|
||||
url = { workspace = true }
|
||||
urlpattern = "0.3"
|
||||
regex = "1"
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tauri = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { version = "1", features = ["sync", "macros"] }
|
||||
#tauri-plugin-fs = { path = "../fs", version = "2.2.1" }
|
||||
tauri-plugin-fs = { version = "2.2.1" }
|
||||
urlpattern = "0.3"
|
||||
regex = "1"
|
||||
http = "1"
|
||||
reqwest = { version = "0.12", default-features = false }
|
||||
url = { workspace = true }
|
||||
data-url = "0.3"
|
||||
cookie_store = { version = "0.21.1", optional = true, features = ["serde"] }
|
||||
bytes = { version = "1.9", optional = true }
|
||||
#tracing = { workspace = true, optional = true }
|
||||
tracing = { version = "0.1", optional = true }
|
||||
|
||||
[features]
|
||||
default = [
|
||||
"rustls-tls",
|
||||
"http2",
|
||||
"charset",
|
||||
"macos-system-configuration",
|
||||
"cookies",
|
||||
]
|
||||
multipart = ["reqwest/multipart"]
|
||||
json = ["reqwest/json"]
|
||||
stream = ["reqwest/stream"]
|
||||
native-tls = ["reqwest/native-tls"]
|
||||
native-tls-vendored = ["reqwest/native-tls-vendored"]
|
||||
native-tls-alpn = ["reqwest/native-tls-alpn"]
|
||||
rustls-tls = ["reqwest/rustls-tls"]
|
||||
rustls-tls-manual-roots = ["reqwest/rustls-tls-manual-roots"]
|
||||
rustls-tls-webpki-roots = ["reqwest/rustls-tls-webpki-roots"]
|
||||
rustls-tls-native-roots = ["reqwest/rustls-tls-native-roots"]
|
||||
blocking = ["reqwest/blocking"]
|
||||
cookies = ["reqwest/cookies", "dep:cookie_store", "dep:bytes"]
|
||||
gzip = ["reqwest/gzip"]
|
||||
brotli = ["reqwest/brotli"]
|
||||
deflate = ["reqwest/deflate"]
|
||||
zstd = ["reqwest/zstd"]
|
||||
trust-dns = ["reqwest/trust-dns"]
|
||||
socks = ["reqwest/socks"]
|
||||
http2 = ["reqwest/http2"]
|
||||
charset = ["reqwest/charset"]
|
||||
macos-system-configuration = ["reqwest/macos-system-configuration"]
|
||||
unsafe-headers = []
|
||||
tracing = ["dep:tracing"]
|
||||
dangerous-settings = []
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
SPDXVersion: SPDX-2.1
|
||||
DataLicense: CC0-1.0
|
||||
PackageName: tauri
|
||||
DataFormat: SPDXRef-1
|
||||
PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
|
||||
PackageHomePage: https://tauri.app
|
||||
PackageLicenseDeclared: Apache-2.0
|
||||
PackageLicenseDeclared: MIT
|
||||
PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
|
||||
PackageSummary: <text>Tauri is a rust project that enables developers to make secure
|
||||
and small desktop applications using a web frontend.
|
||||
</text>
|
||||
PackageComment: <text>The package includes the following libraries; see
|
||||
Relationship information.
|
||||
</text>
|
||||
Created: 2019-05-20T09:00:00Z
|
||||
PackageDownloadLocation: git://github.com/tauri-apps/tauri
|
||||
PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
|
||||
PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
|
||||
Creator: Person: Daniel Thompson-Yvetot
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 - Present Tauri Apps Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+102
@@ -0,0 +1,102 @@
|
||||

|
||||
|
||||
Access the HTTP client written in Rust.
|
||||
|
||||
| Platform | Supported |
|
||||
| -------- | --------- |
|
||||
| Linux | ✓ |
|
||||
| Windows | ✓ |
|
||||
| macOS | ✓ |
|
||||
| Android | ✓ |
|
||||
| iOS | ✓ |
|
||||
|
||||
## Install
|
||||
|
||||
_This plugin requires a Rust version of at least **1.77.2**_
|
||||
|
||||
There are three general methods of installation that we can recommend.
|
||||
|
||||
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
|
||||
2. Pull sources directly from Github using git tags / revision hashes (most secure)
|
||||
3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
|
||||
|
||||
Install the Core plugin by adding the following to your `Cargo.toml` file:
|
||||
|
||||
`src-tauri/Cargo.toml`
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
tauri-plugin-http = "2.0.0"
|
||||
# alternatively with Git:
|
||||
tauri-plugin-http = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
|
||||
```
|
||||
|
||||
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
|
||||
|
||||
> Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use.
|
||||
|
||||
```sh
|
||||
pnpm add @tauri-apps/plugin-http
|
||||
# or
|
||||
npm add @tauri-apps/plugin-http
|
||||
# or
|
||||
yarn add @tauri-apps/plugin-http
|
||||
|
||||
# alternatively with Git:
|
||||
pnpm add https://github.com/tauri-apps/tauri-plugin-http#v2
|
||||
# or
|
||||
npm add https://github.com/tauri-apps/tauri-plugin-http#v2
|
||||
# or
|
||||
yarn add https://github.com/tauri-apps/tauri-plugin-http#v2
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
First you need to register the core plugin with Tauri:
|
||||
|
||||
`src-tauri/src/lib.rs`
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_http::init())
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
|
||||
|
||||
```javascript
|
||||
import { fetch } from '@tauri-apps/plugin-http'
|
||||
const response = await fetch('http://localhost:3003/users/2', {
|
||||
method: 'GET',
|
||||
timeout: 30
|
||||
})
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
|
||||
|
||||
## Partners
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://crabnebula.dev" target="_blank">
|
||||
<img src="https://github.com/tauri-apps/plugins-workspace/raw/v2/.github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
|
||||
|
||||
## License
|
||||
|
||||
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
|
||||
|
||||
MIT or MIT/Apache 2.0 where applicable.
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
# Security Policy
|
||||
|
||||
**Do not report security vulnerabilities through public GitHub issues.**
|
||||
|
||||
**Please use the [Private Vulnerability Disclosure](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability) feature of GitHub.**
|
||||
|
||||
Include as much of the following information:
|
||||
|
||||
- Type of issue (e.g. improper input parsing, privilege escalation, etc.)
|
||||
- The location of the affected source code (tag/branch/commit or direct URL)
|
||||
- Any special configuration required to reproduce the issue
|
||||
- The distribution affected or used to help us with reproduction of the issue
|
||||
- Step-by-step instructions to reproduce the issue
|
||||
- Ideally a reproduction repository
|
||||
- Impact of the issue, including how an attacker might exploit the issue
|
||||
|
||||
We prefer to receive reports in English.
|
||||
|
||||
## Contact
|
||||
|
||||
Please disclose a vulnerability or security relevant issue here: [https://github.com/tauri-apps/plugins-workspace/security/advisories/new](https://github.com/tauri-apps/plugins-workspace/security/advisories/new).
|
||||
|
||||
Alternatively, you can also contact us by email via [security@tauri.app](mailto:security@tauri.app).
|
||||
+1
@@ -0,0 +1 @@
|
||||
if("__TAURI__"in window){var __TAURI_PLUGIN_HTTP__=function(e){"use strict";function t(e,t,r,n){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}function r(e,t,r,n,s){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}var n,s,i,a;"function"==typeof SuppressedError&&SuppressedError;const o="__TAURI_TO_IPC_KEY__";class c{constructor(e){n.set(this,void 0),s.set(this,0),i.set(this,[]),a.set(this,void 0),r(this,n,e||(()=>{})),this.id=function(e,t=!1){return window.__TAURI_INTERNALS__.transformCallback(e,t)}((e=>{const o=e.index;if("end"in e)return void(o==t(this,s,"f")?this.cleanupCallback():r(this,a,o));const c=e.message;if(o==t(this,s,"f")){for(t(this,n,"f").call(this,c),r(this,s,t(this,s,"f")+1);t(this,s,"f")in t(this,i,"f");){const e=t(this,i,"f")[t(this,s,"f")];t(this,n,"f").call(this,e),delete t(this,i,"f")[t(this,s,"f")],r(this,s,t(this,s,"f")+1)}t(this,s,"f")===t(this,a,"f")&&this.cleanupCallback()}else t(this,i,"f")[o]=c}))}cleanupCallback(){Reflect.deleteProperty(window,`_${this.id}`)}set onmessage(e){r(this,n,e)}get onmessage(){return t(this,n,"f")}[(n=new WeakMap,s=new WeakMap,i=new WeakMap,a=new WeakMap,o)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[o]()}}async function d(e,t={},r){return window.__TAURI_INTERNALS__.invoke(e,t,r)}const h="Request cancelled";return e.fetch=async function(e,t){const r=t?.signal;if(r?.aborted)throw new Error(h);const n=t?.maxRedirections,s=t?.connectTimeout,i=t?.proxy,a=t?.danger;t&&(delete t.maxRedirections,delete t.connectTimeout,delete t.proxy,delete t.danger);const o=t?.headers?t.headers instanceof Headers?t.headers:new Headers(t.headers):new Headers,f=new Request(e,t),l=await f.arrayBuffer(),u=0!==l.byteLength?Array.from(new Uint8Array(l)):null;for(const[e,t]of f.headers)o.get(e)||o.set(e,t);const _=(o instanceof Headers?Array.from(o.entries()):Array.isArray(o)?o:Object.entries(o)).map((([e,t])=>[e,"string"==typeof t?t:t.toString()]));if(r?.aborted)throw new Error(h);const w=await d("plugin:http|fetch",{clientConfig:{method:f.method,url:f.url,headers:_,data:u,maxRedirections:n,connectTimeout:s,proxy:i,danger:a}}),p=()=>d("plugin:http|fetch_cancel",{rid:w});if(r?.aborted)throw p(),new Error(h);r?.addEventListener("abort",(()=>{p()}));const{status:y,statusText:m,url:b,headers:g,rid:T}=await d("plugin:http|fetch_send",{rid:w}),R=[101,103,204,205,304].includes(y)?null:new ReadableStream({start:e=>{const t=new c;t.onmessage=t=>{if(r?.aborted)return void e.error(h);const n=new Uint8Array(t),s=n[n.byteLength-1],i=n.slice(0,n.byteLength-1);1!=s?e.enqueue(i):e.close()},d("plugin:http|fetch_read_body",{rid:T,streamChannel:t}).catch((t=>{e.error(t)}))}}),A=new Response(R,{status:y,statusText:m});return Object.defineProperty(A,"url",{value:b}),Object.defineProperty(A,"headers",{value:new Headers(g)}),A},e}({});Object.defineProperty(window.__TAURI__,"http",{value:__TAURI_PLUGIN_HTTP__})}
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
+67
@@ -0,0 +1,67 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#[path = "src/scope.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod scope;
|
||||
|
||||
const COMMANDS: &[&str] = &["fetch", "fetch_cancel", "fetch_send", "fetch_read_body"];
|
||||
|
||||
/// HTTP scope entry.
|
||||
#[derive(schemars::JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
#[allow(unused)]
|
||||
enum HttpScopeEntry {
|
||||
/// A URL that can be accessed by the webview when using the HTTP APIs.
|
||||
/// Wildcards can be used following the URL pattern standard.
|
||||
///
|
||||
/// See [the URL Pattern spec](https://urlpattern.spec.whatwg.org/) for more information.
|
||||
///
|
||||
/// Examples:
|
||||
///
|
||||
/// - "https://*" : allows all HTTPS origin on port 443
|
||||
///
|
||||
/// - "https://*:*" : allows all HTTPS origin on any port
|
||||
///
|
||||
/// - "https://*.github.com/tauri-apps/tauri": allows any subdomain of "github.com" with the "tauri-apps/api" path
|
||||
///
|
||||
/// - "https://myapi.service.com/users/*": allows access to any URLs that begins with "https://myapi.service.com/users/"
|
||||
Value(String),
|
||||
Object {
|
||||
/// A URL that can be accessed by the webview when using the HTTP APIs.
|
||||
/// Wildcards can be used following the URL pattern standard.
|
||||
///
|
||||
/// See [the URL Pattern spec](https://urlpattern.spec.whatwg.org/) for more information.
|
||||
///
|
||||
/// Examples:
|
||||
///
|
||||
/// - "https://*" : allows all HTTPS origin on port 443
|
||||
///
|
||||
/// - "https://*:*" : allows all HTTPS origin on any port
|
||||
///
|
||||
/// - "https://*.github.com/tauri-apps/tauri": allows any subdomain of "github.com" with the "tauri-apps/api" path
|
||||
///
|
||||
/// - "https://myapi.service.com/users/*": allows access to any URLs that begins with "https://myapi.service.com/users/"
|
||||
url: String,
|
||||
},
|
||||
}
|
||||
|
||||
// Ensure `HttpScopeEntry` and `scope::EntryRaw` is kept in sync
|
||||
fn _f() {
|
||||
match scope::EntryRaw::Value(String::new()) {
|
||||
scope::EntryRaw::Value(url) => HttpScopeEntry::Value(url),
|
||||
scope::EntryRaw::Object { url } => HttpScopeEntry::Object { url },
|
||||
};
|
||||
match HttpScopeEntry::Value(String::new()) {
|
||||
HttpScopeEntry::Value(url) => scope::EntryRaw::Value(url),
|
||||
HttpScopeEntry::Object { url } => scope::EntryRaw::Object { url },
|
||||
};
|
||||
}
|
||||
|
||||
fn main() {
|
||||
tauri_plugin::Builder::new(COMMANDS)
|
||||
.global_api_script_path("./api-iife.js")
|
||||
.global_scope_schema(schemars::schema_for!(HttpScopeEntry))
|
||||
.build();
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
'use strict';
|
||||
|
||||
var core = require('@tauri-apps/api/core');
|
||||
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
/**
|
||||
* Make HTTP requests with the Rust backend.
|
||||
*
|
||||
* ## Security
|
||||
*
|
||||
* This API has a scope configuration that forces you to restrict the URLs that can be accessed using glob patterns.
|
||||
*
|
||||
* For instance, this scope configuration only allows making HTTP requests to all subdomains for `tauri.app` except for `https://private.tauri.app`:
|
||||
* ```json
|
||||
* {
|
||||
* "permissions": [
|
||||
* {
|
||||
* "identifier": "http:default",
|
||||
* "allow": [{ "url": "https://*.tauri.app" }],
|
||||
* "deny": [{ "url": "https://private.tauri.app" }]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ```
|
||||
* Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
const ERROR_REQUEST_CANCELLED = 'Request cancelled';
|
||||
/**
|
||||
* Fetch a resource from the network. It returns a `Promise` that resolves to the
|
||||
* `Response` to that `Request`, whether it is successful or not.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const response = await fetch("http://my.json.host/data.json");
|
||||
* console.log(response.status); // e.g. 200
|
||||
* console.log(response.statusText); // e.g. "OK"
|
||||
* const jsonData = await response.json();
|
||||
* ```
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function fetch(input, init) {
|
||||
// abort early here if needed
|
||||
const signal = init?.signal;
|
||||
if (signal?.aborted) {
|
||||
throw new Error(ERROR_REQUEST_CANCELLED);
|
||||
}
|
||||
const maxRedirections = init?.maxRedirections;
|
||||
const connectTimeout = init?.connectTimeout;
|
||||
const proxy = init?.proxy;
|
||||
const danger = init?.danger;
|
||||
// Remove these fields before creating the request
|
||||
if (init) {
|
||||
delete init.maxRedirections;
|
||||
delete init.connectTimeout;
|
||||
delete init.proxy;
|
||||
delete init.danger;
|
||||
}
|
||||
const headers = init?.headers
|
||||
? init.headers instanceof Headers
|
||||
? init.headers
|
||||
: new Headers(init.headers)
|
||||
: new Headers();
|
||||
const req = new Request(input, init);
|
||||
const buffer = await req.arrayBuffer();
|
||||
const data = buffer.byteLength !== 0 ? Array.from(new Uint8Array(buffer)) : null;
|
||||
// append new headers created by the browser `Request` implementation,
|
||||
// if not already declared by the caller of this function
|
||||
for (const [key, value] of req.headers) {
|
||||
if (!headers.get(key)) {
|
||||
headers.set(key, value);
|
||||
}
|
||||
}
|
||||
const headersArray = headers instanceof Headers
|
||||
? Array.from(headers.entries())
|
||||
: Array.isArray(headers)
|
||||
? headers
|
||||
: Object.entries(headers);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const mappedHeaders = headersArray.map(([name, val]) => [
|
||||
name,
|
||||
// we need to ensure we have all header values as strings
|
||||
// eslint-disable-next-line
|
||||
typeof val === 'string' ? val : val.toString()
|
||||
]);
|
||||
// abort early here if needed
|
||||
if (signal?.aborted) {
|
||||
throw new Error(ERROR_REQUEST_CANCELLED);
|
||||
}
|
||||
const rid = await core.invoke('plugin:http|fetch', {
|
||||
clientConfig: {
|
||||
method: req.method,
|
||||
url: req.url,
|
||||
headers: mappedHeaders,
|
||||
data,
|
||||
maxRedirections,
|
||||
connectTimeout,
|
||||
proxy,
|
||||
danger
|
||||
}
|
||||
});
|
||||
const abort = () => core.invoke('plugin:http|fetch_cancel', { rid });
|
||||
// abort early here if needed
|
||||
if (signal?.aborted) {
|
||||
// we don't care about the result of this proimse
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
abort();
|
||||
throw new Error(ERROR_REQUEST_CANCELLED);
|
||||
}
|
||||
signal?.addEventListener('abort', () => void abort());
|
||||
const { status, statusText, url, headers: responseHeaders, rid: responseRid } = await core.invoke('plugin:http|fetch_send', {
|
||||
rid
|
||||
});
|
||||
// no body for 101, 103, 204, 205 and 304
|
||||
// see https://fetch.spec.whatwg.org/#null-body-status
|
||||
const body = [101, 103, 204, 205, 304].includes(status)
|
||||
? null
|
||||
: new ReadableStream({
|
||||
start: (controller) => {
|
||||
const streamChannel = new core.Channel();
|
||||
streamChannel.onmessage = (res) => {
|
||||
// close early if aborted
|
||||
if (signal?.aborted) {
|
||||
controller.error(ERROR_REQUEST_CANCELLED);
|
||||
return;
|
||||
}
|
||||
const resUint8 = new Uint8Array(res);
|
||||
const lastByte = resUint8[resUint8.byteLength - 1];
|
||||
const actualRes = resUint8.slice(0, resUint8.byteLength - 1);
|
||||
// close when the signal to close (last byte is 1) is sent from the IPC.
|
||||
if (lastByte == 1) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
controller.enqueue(actualRes);
|
||||
};
|
||||
// run a non-blocking body stream fetch
|
||||
core.invoke('plugin:http|fetch_read_body', {
|
||||
rid: responseRid,
|
||||
streamChannel
|
||||
}).catch((e) => {
|
||||
controller.error(e);
|
||||
});
|
||||
}
|
||||
});
|
||||
const res = new Response(body, {
|
||||
status,
|
||||
statusText
|
||||
});
|
||||
// Set `Response` properties that are ignored by the
|
||||
// constructor, like url and some headers
|
||||
//
|
||||
// Since url and headers are read only properties
|
||||
// this is the only way to set them.
|
||||
Object.defineProperty(res, 'url', { value: url });
|
||||
Object.defineProperty(res, 'headers', {
|
||||
value: new Headers(responseHeaders)
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
exports.fetch = fetch;
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Configuration of a proxy that a Client should pass requests to.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export interface Proxy {
|
||||
/**
|
||||
* Proxy all traffic to the passed URL.
|
||||
*/
|
||||
all?: string | ProxyConfig;
|
||||
/**
|
||||
* Proxy all HTTP traffic to the passed URL.
|
||||
*/
|
||||
http?: string | ProxyConfig;
|
||||
/**
|
||||
* Proxy all HTTPS traffic to the passed URL.
|
||||
*/
|
||||
https?: string | ProxyConfig;
|
||||
}
|
||||
export interface ProxyConfig {
|
||||
/**
|
||||
* The URL of the proxy server.
|
||||
*/
|
||||
url: string;
|
||||
/**
|
||||
* Set the `Proxy-Authorization` header using Basic auth.
|
||||
*/
|
||||
basicAuth?: {
|
||||
username: string;
|
||||
password: string;
|
||||
};
|
||||
/**
|
||||
* A configuration for filtering out requests that shouldn't be proxied.
|
||||
* Entries are expected to be comma-separated (whitespace between entries is ignored)
|
||||
*/
|
||||
noProxy?: string;
|
||||
}
|
||||
/**
|
||||
* Options to configure the Rust client used to make fetch requests
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export interface ClientOptions {
|
||||
/**
|
||||
* Defines the maximum number of redirects the client should follow.
|
||||
* If set to 0, no redirects will be followed.
|
||||
*/
|
||||
maxRedirections?: number;
|
||||
/** Timeout in milliseconds */
|
||||
connectTimeout?: number;
|
||||
/**
|
||||
* Configuration of a proxy that a Client should pass requests to.
|
||||
*/
|
||||
proxy?: Proxy;
|
||||
/**
|
||||
* Configuration for dangerous settings on the client such as disabling SSL verification.
|
||||
*/
|
||||
danger?: DangerousSettings;
|
||||
}
|
||||
/**
|
||||
* Configuration for dangerous settings on the client such as disabling SSL verification.
|
||||
*
|
||||
* @since 2.3.0
|
||||
*/
|
||||
export interface DangerousSettings {
|
||||
/**
|
||||
* Disables SSL verification.
|
||||
*/
|
||||
acceptInvalidCerts?: boolean;
|
||||
/**
|
||||
* Disables hostname verification.
|
||||
*/
|
||||
acceptInvalidHostnames?: boolean;
|
||||
}
|
||||
/**
|
||||
* Fetch a resource from the network. It returns a `Promise` that resolves to the
|
||||
* `Response` to that `Request`, whether it is successful or not.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const response = await fetch("http://my.json.host/data.json");
|
||||
* console.log(response.status); // e.g. 200
|
||||
* console.log(response.statusText); // e.g. "OK"
|
||||
* const jsonData = await response.json();
|
||||
* ```
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export declare function fetch(input: URL | Request | string, init?: RequestInit & ClientOptions): Promise<Response>;
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
import { invoke, Channel } from '@tauri-apps/api/core';
|
||||
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
/**
|
||||
* Make HTTP requests with the Rust backend.
|
||||
*
|
||||
* ## Security
|
||||
*
|
||||
* This API has a scope configuration that forces you to restrict the URLs that can be accessed using glob patterns.
|
||||
*
|
||||
* For instance, this scope configuration only allows making HTTP requests to all subdomains for `tauri.app` except for `https://private.tauri.app`:
|
||||
* ```json
|
||||
* {
|
||||
* "permissions": [
|
||||
* {
|
||||
* "identifier": "http:default",
|
||||
* "allow": [{ "url": "https://*.tauri.app" }],
|
||||
* "deny": [{ "url": "https://private.tauri.app" }]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ```
|
||||
* Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
const ERROR_REQUEST_CANCELLED = 'Request cancelled';
|
||||
/**
|
||||
* Fetch a resource from the network. It returns a `Promise` that resolves to the
|
||||
* `Response` to that `Request`, whether it is successful or not.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const response = await fetch("http://my.json.host/data.json");
|
||||
* console.log(response.status); // e.g. 200
|
||||
* console.log(response.statusText); // e.g. "OK"
|
||||
* const jsonData = await response.json();
|
||||
* ```
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function fetch(input, init) {
|
||||
// abort early here if needed
|
||||
const signal = init?.signal;
|
||||
if (signal?.aborted) {
|
||||
throw new Error(ERROR_REQUEST_CANCELLED);
|
||||
}
|
||||
const maxRedirections = init?.maxRedirections;
|
||||
const connectTimeout = init?.connectTimeout;
|
||||
const proxy = init?.proxy;
|
||||
const danger = init?.danger;
|
||||
// Remove these fields before creating the request
|
||||
if (init) {
|
||||
delete init.maxRedirections;
|
||||
delete init.connectTimeout;
|
||||
delete init.proxy;
|
||||
delete init.danger;
|
||||
}
|
||||
const headers = init?.headers
|
||||
? init.headers instanceof Headers
|
||||
? init.headers
|
||||
: new Headers(init.headers)
|
||||
: new Headers();
|
||||
const req = new Request(input, init);
|
||||
const buffer = await req.arrayBuffer();
|
||||
const data = buffer.byteLength !== 0 ? Array.from(new Uint8Array(buffer)) : null;
|
||||
// append new headers created by the browser `Request` implementation,
|
||||
// if not already declared by the caller of this function
|
||||
for (const [key, value] of req.headers) {
|
||||
if (!headers.get(key)) {
|
||||
headers.set(key, value);
|
||||
}
|
||||
}
|
||||
const headersArray = headers instanceof Headers
|
||||
? Array.from(headers.entries())
|
||||
: Array.isArray(headers)
|
||||
? headers
|
||||
: Object.entries(headers);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const mappedHeaders = headersArray.map(([name, val]) => [
|
||||
name,
|
||||
// we need to ensure we have all header values as strings
|
||||
// eslint-disable-next-line
|
||||
typeof val === 'string' ? val : val.toString()
|
||||
]);
|
||||
// abort early here if needed
|
||||
if (signal?.aborted) {
|
||||
throw new Error(ERROR_REQUEST_CANCELLED);
|
||||
}
|
||||
const rid = await invoke('plugin:http|fetch', {
|
||||
clientConfig: {
|
||||
method: req.method,
|
||||
url: req.url,
|
||||
headers: mappedHeaders,
|
||||
data,
|
||||
maxRedirections,
|
||||
connectTimeout,
|
||||
proxy,
|
||||
danger
|
||||
}
|
||||
});
|
||||
const abort = () => invoke('plugin:http|fetch_cancel', { rid });
|
||||
// abort early here if needed
|
||||
if (signal?.aborted) {
|
||||
// we don't care about the result of this proimse
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
abort();
|
||||
throw new Error(ERROR_REQUEST_CANCELLED);
|
||||
}
|
||||
signal?.addEventListener('abort', () => void abort());
|
||||
const { status, statusText, url, headers: responseHeaders, rid: responseRid } = await invoke('plugin:http|fetch_send', {
|
||||
rid
|
||||
});
|
||||
// no body for 101, 103, 204, 205 and 304
|
||||
// see https://fetch.spec.whatwg.org/#null-body-status
|
||||
const body = [101, 103, 204, 205, 304].includes(status)
|
||||
? null
|
||||
: new ReadableStream({
|
||||
start: (controller) => {
|
||||
const streamChannel = new Channel();
|
||||
streamChannel.onmessage = (res) => {
|
||||
// close early if aborted
|
||||
if (signal?.aborted) {
|
||||
controller.error(ERROR_REQUEST_CANCELLED);
|
||||
return;
|
||||
}
|
||||
const resUint8 = new Uint8Array(res);
|
||||
const lastByte = resUint8[resUint8.byteLength - 1];
|
||||
const actualRes = resUint8.slice(0, resUint8.byteLength - 1);
|
||||
// close when the signal to close (last byte is 1) is sent from the IPC.
|
||||
if (lastByte == 1) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
controller.enqueue(actualRes);
|
||||
};
|
||||
// run a non-blocking body stream fetch
|
||||
invoke('plugin:http|fetch_read_body', {
|
||||
rid: responseRid,
|
||||
streamChannel
|
||||
}).catch((e) => {
|
||||
controller.error(e);
|
||||
});
|
||||
}
|
||||
});
|
||||
const res = new Response(body, {
|
||||
status,
|
||||
statusText
|
||||
});
|
||||
// Set `Response` properties that are ignored by the
|
||||
// constructor, like url and some headers
|
||||
//
|
||||
// Since url and headers are read only properties
|
||||
// this is the only way to set them.
|
||||
Object.defineProperty(res, 'url', { value: url });
|
||||
Object.defineProperty(res, 'headers', {
|
||||
value: new Headers(responseHeaders)
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
export { fetch };
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/**
|
||||
* Make HTTP requests with the Rust backend.
|
||||
*
|
||||
* ## Security
|
||||
*
|
||||
* This API has a scope configuration that forces you to restrict the URLs that can be accessed using glob patterns.
|
||||
*
|
||||
* For instance, this scope configuration only allows making HTTP requests to all subdomains for `tauri.app` except for `https://private.tauri.app`:
|
||||
* ```json
|
||||
* {
|
||||
* "permissions": [
|
||||
* {
|
||||
* "identifier": "http:default",
|
||||
* "allow": [{ "url": "https://*.tauri.app" }],
|
||||
* "deny": [{ "url": "https://private.tauri.app" }]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ```
|
||||
* Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { Channel, invoke } from '@tauri-apps/api/core'
|
||||
|
||||
/**
|
||||
* Configuration of a proxy that a Client should pass requests to.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export interface Proxy {
|
||||
/**
|
||||
* Proxy all traffic to the passed URL.
|
||||
*/
|
||||
all?: string | ProxyConfig
|
||||
/**
|
||||
* Proxy all HTTP traffic to the passed URL.
|
||||
*/
|
||||
http?: string | ProxyConfig
|
||||
/**
|
||||
* Proxy all HTTPS traffic to the passed URL.
|
||||
*/
|
||||
https?: string | ProxyConfig
|
||||
}
|
||||
|
||||
export interface ProxyConfig {
|
||||
/**
|
||||
* The URL of the proxy server.
|
||||
*/
|
||||
url: string
|
||||
/**
|
||||
* Set the `Proxy-Authorization` header using Basic auth.
|
||||
*/
|
||||
basicAuth?: {
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
/**
|
||||
* A configuration for filtering out requests that shouldn't be proxied.
|
||||
* Entries are expected to be comma-separated (whitespace between entries is ignored)
|
||||
*/
|
||||
noProxy?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Options to configure the Rust client used to make fetch requests
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export interface ClientOptions {
|
||||
/**
|
||||
* Defines the maximum number of redirects the client should follow.
|
||||
* If set to 0, no redirects will be followed.
|
||||
*/
|
||||
maxRedirections?: number
|
||||
/** Timeout in milliseconds */
|
||||
connectTimeout?: number
|
||||
/**
|
||||
* Configuration of a proxy that a Client should pass requests to.
|
||||
*/
|
||||
proxy?: Proxy
|
||||
/**
|
||||
* Configuration for dangerous settings on the client such as disabling SSL verification.
|
||||
*/
|
||||
danger?: DangerousSettings
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for dangerous settings on the client such as disabling SSL verification.
|
||||
*
|
||||
* @since 2.3.0
|
||||
*/
|
||||
export interface DangerousSettings {
|
||||
/**
|
||||
* Disables SSL verification.
|
||||
*/
|
||||
acceptInvalidCerts?: boolean
|
||||
/**
|
||||
* Disables hostname verification.
|
||||
*/
|
||||
acceptInvalidHostnames?: boolean
|
||||
}
|
||||
|
||||
const ERROR_REQUEST_CANCELLED = 'Request cancelled'
|
||||
|
||||
/**
|
||||
* Fetch a resource from the network. It returns a `Promise` that resolves to the
|
||||
* `Response` to that `Request`, whether it is successful or not.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const response = await fetch("http://my.json.host/data.json");
|
||||
* console.log(response.status); // e.g. 200
|
||||
* console.log(response.statusText); // e.g. "OK"
|
||||
* const jsonData = await response.json();
|
||||
* ```
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export async function fetch(
|
||||
input: URL | Request | string,
|
||||
init?: RequestInit & ClientOptions
|
||||
): Promise<Response> {
|
||||
// abort early here if needed
|
||||
const signal = init?.signal
|
||||
if (signal?.aborted) {
|
||||
throw new Error(ERROR_REQUEST_CANCELLED)
|
||||
}
|
||||
|
||||
const maxRedirections = init?.maxRedirections
|
||||
const connectTimeout = init?.connectTimeout
|
||||
const proxy = init?.proxy
|
||||
const danger = init?.danger
|
||||
|
||||
// Remove these fields before creating the request
|
||||
if (init) {
|
||||
delete init.maxRedirections
|
||||
delete init.connectTimeout
|
||||
delete init.proxy
|
||||
delete init.danger
|
||||
}
|
||||
|
||||
const headers = init?.headers
|
||||
? init.headers instanceof Headers
|
||||
? init.headers
|
||||
: new Headers(init.headers)
|
||||
: new Headers()
|
||||
|
||||
const req = new Request(input, init)
|
||||
const buffer = await req.arrayBuffer()
|
||||
const data =
|
||||
buffer.byteLength !== 0 ? Array.from(new Uint8Array(buffer)) : null
|
||||
|
||||
// append new headers created by the browser `Request` implementation,
|
||||
// if not already declared by the caller of this function
|
||||
for (const [key, value] of req.headers) {
|
||||
if (!headers.get(key)) {
|
||||
headers.set(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
const headersArray =
|
||||
headers instanceof Headers
|
||||
? Array.from(headers.entries())
|
||||
: Array.isArray(headers)
|
||||
? headers
|
||||
: Object.entries(headers)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const mappedHeaders: Array<[string, string]> = headersArray.map(
|
||||
([name, val]) => [
|
||||
name,
|
||||
// we need to ensure we have all header values as strings
|
||||
// eslint-disable-next-line
|
||||
typeof val === 'string' ? val : (val as any).toString()
|
||||
]
|
||||
)
|
||||
|
||||
// abort early here if needed
|
||||
if (signal?.aborted) {
|
||||
throw new Error(ERROR_REQUEST_CANCELLED)
|
||||
}
|
||||
|
||||
const rid = await invoke<number>('plugin:http|fetch', {
|
||||
clientConfig: {
|
||||
method: req.method,
|
||||
url: req.url,
|
||||
headers: mappedHeaders,
|
||||
data,
|
||||
maxRedirections,
|
||||
connectTimeout,
|
||||
proxy,
|
||||
danger
|
||||
}
|
||||
})
|
||||
|
||||
const abort = () => invoke('plugin:http|fetch_cancel', { rid })
|
||||
|
||||
// abort early here if needed
|
||||
if (signal?.aborted) {
|
||||
// we don't care about the result of this proimse
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
abort()
|
||||
throw new Error(ERROR_REQUEST_CANCELLED)
|
||||
}
|
||||
|
||||
signal?.addEventListener('abort', () => void abort())
|
||||
|
||||
interface FetchSendResponse {
|
||||
status: number
|
||||
statusText: string
|
||||
headers: [[string, string]]
|
||||
url: string
|
||||
rid: number
|
||||
}
|
||||
|
||||
const {
|
||||
status,
|
||||
statusText,
|
||||
url,
|
||||
headers: responseHeaders,
|
||||
rid: responseRid
|
||||
} = await invoke<FetchSendResponse>('plugin:http|fetch_send', {
|
||||
rid
|
||||
})
|
||||
|
||||
// no body for 101, 103, 204, 205 and 304
|
||||
// see https://fetch.spec.whatwg.org/#null-body-status
|
||||
const body = [101, 103, 204, 205, 304].includes(status)
|
||||
? null
|
||||
: new ReadableStream({
|
||||
start: (controller) => {
|
||||
const streamChannel = new Channel<ArrayBuffer | number[]>()
|
||||
streamChannel.onmessage = (res: ArrayBuffer | number[]) => {
|
||||
// close early if aborted
|
||||
if (signal?.aborted) {
|
||||
controller.error(ERROR_REQUEST_CANCELLED)
|
||||
return
|
||||
}
|
||||
|
||||
const resUint8 = new Uint8Array(res)
|
||||
const lastByte = resUint8[resUint8.byteLength - 1]
|
||||
const actualRes = resUint8.slice(0, resUint8.byteLength - 1)
|
||||
|
||||
// close when the signal to close (last byte is 1) is sent from the IPC.
|
||||
if (lastByte == 1) {
|
||||
controller.close()
|
||||
return
|
||||
}
|
||||
|
||||
controller.enqueue(actualRes)
|
||||
}
|
||||
|
||||
// run a non-blocking body stream fetch
|
||||
invoke('plugin:http|fetch_read_body', {
|
||||
rid: responseRid,
|
||||
streamChannel
|
||||
}).catch((e) => {
|
||||
controller.error(e)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const res = new Response(body, {
|
||||
status,
|
||||
statusText
|
||||
})
|
||||
|
||||
// Set `Response` properties that are ignored by the
|
||||
// constructor, like url and some headers
|
||||
//
|
||||
// Since url and headers are read only properties
|
||||
// this is the only way to set them.
|
||||
Object.defineProperty(res, 'url', { value: url })
|
||||
Object.defineProperty(res, 'headers', {
|
||||
value: new Headers(responseHeaders)
|
||||
})
|
||||
|
||||
return res
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@tauri-apps/plugin-http",
|
||||
"version": "2.4.3",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"authors": [
|
||||
"Tauri Programme within The Commons Conservancy"
|
||||
],
|
||||
"repository": "https://github.com/tauri-apps/plugins-workspace",
|
||||
"type": "module",
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"main": "./dist-js/index.cjs",
|
||||
"module": "./dist-js/index.js",
|
||||
"exports": {
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"import": "./dist-js/index.js",
|
||||
"require": "./dist-js/index.cjs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rollup -c"
|
||||
},
|
||||
"files": [
|
||||
"dist-js",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.0.0"
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-fetch"
|
||||
description = "Enables the fetch command without any pre-configured scope."
|
||||
commands.allow = ["fetch"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-fetch"
|
||||
description = "Denies the fetch command without any pre-configured scope."
|
||||
commands.deny = ["fetch"]
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-fetch-cancel"
|
||||
description = "Enables the fetch_cancel command without any pre-configured scope."
|
||||
commands.allow = ["fetch_cancel"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-fetch-cancel"
|
||||
description = "Denies the fetch_cancel command without any pre-configured scope."
|
||||
commands.deny = ["fetch_cancel"]
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-fetch-read-body"
|
||||
description = "Enables the fetch_read_body command without any pre-configured scope."
|
||||
commands.allow = ["fetch_read_body"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-fetch-read-body"
|
||||
description = "Denies the fetch_read_body command without any pre-configured scope."
|
||||
commands.deny = ["fetch_read_body"]
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-fetch-send"
|
||||
description = "Enables the fetch_send command without any pre-configured scope."
|
||||
commands.allow = ["fetch_send"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-fetch-send"
|
||||
description = "Denies the fetch_send command without any pre-configured scope."
|
||||
commands.deny = ["fetch_send"]
|
||||
@@ -0,0 +1,135 @@
|
||||
## Default Permission
|
||||
|
||||
This permission set configures what kind of
|
||||
fetch operations are available from the http plugin.
|
||||
|
||||
This enables all fetch operations but does not
|
||||
allow explicitly any origins to be fetched. This needs to
|
||||
be manually configured before usage.
|
||||
|
||||
#### Granted Permissions
|
||||
|
||||
All fetch operations are enabled.
|
||||
|
||||
|
||||
|
||||
#### This default permission set includes the following:
|
||||
|
||||
- `allow-fetch`
|
||||
- `allow-fetch-cancel`
|
||||
- `allow-fetch-read-body`
|
||||
- `allow-fetch-send`
|
||||
|
||||
## Permission Table
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Identifier</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:allow-fetch`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the fetch command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:deny-fetch`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the fetch command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:allow-fetch-cancel`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the fetch_cancel command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:deny-fetch-cancel`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the fetch_cancel command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:allow-fetch-read-body`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the fetch_read_body command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:deny-fetch-read-body`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the fetch_read_body command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:allow-fetch-send`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the fetch_send command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:deny-fetch-send`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the fetch_send command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
@@ -0,0 +1,22 @@
|
||||
"$schema" = "schemas/schema.json"
|
||||
|
||||
[default]
|
||||
description = """
|
||||
This permission set configures what kind of
|
||||
fetch operations are available from the http plugin.
|
||||
|
||||
This enables all fetch operations but does not
|
||||
allow explicitly any origins to be fetched. This needs to
|
||||
be manually configured before usage.
|
||||
|
||||
#### Granted Permissions
|
||||
|
||||
All fetch operations are enabled.
|
||||
|
||||
"""
|
||||
permissions = [
|
||||
"allow-fetch",
|
||||
"allow-fetch-cancel",
|
||||
"allow-fetch-read-body",
|
||||
"allow-fetch-send",
|
||||
]
|
||||
@@ -0,0 +1,354 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "PermissionFile",
|
||||
"description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"default": {
|
||||
"description": "The default permission set for the plugin",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/DefaultPermission"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"set": {
|
||||
"description": "A list of permissions sets defined",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/PermissionSet"
|
||||
}
|
||||
},
|
||||
"permission": {
|
||||
"description": "A list of inlined permissions",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Permission"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"DefaultPermission": {
|
||||
"description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"permissions"
|
||||
],
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "The version of the permission.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint64",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"permissions": {
|
||||
"description": "All permissions this set contains.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"PermissionSet": {
|
||||
"description": "A set of direct permissions grouped together under a new name.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"description",
|
||||
"identifier",
|
||||
"permissions"
|
||||
],
|
||||
"properties": {
|
||||
"identifier": {
|
||||
"description": "A unique identifier for the permission.",
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does.",
|
||||
"type": "string"
|
||||
},
|
||||
"permissions": {
|
||||
"description": "All permissions this set contains.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/PermissionKind"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Permission": {
|
||||
"description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"identifier"
|
||||
],
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "The version of the permission.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint64",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"identifier": {
|
||||
"description": "A unique identifier for the permission.",
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"commands": {
|
||||
"description": "Allowed or denied commands when using this permission.",
|
||||
"default": {
|
||||
"allow": [],
|
||||
"deny": []
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Commands"
|
||||
}
|
||||
]
|
||||
},
|
||||
"scope": {
|
||||
"description": "Allowed or denied scoped when using this permission.",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Scopes"
|
||||
}
|
||||
]
|
||||
},
|
||||
"platforms": {
|
||||
"description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Target"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Commands": {
|
||||
"description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"allow": {
|
||||
"description": "Allowed command.",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"deny": {
|
||||
"description": "Denied command, which takes priority.",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Scopes": {
|
||||
"description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"allow": {
|
||||
"description": "Data that defines what is allowed by the scope.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
},
|
||||
"deny": {
|
||||
"description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Value": {
|
||||
"description": "All supported ACL values.",
|
||||
"anyOf": [
|
||||
{
|
||||
"description": "Represents a null JSON value.",
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`bool`].",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"description": "Represents a valid ACL [`Number`].",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Number"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`String`].",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"description": "Represents a list of other [`Value`]s.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "Represents a map of [`String`] keys to [`Value`]s.",
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"Number": {
|
||||
"description": "A valid ACL number.",
|
||||
"anyOf": [
|
||||
{
|
||||
"description": "Represents an [`i64`].",
|
||||
"type": "integer",
|
||||
"format": "int64"
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`f64`].",
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Target": {
|
||||
"description": "Platform target.",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "MacOS.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"macOS"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Windows.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"windows"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Linux.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"linux"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Android.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"android"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "iOS.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"iOS"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"PermissionKind": {
|
||||
"type": "string",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "Enables the fetch command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-fetch",
|
||||
"markdownDescription": "Enables the fetch command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the fetch command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-fetch",
|
||||
"markdownDescription": "Denies the fetch command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the fetch_cancel command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-fetch-cancel",
|
||||
"markdownDescription": "Enables the fetch_cancel command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the fetch_cancel command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-fetch-cancel",
|
||||
"markdownDescription": "Denies the fetch_cancel command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the fetch_read_body command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-fetch-read-body",
|
||||
"markdownDescription": "Enables the fetch_read_body command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the fetch_read_body command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-fetch-read-body",
|
||||
"markdownDescription": "Denies the fetch_read_body command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the fetch_send command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-fetch-send",
|
||||
"markdownDescription": "Enables the fetch_send command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the fetch_send command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-fetch-send",
|
||||
"markdownDescription": "Denies the fetch_send command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "This permission set configures what kind of\nfetch operations are available from the http plugin.\n\nThis enables all fetch operations but does not\nallow explicitly any origins to be fetched. This needs to\nbe manually configured before usage.\n\n#### Granted Permissions\n\nAll fetch operations are enabled.\n\n\n#### This default permission set includes:\n\n- `allow-fetch`\n- `allow-fetch-cancel`\n- `allow-fetch-read-body`\n- `allow-fetch-send`",
|
||||
"type": "string",
|
||||
"const": "default",
|
||||
"markdownDescription": "This permission set configures what kind of\nfetch operations are available from the http plugin.\n\nThis enables all fetch operations but does not\nallow explicitly any origins to be fetched. This needs to\nbe manually configured before usage.\n\n#### Granted Permissions\n\nAll fetch operations are enabled.\n\n\n#### This default permission set includes:\n\n- `allow-fetch`\n- `allow-fetch-cancel`\n- `allow-fetch-read-body`\n- `allow-fetch-send`"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import { createConfig } from '../../shared/rollup.config.js'
|
||||
|
||||
export default createConfig()
|
||||
+469
@@ -0,0 +1,469 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{future::Future, pin::Pin, str::FromStr, sync::Arc, time::Duration};
|
||||
|
||||
use http::{header, HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
|
||||
use reqwest::{redirect::Policy, NoProxy};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{
|
||||
async_runtime::Mutex,
|
||||
command,
|
||||
ipc::{Channel, CommandScope, GlobalScope},
|
||||
Manager, ResourceId, ResourceTable, Runtime, State, Webview,
|
||||
};
|
||||
use tokio::sync::oneshot::{channel, Receiver, Sender};
|
||||
|
||||
use crate::{
|
||||
scope::{Entry, Scope},
|
||||
Error, Http, Result,
|
||||
};
|
||||
|
||||
const HTTP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
|
||||
|
||||
struct ReqwestResponse(reqwest::Response);
|
||||
impl tauri::Resource for ReqwestResponse {}
|
||||
|
||||
type CancelableResponseResult = Result<reqwest::Response>;
|
||||
type CancelableResponseFuture =
|
||||
Pin<Box<dyn Future<Output = CancelableResponseResult> + Send + Sync>>;
|
||||
|
||||
struct FetchRequest {
|
||||
fut: Mutex<CancelableResponseFuture>,
|
||||
abort_tx_rid: ResourceId,
|
||||
abort_rx_rid: ResourceId,
|
||||
}
|
||||
impl tauri::Resource for FetchRequest {}
|
||||
|
||||
struct AbortSender(Sender<()>);
|
||||
impl tauri::Resource for AbortRecveiver {}
|
||||
|
||||
impl AbortSender {
|
||||
fn abort(self) {
|
||||
let _ = self.0.send(());
|
||||
}
|
||||
}
|
||||
|
||||
struct AbortRecveiver(Receiver<()>);
|
||||
impl tauri::Resource for AbortSender {}
|
||||
|
||||
trait AddRequest {
|
||||
fn add_request(&mut self, fut: CancelableResponseFuture) -> ResourceId;
|
||||
}
|
||||
|
||||
impl AddRequest for ResourceTable {
|
||||
fn add_request(&mut self, fut: CancelableResponseFuture) -> ResourceId {
|
||||
let (tx, rx) = channel::<()>();
|
||||
let (tx, rx) = (AbortSender(tx), AbortRecveiver(rx));
|
||||
let req = FetchRequest {
|
||||
fut: Mutex::new(fut),
|
||||
abort_tx_rid: self.add(tx),
|
||||
abort_rx_rid: self.add(rx),
|
||||
};
|
||||
self.add(req)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FetchResponse {
|
||||
status: u16,
|
||||
status_text: String,
|
||||
headers: Vec<(String, String)>,
|
||||
url: String,
|
||||
rid: ResourceId,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[allow(dead_code)] //feature flags shoudln't affect api
|
||||
pub struct DangerousSettings {
|
||||
accept_invalid_certs: bool,
|
||||
accept_invalid_hostnames: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClientConfig {
|
||||
method: String,
|
||||
url: url::Url,
|
||||
headers: Vec<(String, String)>,
|
||||
data: Option<Vec<u8>>,
|
||||
connect_timeout: Option<u64>,
|
||||
max_redirections: Option<usize>,
|
||||
proxy: Option<Proxy>,
|
||||
danger: Option<DangerousSettings>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Proxy {
|
||||
all: Option<UrlOrConfig>,
|
||||
http: Option<UrlOrConfig>,
|
||||
https: Option<UrlOrConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(untagged)]
|
||||
pub enum UrlOrConfig {
|
||||
Url(String),
|
||||
Config(ProxyConfig),
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProxyConfig {
|
||||
url: String,
|
||||
basic_auth: Option<BasicAuth>,
|
||||
no_proxy: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct BasicAuth {
|
||||
username: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn proxy_creator(
|
||||
url_or_config: UrlOrConfig,
|
||||
proxy_fn: fn(String) -> reqwest::Result<reqwest::Proxy>,
|
||||
) -> reqwest::Result<reqwest::Proxy> {
|
||||
match url_or_config {
|
||||
UrlOrConfig::Url(url) => Ok(proxy_fn(url)?),
|
||||
UrlOrConfig::Config(ProxyConfig {
|
||||
url,
|
||||
basic_auth,
|
||||
no_proxy,
|
||||
}) => {
|
||||
let mut proxy = proxy_fn(url)?;
|
||||
if let Some(basic_auth) = basic_auth {
|
||||
proxy = proxy.basic_auth(&basic_auth.username, &basic_auth.password);
|
||||
}
|
||||
if let Some(no_proxy) = no_proxy {
|
||||
proxy = proxy.no_proxy(NoProxy::from_string(&no_proxy));
|
||||
}
|
||||
Ok(proxy)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn attach_proxy(
|
||||
proxy: Proxy,
|
||||
mut builder: reqwest::ClientBuilder,
|
||||
) -> crate::Result<reqwest::ClientBuilder> {
|
||||
let Proxy { all, http, https } = proxy;
|
||||
|
||||
if let Some(all) = all {
|
||||
let proxy = proxy_creator(all, reqwest::Proxy::all)?;
|
||||
builder = builder.proxy(proxy);
|
||||
}
|
||||
|
||||
if let Some(http) = http {
|
||||
let proxy = proxy_creator(http, reqwest::Proxy::http)?;
|
||||
builder = builder.proxy(proxy);
|
||||
}
|
||||
|
||||
if let Some(https) = https {
|
||||
let proxy = proxy_creator(https, reqwest::Proxy::https)?;
|
||||
builder = builder.proxy(proxy);
|
||||
}
|
||||
|
||||
Ok(builder)
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub async fn fetch<R: Runtime>(
|
||||
webview: Webview<R>,
|
||||
state: State<'_, Http>,
|
||||
client_config: ClientConfig,
|
||||
command_scope: CommandScope<Entry>,
|
||||
global_scope: GlobalScope<Entry>,
|
||||
) -> crate::Result<ResourceId> {
|
||||
let ClientConfig {
|
||||
method,
|
||||
url,
|
||||
headers: headers_raw,
|
||||
data,
|
||||
connect_timeout,
|
||||
max_redirections,
|
||||
proxy,
|
||||
danger,
|
||||
} = client_config;
|
||||
|
||||
let scheme = url.scheme();
|
||||
let method = Method::from_bytes(method.as_bytes())?;
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
for (h, v) in headers_raw {
|
||||
let name = HeaderName::from_str(&h)?;
|
||||
#[cfg(not(feature = "unsafe-headers"))]
|
||||
if is_unsafe_header(&name) {
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
eprintln!("[\x1b[33mWARNING\x1b[0m] Skipping {name} header as it is a forbidden header per fetch spec https://fetch.spec.whatwg.org/#terminology-headers");
|
||||
eprintln!("[\x1b[33mWARNING\x1b[0m] if keeping the header is a desired behavior, you can enable `unsafe-headers` feature flag in your Cargo.toml");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
headers.append(name, HeaderValue::from_str(&v)?);
|
||||
}
|
||||
|
||||
match scheme {
|
||||
"http" | "https" => {
|
||||
if Scope::new(
|
||||
command_scope
|
||||
.allows()
|
||||
.iter()
|
||||
.chain(global_scope.allows())
|
||||
.collect(),
|
||||
command_scope
|
||||
.denies()
|
||||
.iter()
|
||||
.chain(global_scope.denies())
|
||||
.collect(),
|
||||
)
|
||||
.is_allowed(&url)
|
||||
{
|
||||
let mut builder = reqwest::ClientBuilder::new();
|
||||
|
||||
if let Some(danger_config) = danger {
|
||||
#[cfg(not(feature = "dangerous-settings"))]
|
||||
{
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
eprintln!("[\x1b[33mWARNING\x1b[0m] using dangerous settings requires `dangerous-settings` feature flag in your Cargo.toml");
|
||||
}
|
||||
let _ = danger_config;
|
||||
return Err(Error::DangerousSettings);
|
||||
}
|
||||
#[cfg(feature = "dangerous-settings")]
|
||||
{
|
||||
builder = builder
|
||||
.danger_accept_invalid_certs(danger_config.accept_invalid_certs)
|
||||
.danger_accept_invalid_hostnames(danger_config.accept_invalid_hostnames)
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(timeout) = connect_timeout {
|
||||
builder = builder.connect_timeout(Duration::from_millis(timeout));
|
||||
}
|
||||
|
||||
if let Some(max_redirections) = max_redirections {
|
||||
builder = builder.redirect(if max_redirections == 0 {
|
||||
Policy::none()
|
||||
} else {
|
||||
Policy::limited(max_redirections)
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(proxy_config) = proxy {
|
||||
builder = attach_proxy(proxy_config, builder)?;
|
||||
}
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
{
|
||||
builder = builder.cookie_provider(state.cookies_jar.clone());
|
||||
}
|
||||
|
||||
let mut request = builder.build()?.request(method.clone(), url);
|
||||
|
||||
// POST and PUT requests should always have a 0 length content-length,
|
||||
// if there is no body. https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
|
||||
if data.is_none() && matches!(method, Method::POST | Method::PUT) {
|
||||
headers.append(header::CONTENT_LENGTH, HeaderValue::from_str("0")?);
|
||||
}
|
||||
|
||||
if headers.contains_key(header::RANGE) {
|
||||
// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch step 18
|
||||
// If httpRequest’s header list contains `Range`, then append (`Accept-Encoding`, `identity`)
|
||||
headers.append(header::ACCEPT_ENCODING, HeaderValue::from_str("identity")?);
|
||||
}
|
||||
|
||||
if !headers.contains_key(header::USER_AGENT) {
|
||||
headers.append(header::USER_AGENT, HeaderValue::from_str(HTTP_USER_AGENT)?);
|
||||
}
|
||||
|
||||
// ensure we have an Origin header set
|
||||
if cfg!(not(feature = "unsafe-headers")) || !headers.contains_key(header::ORIGIN) {
|
||||
if let Ok(url) = webview.url() {
|
||||
headers.append(
|
||||
header::ORIGIN,
|
||||
HeaderValue::from_str(&url.origin().ascii_serialization())?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// In case empty origin is passed, remove it. Some services do not like Origin header
|
||||
// so this way we can remove it in explicit way. The default behaviour is still to set it
|
||||
if cfg!(feature = "unsafe-headers")
|
||||
&& headers.get(header::ORIGIN) == Some(&HeaderValue::from_static(""))
|
||||
{
|
||||
headers.remove(header::ORIGIN);
|
||||
};
|
||||
|
||||
if let Some(data) = data {
|
||||
request = request.body(data);
|
||||
}
|
||||
|
||||
request = request.headers(headers);
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::trace!("{:?}", request);
|
||||
|
||||
let fut = async move { request.send().await.map_err(Into::into) };
|
||||
|
||||
let mut resources_table = webview.resources_table();
|
||||
let rid = resources_table.add_request(Box::pin(fut));
|
||||
|
||||
Ok(rid)
|
||||
} else {
|
||||
Err(Error::UrlNotAllowed(url))
|
||||
}
|
||||
}
|
||||
"data" => {
|
||||
let data_url =
|
||||
data_url::DataUrl::process(url.as_str()).map_err(|_| Error::DataUrlError)?;
|
||||
let (body, _) = data_url
|
||||
.decode_to_vec()
|
||||
.map_err(|_| Error::DataUrlDecodeError)?;
|
||||
|
||||
let response = http::Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, data_url.mime_type().to_string())
|
||||
.body(reqwest::Body::from(body))?;
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::trace!("{:?}", response);
|
||||
|
||||
let fut = async move { Ok(reqwest::Response::from(response)) };
|
||||
let mut resources_table = webview.resources_table();
|
||||
let rid = resources_table.add_request(Box::pin(fut));
|
||||
Ok(rid)
|
||||
}
|
||||
_ => Err(Error::SchemeNotSupport(scheme.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn fetch_cancel<R: Runtime>(webview: Webview<R>, rid: ResourceId) -> crate::Result<()> {
|
||||
let mut resources_table = webview.resources_table();
|
||||
let req = resources_table.get::<FetchRequest>(rid)?;
|
||||
let abort_tx = resources_table.take::<AbortSender>(req.abort_tx_rid)?;
|
||||
if let Some(abort_tx) = Arc::into_inner(abort_tx) {
|
||||
abort_tx.abort();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub async fn fetch_send<R: Runtime>(
|
||||
webview: Webview<R>,
|
||||
rid: ResourceId,
|
||||
) -> crate::Result<FetchResponse> {
|
||||
let (req, abort_rx) = {
|
||||
let mut resources_table = webview.resources_table();
|
||||
let req = resources_table.get::<FetchRequest>(rid)?;
|
||||
let abort_rx = resources_table.take::<AbortRecveiver>(req.abort_rx_rid)?;
|
||||
(req, abort_rx)
|
||||
};
|
||||
|
||||
let Some(abort_rx) = Arc::into_inner(abort_rx) else {
|
||||
return Err(Error::RequestCanceled);
|
||||
};
|
||||
|
||||
let mut fut = req.fut.lock().await;
|
||||
|
||||
let res = tokio::select! {
|
||||
res = fut.as_mut() => res?,
|
||||
_ = abort_rx.0 => {
|
||||
let mut resources_table = webview.resources_table();
|
||||
resources_table.close(rid)?;
|
||||
return Err(Error::RequestCanceled);
|
||||
}
|
||||
};
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::trace!("{:?}", res);
|
||||
|
||||
let status = res.status();
|
||||
let url = res.url().to_string();
|
||||
let mut headers = Vec::new();
|
||||
for (key, val) in res.headers().iter() {
|
||||
headers.push((
|
||||
key.as_str().into(),
|
||||
String::from_utf8(val.as_bytes().to_vec())?,
|
||||
));
|
||||
}
|
||||
|
||||
let mut resources_table = webview.resources_table();
|
||||
let rid = resources_table.add(ReqwestResponse(res));
|
||||
|
||||
Ok(FetchResponse {
|
||||
status: status.as_u16(),
|
||||
status_text: status.canonical_reason().unwrap_or_default().to_string(),
|
||||
headers,
|
||||
url,
|
||||
rid,
|
||||
})
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub async fn fetch_read_body<R: Runtime>(
|
||||
webview: Webview<R>,
|
||||
rid: ResourceId,
|
||||
stream_channel: Channel<tauri::ipc::InvokeResponseBody>,
|
||||
) -> crate::Result<()> {
|
||||
let res = {
|
||||
let mut resources_table = webview.resources_table();
|
||||
resources_table.take::<ReqwestResponse>(rid)?
|
||||
};
|
||||
|
||||
let mut res = Arc::into_inner(res).unwrap().0;
|
||||
|
||||
// send response through IPC channel
|
||||
while let Some(chunk) = res.chunk().await? {
|
||||
let mut chunk = chunk.to_vec();
|
||||
// append 0 to indicate we are not done yet
|
||||
chunk.push(0);
|
||||
stream_channel.send(tauri::ipc::InvokeResponseBody::Raw(chunk))?;
|
||||
}
|
||||
|
||||
// send 1 to indicate we are done
|
||||
stream_channel.send(tauri::ipc::InvokeResponseBody::Raw(vec![1]))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// forbidden headers per fetch spec https://fetch.spec.whatwg.org/#terminology-headers
|
||||
#[cfg(not(feature = "unsafe-headers"))]
|
||||
fn is_unsafe_header(header: &HeaderName) -> bool {
|
||||
matches!(
|
||||
*header,
|
||||
header::ACCEPT_CHARSET
|
||||
| header::ACCEPT_ENCODING
|
||||
| header::ACCESS_CONTROL_REQUEST_HEADERS
|
||||
| header::ACCESS_CONTROL_REQUEST_METHOD
|
||||
| header::CONNECTION
|
||||
| header::CONTENT_LENGTH
|
||||
| header::COOKIE
|
||||
| header::DATE
|
||||
| header::DNT
|
||||
| header::EXPECT
|
||||
| header::HOST
|
||||
| header::ORIGIN
|
||||
| header::REFERER
|
||||
| header::SET_COOKIE
|
||||
| header::TE
|
||||
| header::TRAILER
|
||||
| header::TRANSFER_ENCODING
|
||||
| header::UPGRADE
|
||||
| header::VIA
|
||||
) || {
|
||||
let lower = header.as_str().to_lowercase();
|
||||
lower.starts_with("proxy-") || lower.starts_with("sec-")
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::{Serialize, Serializer};
|
||||
use url::Url;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error(transparent)]
|
||||
Network(#[from] reqwest::Error),
|
||||
#[error(transparent)]
|
||||
Http(#[from] http::Error),
|
||||
#[error(transparent)]
|
||||
HttpInvalidHeaderName(#[from] http::header::InvalidHeaderName),
|
||||
#[error(transparent)]
|
||||
HttpInvalidHeaderValue(#[from] http::header::InvalidHeaderValue),
|
||||
/// URL not allowed by the scope.
|
||||
#[error("url not allowed on the configured scope: {0}")]
|
||||
UrlNotAllowed(Url),
|
||||
#[error(transparent)]
|
||||
UrlParseError(#[from] url::ParseError),
|
||||
/// HTTP method error.
|
||||
#[error(transparent)]
|
||||
HttpMethod(#[from] http::method::InvalidMethod),
|
||||
#[error("scheme {0} not supported")]
|
||||
SchemeNotSupport(String),
|
||||
#[error("Request canceled")]
|
||||
RequestCanceled,
|
||||
#[error(transparent)]
|
||||
FsError(#[from] tauri_plugin_fs::Error),
|
||||
#[error("failed to process data url")]
|
||||
DataUrlError,
|
||||
#[error("failed to decode data url into bytes")]
|
||||
DataUrlDecodeError,
|
||||
#[error(transparent)]
|
||||
Tauri(#[from] tauri::Error),
|
||||
#[error(transparent)]
|
||||
Utf8(#[from] std::string::FromUtf8Error),
|
||||
#[error("dangerous settings used but are not enabled")]
|
||||
DangerousSettings,
|
||||
}
|
||||
|
||||
impl Serialize for Error {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.to_string().as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//! Access the HTTP client written in Rust.
|
||||
|
||||
pub use reqwest;
|
||||
use tauri::{
|
||||
plugin::{Builder, TauriPlugin},
|
||||
Manager, Runtime,
|
||||
};
|
||||
|
||||
pub use error::{Error, Result};
|
||||
|
||||
// NB(bt): We're making everything public so we can access it.
|
||||
pub mod commands;
|
||||
pub mod error;
|
||||
#[cfg(feature = "cookies")]
|
||||
pub mod reqwest_cookie_store;
|
||||
pub mod scope;
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
const COOKIES_FILENAME: &str = ".cookies";
|
||||
|
||||
// NB(bt): We've vendored in this library so we can poke at the cookie data store.
|
||||
pub struct Http {
|
||||
#[cfg(feature = "cookies")]
|
||||
pub cookies_jar: std::sync::Arc<crate::reqwest_cookie_store::CookieStoreMutex>,
|
||||
}
|
||||
|
||||
pub fn init<R: Runtime>() -> TauriPlugin<R> {
|
||||
Builder::<R>::new("http")
|
||||
.setup(|app, _| {
|
||||
#[cfg(feature = "cookies")]
|
||||
let cookies_jar = {
|
||||
use crate::reqwest_cookie_store::*;
|
||||
use std::fs::File;
|
||||
use std::io::BufReader;
|
||||
|
||||
let cache_dir = app.path().app_cache_dir()?;
|
||||
std::fs::create_dir_all(&cache_dir)?;
|
||||
|
||||
let path = cache_dir.join(COOKIES_FILENAME);
|
||||
let file = File::options()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.read(true)
|
||||
.open(&path)?;
|
||||
|
||||
let reader = BufReader::new(file);
|
||||
CookieStoreMutex::load(path.clone(), reader).unwrap_or_else(|_e| {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!(
|
||||
"failed to load cookie store: {_e}, falling back to empty store"
|
||||
);
|
||||
CookieStoreMutex::new(path, Default::default())
|
||||
})
|
||||
};
|
||||
|
||||
let state = Http {
|
||||
#[cfg(feature = "cookies")]
|
||||
cookies_jar: std::sync::Arc::new(cookies_jar),
|
||||
};
|
||||
|
||||
app.manage(state);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.on_event(|app, event| {
|
||||
#[cfg(feature = "cookies")]
|
||||
if let tauri::RunEvent::Exit = event {
|
||||
let state = app.state::<Http>();
|
||||
|
||||
match state.cookies_jar.request_save() {
|
||||
Ok(rx) => {
|
||||
let _ = rx.recv();
|
||||
}
|
||||
Err(_e) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::error!("failed to save cookie jar: {_e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::fetch,
|
||||
commands::fetch_cancel,
|
||||
commands::fetch_send,
|
||||
commands::fetch_read_body
|
||||
])
|
||||
.build()
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// taken from https://github.com/pfernie/reqwest_cookie_store/blob/2ec4afabcd55e24d3afe3f0626ee6dc97bed938d/src/lib.rs
|
||||
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::{mpsc::Receiver, Mutex},
|
||||
};
|
||||
|
||||
// NB(bt): Re-export these for reuse
|
||||
pub use cookie_store::{CookieStore, RawCookie, RawCookieParseError};
|
||||
use reqwest::header::HeaderValue;
|
||||
|
||||
fn set_cookies(
|
||||
cookie_store: &mut CookieStore,
|
||||
cookie_headers: &mut dyn Iterator<Item = &HeaderValue>,
|
||||
url: &url::Url,
|
||||
) {
|
||||
let cookies = cookie_headers.filter_map(|val| {
|
||||
std::str::from_utf8(val.as_bytes())
|
||||
.map_err(RawCookieParseError::from)
|
||||
.and_then(RawCookie::parse)
|
||||
.map(|c| c.into_owned())
|
||||
.ok()
|
||||
});
|
||||
cookie_store.store_response_cookies(cookies, url);
|
||||
}
|
||||
|
||||
fn cookies(cookie_store: &CookieStore, url: &url::Url) -> Option<HeaderValue> {
|
||||
let s = cookie_store
|
||||
.get_request_values(url)
|
||||
.map(|(name, value)| format!("{}={}", name, value))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ");
|
||||
|
||||
if s.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
HeaderValue::from_maybe_shared(bytes::Bytes::from(s)).ok()
|
||||
}
|
||||
|
||||
/// A [`cookie_store::CookieStore`] wrapped internally by a [`std::sync::Mutex`], suitable for use in
|
||||
/// async/concurrent contexts.
|
||||
#[derive(Debug)]
|
||||
pub struct CookieStoreMutex {
|
||||
pub path: PathBuf,
|
||||
// NB(bt): We've made both of these public so we can access them.
|
||||
pub store: Mutex<CookieStore>,
|
||||
pub save_task: Mutex<Option<CancellableTask>>,
|
||||
}
|
||||
|
||||
impl CookieStoreMutex {
|
||||
/// Create a new [`CookieStoreMutex`] from an existing [`cookie_store::CookieStore`].
|
||||
pub fn new(path: PathBuf, cookie_store: CookieStore) -> CookieStoreMutex {
|
||||
CookieStoreMutex {
|
||||
path,
|
||||
store: Mutex::new(cookie_store),
|
||||
save_task: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load<R: std::io::BufRead>(
|
||||
path: PathBuf,
|
||||
reader: R,
|
||||
) -> cookie_store::Result<CookieStoreMutex> {
|
||||
cookie_store::serde::load(reader, |c| serde_json::from_str(c))
|
||||
.map(|store| CookieStoreMutex::new(path, store))
|
||||
}
|
||||
|
||||
fn cookies_to_str(&self) -> Result<String, serde_json::Error> {
|
||||
let mut cookies = Vec::new();
|
||||
for cookie in self
|
||||
.store
|
||||
.lock()
|
||||
.expect("poisoned cookie jar mutex")
|
||||
.iter_unexpired()
|
||||
{
|
||||
if cookie.is_persistent() {
|
||||
cookies.push(cookie.clone());
|
||||
}
|
||||
}
|
||||
serde_json::to_string(&cookies)
|
||||
}
|
||||
|
||||
pub fn request_save(&self) -> cookie_store::Result<Receiver<()>> {
|
||||
let cookie_str = self.cookies_to_str()?;
|
||||
let path = self.path.clone();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let task = tauri::async_runtime::spawn(async move {
|
||||
match tokio::fs::write(&path, &cookie_str).await {
|
||||
Ok(()) => {
|
||||
let _ = tx.send(());
|
||||
}
|
||||
Err(_e) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::error!("failed to save cookie jar: {_e}");
|
||||
}
|
||||
}
|
||||
});
|
||||
self.save_task
|
||||
.lock()
|
||||
.unwrap()
|
||||
.replace(CancellableTask(task));
|
||||
Ok(rx)
|
||||
}
|
||||
}
|
||||
|
||||
impl reqwest::cookie::CookieStore for CookieStoreMutex {
|
||||
fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) {
|
||||
set_cookies(&mut self.store.lock().unwrap(), cookie_headers, url);
|
||||
|
||||
// try to persist cookies immediately asynchronously
|
||||
if let Err(_e) = self.request_save() {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::error!("failed to save cookie jar: {_e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn cookies(&self, url: &url::Url) -> Option<HeaderValue> {
|
||||
let store = self.store.lock().unwrap();
|
||||
cookies(&store, url)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CancellableTask(tauri::async_runtime::JoinHandle<()>);
|
||||
|
||||
impl Drop for CancellableTask {
|
||||
fn drop(&mut self) {
|
||||
self.0.abort();
|
||||
}
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use url::Url;
|
||||
use urlpattern::{UrlPattern, UrlPatternMatchInput};
|
||||
|
||||
#[allow(rustdoc::bare_urls)]
|
||||
#[derive(Debug)]
|
||||
pub struct Entry {
|
||||
pub url: UrlPattern,
|
||||
}
|
||||
|
||||
fn parse_url_pattern(s: &str) -> Result<UrlPattern, urlpattern::quirks::Error> {
|
||||
let mut init = urlpattern::UrlPatternInit::parse_constructor_string::<regex::Regex>(s, None)?;
|
||||
if init.search.as_ref().map(|p| p.is_empty()).unwrap_or(true) {
|
||||
init.search.replace("*".to_string());
|
||||
}
|
||||
if init.hash.as_ref().map(|p| p.is_empty()).unwrap_or(true) {
|
||||
init.hash.replace("*".to_string());
|
||||
}
|
||||
if init
|
||||
.pathname
|
||||
.as_ref()
|
||||
.map(|p| p.is_empty() || p == "/")
|
||||
.unwrap_or(true)
|
||||
{
|
||||
init.pathname.replace("*".to_string());
|
||||
}
|
||||
UrlPattern::parse(init, Default::default())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub(crate) enum EntryRaw {
|
||||
Value(String),
|
||||
Object { url: String },
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Entry {
|
||||
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
EntryRaw::deserialize(deserializer).and_then(|raw| {
|
||||
let url = match raw {
|
||||
EntryRaw::Value(url) => url,
|
||||
EntryRaw::Object { url } => url,
|
||||
};
|
||||
Ok(Entry {
|
||||
url: parse_url_pattern(&url).map_err(|e| {
|
||||
serde::de::Error::custom(format!("`{}` is not a valid URL pattern: {e}", url))
|
||||
})?,
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Scope for filesystem access.
|
||||
#[derive(Debug)]
|
||||
pub struct Scope<'a> {
|
||||
allowed: Vec<&'a Arc<Entry>>,
|
||||
denied: Vec<&'a Arc<Entry>>,
|
||||
}
|
||||
|
||||
impl<'a> Scope<'a> {
|
||||
/// Creates a new scope from the scope configuration.
|
||||
pub(crate) fn new(allowed: Vec<&'a Arc<Entry>>, denied: Vec<&'a Arc<Entry>>) -> Self {
|
||||
Self { allowed, denied }
|
||||
}
|
||||
|
||||
/// Determines if the given URL is allowed on this scope.
|
||||
pub fn is_allowed(&self, url: &Url) -> bool {
|
||||
let denied = self.denied.iter().any(|entry| {
|
||||
entry
|
||||
.url
|
||||
.test(UrlPatternMatchInput::Url(url.clone()))
|
||||
.unwrap_or_default()
|
||||
});
|
||||
if denied {
|
||||
false
|
||||
} else {
|
||||
self.allowed.iter().any(|entry| {
|
||||
entry
|
||||
.url
|
||||
.test(UrlPatternMatchInput::Url(url.clone()))
|
||||
.unwrap_or_default()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{str::FromStr, sync::Arc};
|
||||
|
||||
use super::Entry;
|
||||
|
||||
impl FromStr for Entry {
|
||||
type Err = urlpattern::quirks::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let pattern = super::parse_url_pattern(s)?;
|
||||
Ok(Self { url: pattern })
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denied_takes_precedence() {
|
||||
let allow = Arc::new("http://localhost:8080/file.png".parse().unwrap());
|
||||
let deny = Arc::new("http://localhost:8080/*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&allow], vec![&deny]);
|
||||
assert!(!scope.is_allowed(&"http://localhost:8080/file.png".parse().unwrap()));
|
||||
assert!(!scope.is_allowed(&"http://localhost:8080?framework=tauri".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_url() {
|
||||
// plain URL
|
||||
let entry = Arc::new("http://localhost:8080".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
assert!(scope.is_allowed(&"http://localhost:8080".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/file".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/path/to/asset.png".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/path/list?limit=50".parse().unwrap()));
|
||||
|
||||
assert!(!scope.is_allowed(&"https://localhost:8080".parse().unwrap()));
|
||||
assert!(!scope.is_allowed(&"http://localhost:8081".parse().unwrap()));
|
||||
assert!(!scope.is_allowed(&"http://local:8080".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_path() {
|
||||
// URL with fixed path
|
||||
let entry = Arc::new("http://localhost:8080/file.png".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/file.png".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/file.png?q=1".parse().unwrap()));
|
||||
|
||||
assert!(!scope.is_allowed(&"http://localhost:8080".parse().unwrap()));
|
||||
assert!(!scope.is_allowed(&"http://localhost:8080/file".parse().unwrap()));
|
||||
assert!(!scope.is_allowed(&"http://localhost:8080/file.png/other.jpg".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_wildcard() {
|
||||
let entry = Arc::new("http://localhost:8080/*.png".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/file.png".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/file.png#head".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/assets/file.png".parse().unwrap()));
|
||||
assert!(scope.is_allowed(
|
||||
&"http://localhost:8080/assets/file.png?width=100&height=200"
|
||||
.parse()
|
||||
.unwrap()
|
||||
));
|
||||
|
||||
assert!(!scope.is_allowed(&"http://localhost:8080/file.jpeg".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn domain_wildcard() {
|
||||
let entry = Arc::new("http://*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"http://something.else".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://something.else#tauri".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://something.else/path/to/file".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://something.else?rel=tauri".parse().unwrap()));
|
||||
assert!(scope.is_allowed(
|
||||
&"http://something.else/path/to/file.mp4?start=500"
|
||||
.parse()
|
||||
.unwrap()
|
||||
));
|
||||
|
||||
assert!(!scope.is_allowed(&"https://something.else".parse().unwrap()));
|
||||
|
||||
let entry = Arc::new("http://*/*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"http://something.else".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://something.else/path/to/file".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scheme_wildcard() {
|
||||
let entry = Arc::new("*://*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"http://something.else".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://something.else/path/to/file".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"file://path".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"file://path/to/file".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"https://something.else".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"https://something.else?x=1#frag".parse().unwrap()));
|
||||
|
||||
let entry = Arc::new("*://*/*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"http://something.else".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://something.else/path/to/file".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"file://path/to/file".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"https://something.else".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_query() {
|
||||
let entry = Arc::new("https://tauri.app/path?x=*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"https://tauri.app/path?x=5".parse().unwrap()));
|
||||
|
||||
assert!(!scope.is_allowed(&"https://tauri.app/path?y=5".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_hash() {
|
||||
let entry = Arc::new("https://tauri.app/path#frame*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"https://tauri.app/path#frame".parse().unwrap()));
|
||||
|
||||
assert!(!scope.is_allowed(&"https://tauri.app/path#work".parse().unwrap()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["guest-js/*.ts"]
|
||||
}
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Get the directory of this script
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# Go up to the root of the repository (assumes src/app/pages is always 3 levels deep)
|
||||
REPO_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)"
|
||||
|
||||
cd "${REPO_ROOT}"
|
||||
echo "${REPO_ROOT}"
|
||||
|
||||
|
||||
# Run the launch script
|
||||
./script/desktop/launch_desktop_2d.sh
|
||||
@@ -1,33 +0,0 @@
|
||||
import { ApiManager, ApiResponse } from "./ApiManager";
|
||||
import { Subscription } from "./models/Billing";
|
||||
import { LoyaltyProgram } from "./enums/Billing";
|
||||
|
||||
export class BillingApi extends ApiManager {
|
||||
public async ListActiveSubscriptions(): Promise<
|
||||
ApiResponse<{
|
||||
active_subscriptions: Subscription[];
|
||||
maybe_loyalty_program?: LoyaltyProgram;
|
||||
}>
|
||||
> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/billing/active_subscriptions`;
|
||||
return await this.get<{
|
||||
success: boolean;
|
||||
active_subscriptions?: Subscription[];
|
||||
maybe_loyalty_program?: LoyaltyProgram;
|
||||
error_message?: string;
|
||||
}>({ endpoint: endpoint })
|
||||
.then((response) => ({
|
||||
success: response.success,
|
||||
data: {
|
||||
active_subscriptions: response.active_subscriptions || [],
|
||||
maybe_loyalty_program: response.maybe_loyalty_program,
|
||||
},
|
||||
}))
|
||||
.catch((err) => {
|
||||
return {
|
||||
success: false,
|
||||
errorMessage: err.message,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
import { ApiManager, ApiResponse } from "./ApiManager";
|
||||
|
||||
export class CommentsApi extends ApiManager {
|
||||
public CreateComment({
|
||||
commentMarkdown,
|
||||
entityToken,
|
||||
entityType,
|
||||
uuidIdempotencyToken,
|
||||
}: {
|
||||
commentMarkdown: string;
|
||||
entityToken: string;
|
||||
entityType: string;
|
||||
uuidIdempotencyToken: string;
|
||||
}): Promise<ApiResponse<string>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/comments/new`;
|
||||
|
||||
const body = {
|
||||
comment_markdown: commentMarkdown,
|
||||
entity_token: entityToken,
|
||||
entity_type: entityType,
|
||||
uuid_idempotency_token: uuidIdempotencyToken,
|
||||
};
|
||||
|
||||
return this.post<
|
||||
{
|
||||
comment_markdown: string;
|
||||
entity_token: string;
|
||||
entity_type: string;
|
||||
uuid_idempotency_token: string;
|
||||
},
|
||||
{
|
||||
success?: boolean;
|
||||
comment_token?: string;
|
||||
BadInput?: string;
|
||||
}
|
||||
>({ endpoint, body })
|
||||
.then((response) => ({
|
||||
success: response.success ?? false,
|
||||
data: response.comment_token,
|
||||
errorMessage: response.BadInput,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
|
||||
public DeleteComment({
|
||||
commentToken,
|
||||
}: {
|
||||
commentToken: string;
|
||||
}): Promise<ApiResponse<undefined>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/comments/delete/${commentToken}`;
|
||||
|
||||
return this.post<
|
||||
{ as_mod: boolean },
|
||||
{
|
||||
success?: boolean;
|
||||
BadInput?: string;
|
||||
}
|
||||
>({ endpoint, body: { as_mod: true } })
|
||||
.then((response) => ({
|
||||
success: response.success ?? false,
|
||||
errorMessage: response.BadInput,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
|
||||
public ListCommentsByEntity({
|
||||
entityType,
|
||||
entityToken,
|
||||
}: {
|
||||
entityType: string;
|
||||
entityToken: string;
|
||||
}): Promise<ApiResponse<string[]>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/comments/list/${entityType}/${entityToken}`;
|
||||
|
||||
return this.get<{
|
||||
success: boolean;
|
||||
comments: string[];
|
||||
}>({ endpoint })
|
||||
.then((response) => ({
|
||||
success: true,
|
||||
data: response.comments,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import { ApiManager, ApiResponse } from "./ApiManager";
|
||||
import { Job, JobPreview } from "./models/Job";
|
||||
|
||||
export class JobsApi extends ApiManager {
|
||||
public GetPreviewStatusByJobToken({
|
||||
token,
|
||||
}: {
|
||||
token: string;
|
||||
}): Promise<ApiResponse<JobPreview>> {
|
||||
console.log(token);
|
||||
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/workflows/preview_status/${token}`;
|
||||
|
||||
return this.get<ApiResponse<JobPreview>>({ endpoint })
|
||||
.then((response) => ({
|
||||
success: response.success,
|
||||
data: response.data,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
|
||||
public GetJobByToken({
|
||||
token,
|
||||
}: {
|
||||
token: string;
|
||||
}): Promise<ApiResponse<Job>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/jobs/job/${token}`;
|
||||
|
||||
return this.get<{
|
||||
success: boolean;
|
||||
state: Job;
|
||||
}>({ endpoint })
|
||||
.then((response) => ({
|
||||
success: response.success,
|
||||
data: response.state,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
|
||||
public ListRecentJobs(): Promise<ApiResponse<Job[]>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/jobs/session`;
|
||||
|
||||
return this.get<{
|
||||
success: boolean;
|
||||
jobs: Job[];
|
||||
error_reason?: string;
|
||||
}>({ endpoint })
|
||||
.then((response) => ({
|
||||
success: response.success,
|
||||
data: response.jobs,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
|
||||
public DeleteJobByToken(jobToken: string): Promise<ApiResponse<undefined>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/jobs/job/${jobToken}`;
|
||||
|
||||
return this.delete<
|
||||
undefined,
|
||||
{
|
||||
success: boolean;
|
||||
}
|
||||
>({ endpoint })
|
||||
.then((response) => ({
|
||||
success: response.success,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import { ApiManager, ApiResponse } from "./ApiManager";
|
||||
import { StatusAlert } from "./models/StatusAlert";
|
||||
|
||||
export class MiscApi extends ApiManager {
|
||||
public GetStatusAlertCheck(): Promise<ApiResponse<StatusAlert>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/session`;
|
||||
return this.get<{
|
||||
success: boolean;
|
||||
maybe_alert?: Omit<StatusAlert, "refresh_interval_millis">;
|
||||
refresh_interval_millis: number;
|
||||
}>({ endpoint: endpoint })
|
||||
.then((response) => ({
|
||||
success: response.success,
|
||||
data: {
|
||||
...response.maybe_alert,
|
||||
refresh_interval_millis: response.refresh_interval_millis,
|
||||
},
|
||||
}))
|
||||
.catch((err) => {
|
||||
return {
|
||||
success: false,
|
||||
errorMessage: err.mesasge,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import { ApiManager, ApiResponse } from "./ApiManager";
|
||||
|
||||
export class ModerationApi extends ApiManager {
|
||||
public async UpdateFeatureFlagsByToken({
|
||||
usernameOrToken,
|
||||
flags,
|
||||
}: {
|
||||
usernameOrToken: string;
|
||||
flags: string[];
|
||||
}): Promise<
|
||||
ApiResponse<{
|
||||
inference_job_token?: string;
|
||||
inference_job_token_type?: string;
|
||||
}>
|
||||
> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/moderation/user_feature_flags/${usernameOrToken}`;
|
||||
|
||||
const body = {
|
||||
action: {
|
||||
AddFlags: {
|
||||
flags,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return this.post<
|
||||
{ action: { AddFlags: { flags: string[] } } },
|
||||
{ success?: boolean; BadInput?: string }
|
||||
>({
|
||||
endpoint,
|
||||
body: body,
|
||||
})
|
||||
.then((response) => ({
|
||||
success: response.success ?? false,
|
||||
errorMessage: response.BadInput,
|
||||
}))
|
||||
.catch((err) => ({
|
||||
success: false,
|
||||
errorMessage: err.message,
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { ApiManager, ApiResponse } from "./ApiManager";
|
||||
import { Prompts } from "./models/Prompts";
|
||||
|
||||
export class PromptsApi extends ApiManager {
|
||||
public GetPromptsByToken({
|
||||
token,
|
||||
}: {
|
||||
token: string;
|
||||
}): Promise<ApiResponse<Prompts>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/prompts/${token}`;
|
||||
|
||||
return this.get<{
|
||||
success: boolean;
|
||||
prompt: Prompts;
|
||||
error_reason?: string;
|
||||
}>({ endpoint })
|
||||
.then((response) => ({
|
||||
success: response.success,
|
||||
data: response.prompt,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import { ApiManager, ApiResponse } from "./ApiManager";
|
||||
import { GenerateTtsAudioErrorType } from "./enums/Tts";
|
||||
import { Visibility } from "./enums/Visibility";
|
||||
|
||||
export interface GenerateTtsAudioRequest {
|
||||
creator_set_visibility?: Visibility;
|
||||
uuid_idempotency_token: string;
|
||||
tts_model_token: string;
|
||||
inference_text: string;
|
||||
is_storyteller_demo?: boolean;
|
||||
}
|
||||
|
||||
export interface GenerateTtsAudioResponse {
|
||||
success?: boolean;
|
||||
inference_job_token?: string;
|
||||
inference_job_token_type?: string;
|
||||
BadInput?: string;
|
||||
}
|
||||
|
||||
export class TtsApi extends ApiManager {
|
||||
public async GenerateTtsAudio(request: GenerateTtsAudioRequest): Promise<
|
||||
ApiResponse<{
|
||||
inference_job_token?: string;
|
||||
inference_job_token_type?: string;
|
||||
}>
|
||||
> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/tts/inference`;
|
||||
|
||||
const body = {
|
||||
...request,
|
||||
...(request.creator_set_visibility
|
||||
? {}
|
||||
: { creator_set_visibility: Visibility.Public }),
|
||||
};
|
||||
|
||||
return this.post<GenerateTtsAudioRequest, GenerateTtsAudioResponse>({
|
||||
endpoint,
|
||||
body: body,
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.success) {
|
||||
return {
|
||||
success: false,
|
||||
errorMessage: response.BadInput,
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
inference_job_token: response.inference_job_token,
|
||||
inference_job_token_type: response.inference_job_token_type,
|
||||
},
|
||||
};
|
||||
})
|
||||
.catch(() => {
|
||||
return {
|
||||
success: false,
|
||||
errorMessage: GenerateTtsAudioErrorType.UnknownError,
|
||||
data: {},
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
import { ApiManager, ApiResponse } from "./ApiManager";
|
||||
import {
|
||||
UserBookmarkBatch,
|
||||
UserBookmarkByEntity,
|
||||
UserBookmarkByUser,
|
||||
} from "./models/UserBookmark";
|
||||
import { Pagination } from "./models/Pagination";
|
||||
|
||||
export enum ScopedEntityTypes {
|
||||
USER = "user",
|
||||
TTS_MODEL = "tts-model",
|
||||
TTS_RESULT = "tts-result",
|
||||
W2L_TEMPLATE = "w2l-template",
|
||||
W2L_RESULT = "w2l-result",
|
||||
MEDIA_FILE = "media_file",
|
||||
MODEL_WEIGHT = "model_weight",
|
||||
VOICE_CONVERSION_MODEL = "voice_conversion_model",
|
||||
ZS_VOICE = "z_voice",
|
||||
}
|
||||
|
||||
export enum ScopedWeightTypes {
|
||||
HIFIGAN_TTl2 = "hifigan_tt2",
|
||||
RVC_V2 = "rvc_v2",
|
||||
SD_1_5 = "sd_1.5",
|
||||
SDXL = "sdxl",
|
||||
SO_VITS_SVC = "so_vits_svc",
|
||||
TT2 = "tt2",
|
||||
LORA = "loRA",
|
||||
VALL_E = "vall_e",
|
||||
COMFY_UI = "comfy_ui",
|
||||
}
|
||||
|
||||
export enum ScopedMediaFileType {
|
||||
IMAGE_GENERATION = "image_generation",
|
||||
TEXT_TO_SPEECH = "text_to_speech",
|
||||
VOCODER = "vocoder",
|
||||
VOICE_CONVERSION = "voice_conversion",
|
||||
WORKFLOW_CONFIG = "workflow_config",
|
||||
}
|
||||
|
||||
interface ListUserBookmarksByUserRequest {
|
||||
username: string;
|
||||
sort_ascending?: boolean;
|
||||
page_size?: number;
|
||||
page_index?: number;
|
||||
maybe_scoped_entity_type?: ScopedEntityTypes[];
|
||||
maybe_scoped_weight_type?: ScopedWeightTypes[];
|
||||
maybe_scoped_media_file_type?: ScopedMediaFileType[];
|
||||
}
|
||||
|
||||
export class UserBookmarksApi extends ApiManager {
|
||||
public CreateUserBookmark({
|
||||
entityToken,
|
||||
entityType,
|
||||
}: {
|
||||
entityToken: string;
|
||||
entityType: string;
|
||||
}): Promise<
|
||||
ApiResponse<{
|
||||
new_bookmark_count_for_entity?: number;
|
||||
user_bookmark_token?: string;
|
||||
}>
|
||||
> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/user_bookmarks/create`;
|
||||
const body = {
|
||||
entity_token: entityToken,
|
||||
entity_type: entityType,
|
||||
};
|
||||
|
||||
return this.post<
|
||||
{
|
||||
entity_token: string;
|
||||
entity_type: string;
|
||||
},
|
||||
{
|
||||
success?: boolean;
|
||||
new_bookmark_count_for_entity?: number;
|
||||
user_bookmark_token: string;
|
||||
BadInput?: string;
|
||||
}
|
||||
>({ endpoint, body })
|
||||
.then((response) => ({
|
||||
success: response.success ?? false,
|
||||
data: {
|
||||
new_bookmark_count_for_entity: response.new_bookmark_count_for_entity,
|
||||
user_bookmark_token: response.user_bookmark_token,
|
||||
},
|
||||
errorMessage: response.BadInput,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
|
||||
public DeleteUserBookmark({
|
||||
entityToken,
|
||||
}: {
|
||||
entityToken: string;
|
||||
}): Promise<ApiResponse<undefined>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/user_bookmarks/delete/${entityToken}`;
|
||||
|
||||
return this.delete<
|
||||
{ as_mod: boolean },
|
||||
{
|
||||
success?: boolean;
|
||||
BadInput?: string;
|
||||
}
|
||||
>({ endpoint, body: { as_mod: true } })
|
||||
.then((response) => ({
|
||||
success: response.success ?? false,
|
||||
errorMessage: response.BadInput,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
|
||||
public ListUserBookmarks(): Promise<ApiResponse<UserBookmarkBatch[]>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/user_bookmarks/batch`;
|
||||
|
||||
return this.get<{
|
||||
success?: boolean;
|
||||
bookmarks?: UserBookmarkBatch[];
|
||||
BadInput?: string;
|
||||
}>({ endpoint })
|
||||
.then((response) => ({
|
||||
success: response.success ?? false,
|
||||
data: response.bookmarks,
|
||||
errorMessage: response.BadInput,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
|
||||
public ListUserBookmarksByUser({
|
||||
username,
|
||||
sort_ascending,
|
||||
page_size,
|
||||
page_index,
|
||||
maybe_scoped_entity_type,
|
||||
maybe_scoped_weight_type,
|
||||
maybe_scoped_media_file_type,
|
||||
}: ListUserBookmarksByUserRequest): Promise<
|
||||
ApiResponse<UserBookmarkByUser[], Pagination>
|
||||
> {
|
||||
const user = username;
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/user_bookmarks/list/${user}`;
|
||||
|
||||
const query = {
|
||||
sort_ascending,
|
||||
page_size,
|
||||
page_index,
|
||||
maybe_scoped_entity_type: maybe_scoped_entity_type
|
||||
? maybe_scoped_entity_type.join(",")
|
||||
: undefined,
|
||||
maybe_scoped_weight_type: maybe_scoped_weight_type
|
||||
? maybe_scoped_weight_type.join(",")
|
||||
: undefined,
|
||||
maybe_scoped_media_file_type: maybe_scoped_media_file_type
|
||||
? maybe_scoped_media_file_type.join(",")
|
||||
: undefined,
|
||||
};
|
||||
|
||||
return this.get<{
|
||||
success?: boolean;
|
||||
pagination?: Pagination;
|
||||
results: UserBookmarkByUser[];
|
||||
}>({ endpoint, query })
|
||||
.then((response) => ({
|
||||
success: response.success ?? false,
|
||||
data: response.results,
|
||||
pagination: response.pagination,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
|
||||
public ListUserBookmarksByEntity({
|
||||
entityType,
|
||||
entityToken,
|
||||
}: {
|
||||
entityType: string;
|
||||
entityToken: string;
|
||||
}): Promise<ApiResponse<UserBookmarkByEntity[]>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/user_bookmarks/list/${entityType}/${entityToken}`;
|
||||
|
||||
return this.get<{
|
||||
success: boolean;
|
||||
user_bookmarks: UserBookmarkByEntity[];
|
||||
}>({ endpoint })
|
||||
.then((response) => ({
|
||||
success: true,
|
||||
data: response.user_bookmarks,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
import { ApiManager, ApiResponse } from "./ApiManager";
|
||||
import { UserInfo } from "./models/Users";
|
||||
|
||||
export class UsersApi extends ApiManager {
|
||||
public GetSession(): Promise<
|
||||
ApiResponse<{
|
||||
loggedIn: boolean;
|
||||
user?: UserInfo;
|
||||
}>
|
||||
> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/session`;
|
||||
return this.get<{
|
||||
success: boolean;
|
||||
logged_in: boolean;
|
||||
user?: UserInfo;
|
||||
error_message?: string;
|
||||
}>({ endpoint: endpoint })
|
||||
.then((response) => ({
|
||||
success: response.success,
|
||||
data: {
|
||||
loggedIn: response.logged_in,
|
||||
user: response.user,
|
||||
},
|
||||
}))
|
||||
.catch((err) => {
|
||||
return {
|
||||
success: false,
|
||||
errorMessage: err.mesasge,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
public GetUserProfile(username: string): Promise<
|
||||
ApiResponse<{
|
||||
user?: UserInfo;
|
||||
}>
|
||||
> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/user/${username}/profile`;
|
||||
return this.get<{
|
||||
success: boolean;
|
||||
user?: UserInfo;
|
||||
error_message?: string;
|
||||
}>({ endpoint: endpoint })
|
||||
.then((response) => ({
|
||||
success: response.success,
|
||||
data: {
|
||||
user: response.user,
|
||||
},
|
||||
}))
|
||||
.catch((err) => {
|
||||
return {
|
||||
success: false,
|
||||
error_message: err.message,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
public async Login({
|
||||
usernameOrEmail,
|
||||
password,
|
||||
}: {
|
||||
usernameOrEmail: string;
|
||||
password: string;
|
||||
}): Promise<ApiResponse<{ signedSession?: string }>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/login`;
|
||||
|
||||
const body = {
|
||||
username_or_email: usernameOrEmail,
|
||||
password: password,
|
||||
};
|
||||
return await this.post<
|
||||
{ username_or_email: string; password: string },
|
||||
{
|
||||
success: boolean;
|
||||
signed_session?: string;
|
||||
error_message?: string;
|
||||
error_type?: string;
|
||||
}
|
||||
>({
|
||||
endpoint: endpoint,
|
||||
body: body,
|
||||
})
|
||||
.then((response) => ({
|
||||
success: response.success,
|
||||
data: { signedSession: response.signed_session },
|
||||
errorMessage: response.error_message,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return {
|
||||
success: false,
|
||||
error_message: err.message,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
public Logout(): Promise<ApiResponse<null>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/logout`;
|
||||
return this.post<null, { success: boolean; error_message?: string }>({
|
||||
endpoint: endpoint,
|
||||
})
|
||||
.then((response) => ({
|
||||
success: response.success,
|
||||
}))
|
||||
.catch((err) => {
|
||||
return {
|
||||
success: false,
|
||||
errorMessage: err.message,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
public async Signup({
|
||||
username,
|
||||
email,
|
||||
password,
|
||||
passwordConfirmation,
|
||||
}: {
|
||||
username: string;
|
||||
email: string;
|
||||
password: string;
|
||||
passwordConfirmation: string;
|
||||
}): Promise<ApiResponse<{ signedSession?: string }>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/create_account`;
|
||||
const body = {
|
||||
email_address: email,
|
||||
password,
|
||||
password_confirmation: passwordConfirmation,
|
||||
username,
|
||||
};
|
||||
return await this.post<
|
||||
{
|
||||
username: string;
|
||||
email_address: string;
|
||||
password: string;
|
||||
password_confirmation: string;
|
||||
},
|
||||
{
|
||||
success: boolean;
|
||||
signed_session?: string;
|
||||
error_fields?: Record<string, string>;
|
||||
error_message?: string;
|
||||
error_type?: string;
|
||||
}
|
||||
>({
|
||||
endpoint: endpoint,
|
||||
body: body,
|
||||
})
|
||||
.then((response) => {
|
||||
return {
|
||||
success: response.success,
|
||||
data: { signedSession: response.signed_session },
|
||||
errorMessage: Object.values(response.error_fields ?? {}).join(","),
|
||||
};
|
||||
})
|
||||
.catch((err) => {
|
||||
return {
|
||||
success: false,
|
||||
error_message: err.message,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,9 @@
|
||||
// https://storyteller-docs.netlify.app/#/
|
||||
export * from "./AnalyticsApi";
|
||||
export * from "./BetaKeysApi";
|
||||
export * from "./BillingApi";
|
||||
export * from "./CommentsApi";
|
||||
export * from "./EngineApi";
|
||||
export * from "./FeaturedItemsApi";
|
||||
export * from "./JobsApi";
|
||||
export * from "./MediaFilesApi";
|
||||
export * from "./MediaUploadApi";
|
||||
export * from "./MiscApi";
|
||||
export * from "./ModerationApi";
|
||||
export * from "./PromptsApi";
|
||||
export * from "./TtsApi";
|
||||
export * from "./UserBookmarksApi";
|
||||
export * from "./UsersApi";
|
||||
export * from "./VideoApi";
|
||||
export * from "./WeightsApi";
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useEffect, useState } from "react";
|
||||
import { Button } from "~/components/ui"
|
||||
|
||||
const testUrl = "https://api.fakeyou.com/v1/media_files/list/user/hanashi?include_user_uploads=true&page_size=24&filter_media_classes=unknown";
|
||||
|
||||
const getTestData = (callback: (data: any) => void) => {
|
||||
const netCall = async () => {
|
||||
// GET the test url
|
||||
|
||||
@@ -1,607 +0,0 @@
|
||||
import Konva from "konva";
|
||||
import { Container } from "konva/lib/Container";
|
||||
import { Shape } from "konva/lib/Shape";
|
||||
import { Group } from "konva/lib/Group";
|
||||
|
||||
import { DiffusionSharedWorkerClient } from "../SharedWorkers/Diffusion/DiffusionSharedWorkerClient";
|
||||
import {
|
||||
// SharedWorkerRequest,
|
||||
SharedWorkerResponse,
|
||||
} from "../WorkerPrimitives/SharedWorkerBase";
|
||||
import {
|
||||
DiffusionSharedWorkerProgressData,
|
||||
DiffusionSharedWorkerResponseData,
|
||||
// DiffusionSharedWorker,
|
||||
DiffusionSharedWorkerItemData,
|
||||
} from "../SharedWorkers/Diffusion/DiffusionSharedWorker";
|
||||
|
||||
import { RenderingOptions } from "../Engine";
|
||||
import { FileUtilities } from "../FileUtilities/FileUtilities";
|
||||
import { ImageNode, VideoNode, TextNode } from "../Nodes";
|
||||
import { MediaNode } from "../types";
|
||||
|
||||
import { RenderTask } from "./RenderTask";
|
||||
import { OffScreenSceneCanvas } from "./OffScreenSceneCanvas";
|
||||
|
||||
// https://www.aiseesoft.com/resource/phone-aspect-ratio-screen-resolution.html#:~:text=16%3A9%20Aspect%20Ratio
|
||||
|
||||
export class RenderEngine {
|
||||
private videoNodes: VideoNode[];
|
||||
private imageNodes: (ImageNode | TextNode)[];
|
||||
|
||||
private offScreenCanvas: OffscreenCanvas;
|
||||
private context: OffscreenCanvasRenderingContext2D | null;
|
||||
|
||||
private isProcessing: boolean;
|
||||
|
||||
// private frames: ImageBitmap[];
|
||||
|
||||
// capturing composite within window
|
||||
private bgLayerRef: Konva.Layer;
|
||||
private mediaLayerRef: Konva.Layer;
|
||||
|
||||
private height: number;
|
||||
private width: number;
|
||||
private positionX: number;
|
||||
private positionY: number;
|
||||
|
||||
private canUseSharedWorker: boolean;
|
||||
|
||||
private port: MessagePort | undefined;
|
||||
private upperMaxFrames: number;
|
||||
|
||||
public captureCanvas: Konva.Rect;
|
||||
|
||||
public videoLoadingCanvas: VideoNode | undefined;
|
||||
|
||||
public fps: number = 24;
|
||||
constructor({
|
||||
width,
|
||||
height,
|
||||
bgLayerRef,
|
||||
mediaLayerRef,
|
||||
offScreenCanvas,
|
||||
onRenderingSystemMessageRecieved,
|
||||
}: {
|
||||
width: number;
|
||||
height: number;
|
||||
bgLayerRef: Konva.Layer;
|
||||
mediaLayerRef: Konva.Layer;
|
||||
offScreenCanvas: OffscreenCanvas;
|
||||
onRenderingSystemMessageRecieved: (
|
||||
response: SharedWorkerResponse<
|
||||
DiffusionSharedWorkerResponseData,
|
||||
DiffusionSharedWorkerProgressData
|
||||
>,
|
||||
) => void;
|
||||
}) {
|
||||
this.videoLoadingCanvas = undefined;
|
||||
this.videoNodes = [];
|
||||
this.imageNodes = [];
|
||||
|
||||
this.isProcessing = false;
|
||||
this.onRenderingSystemMessageRecieved = onRenderingSystemMessageRecieved;
|
||||
// TODO: Make this dynamic and update this on change of canvas.
|
||||
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.positionX = window.innerWidth / 2 - this.width / 2;
|
||||
this.positionY = window.innerHeight / 2 - this.height / 2;
|
||||
|
||||
this.offScreenCanvas = offScreenCanvas;
|
||||
this.offScreenCanvas.width = this.width;
|
||||
this.offScreenCanvas.height = this.height;
|
||||
this.context = this.offScreenCanvas.getContext("2d");
|
||||
|
||||
// this.frames = [];
|
||||
|
||||
this.bgLayerRef = bgLayerRef;
|
||||
this.mediaLayerRef = mediaLayerRef;
|
||||
|
||||
this.port = undefined;
|
||||
|
||||
this.fps = 24;
|
||||
|
||||
this.captureCanvas = new Konva.Rect({
|
||||
name: "CaptureCanvas",
|
||||
x: this.positionX,
|
||||
y: this.positionY,
|
||||
width: this.width,
|
||||
height: this.height,
|
||||
fill: "white",
|
||||
stroke: "black",
|
||||
strokeWidth: 1,
|
||||
draggable: false,
|
||||
});
|
||||
|
||||
this.upperMaxFrames = 7 * this.fps; // seconds by fps
|
||||
|
||||
this.bgLayerRef.add(this.captureCanvas);
|
||||
// send back
|
||||
this.captureCanvas.setZIndex(0);
|
||||
|
||||
this.canUseSharedWorker = false;
|
||||
this.setupSharedWorker();
|
||||
|
||||
//this.debug();
|
||||
}
|
||||
|
||||
private onRenderingSystemMessageRecieved: (
|
||||
response: SharedWorkerResponse<
|
||||
DiffusionSharedWorkerResponseData,
|
||||
DiffusionSharedWorkerProgressData
|
||||
>,
|
||||
) => void;
|
||||
|
||||
private diffusionWorker:
|
||||
| DiffusionSharedWorkerClient<
|
||||
DiffusionSharedWorkerItemData,
|
||||
DiffusionSharedWorkerResponseData,
|
||||
DiffusionSharedWorkerProgressData
|
||||
>
|
||||
| undefined;
|
||||
|
||||
async updateCaptureCanvas(
|
||||
width: number | undefined,
|
||||
height: number | undefined,
|
||||
) {
|
||||
if (!this.captureCanvas) {
|
||||
return;
|
||||
}
|
||||
if (width) {
|
||||
this.width = width;
|
||||
}
|
||||
if (height) {
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
// Ensures that all the nodes stag in the same place should
|
||||
// there be a window resize.
|
||||
// recompute the position
|
||||
// to ensure that the position of this stays
|
||||
|
||||
const oldPositionX = this.positionX;
|
||||
const oldPositionY = this.positionY;
|
||||
|
||||
// recompute the position
|
||||
this.positionX = window.innerWidth / 2 - this.width / 2;
|
||||
this.positionY = window.innerHeight / 2 - this.height / 2;
|
||||
|
||||
this.captureCanvas.setPosition({ x: this.positionX, y: this.positionY });
|
||||
this.captureCanvas.size({ width: this.width, height: this.height });
|
||||
|
||||
// this is the change in positions
|
||||
const deltaX = this.positionX - oldPositionX;
|
||||
const deltaY = this.positionY - oldPositionY;
|
||||
|
||||
var children = this.mediaLayerRef.getChildren();
|
||||
for (let i = 0; i < children.length; i++) {
|
||||
let node = children[i];
|
||||
|
||||
// skip the capture canvas update.
|
||||
if (node.name() === "CaptureCanvas") {
|
||||
continue;
|
||||
}
|
||||
const pos = node.getPosition();
|
||||
node.setPosition({
|
||||
x: pos.x + deltaX,
|
||||
y: pos.y + deltaY,
|
||||
});
|
||||
}
|
||||
|
||||
// update the context menu
|
||||
// TODO: find selected node and update that position
|
||||
// this.videoNodes.forEach((node) => {
|
||||
// node.updateContextComponents();
|
||||
// });
|
||||
|
||||
this.mediaLayerRef.batchDraw();
|
||||
}
|
||||
|
||||
debug() {
|
||||
// DEBUG ONLY
|
||||
const rectangle = new Konva.Rect({
|
||||
x: this.positionX,
|
||||
y: this.positionY,
|
||||
width: 100,
|
||||
height: 100,
|
||||
fill: "green",
|
||||
stroke: "black",
|
||||
strokeWidth: 1,
|
||||
draggable: false,
|
||||
});
|
||||
this.mediaLayerRef.add(rectangle);
|
||||
}
|
||||
|
||||
async sendCanvasPayload(renderTask: RenderTask) {
|
||||
if (!this.port) {
|
||||
return console.log("Undefined Worker");
|
||||
}
|
||||
this.port.postMessage(renderTask);
|
||||
}
|
||||
|
||||
setupSharedWorker() {
|
||||
if (typeof SharedWorker !== "undefined") {
|
||||
console.log("Shared Workers are supported in this browser.");
|
||||
// Debug chrome://inspect/#workers
|
||||
// "src\\KonvaApp\\SharedWorkers\\Diffusion\\DiffusionSharedWorker.ts",
|
||||
this.diffusionWorker = new DiffusionSharedWorkerClient(
|
||||
this.onRenderingSystemMessageRecieved,
|
||||
);
|
||||
|
||||
this.canUseSharedWorker = true;
|
||||
} else {
|
||||
console.log("Shared Workers are not supported in this browser.");
|
||||
// Handle the lack of Shared Worker support (e.g., fallback to another solution)
|
||||
this.canUseSharedWorker = false;
|
||||
}
|
||||
}
|
||||
|
||||
public placeDebugRect(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
layer: Konva.Layer,
|
||||
): void {
|
||||
const rect = new Konva.Rect({
|
||||
x: x,
|
||||
y: y,
|
||||
width: width, // Default width
|
||||
height: height, // Default height
|
||||
fill: "green",
|
||||
draggable: false,
|
||||
});
|
||||
|
||||
layer.add(rect);
|
||||
layer.draw();
|
||||
}
|
||||
|
||||
// This function uses a portion of the video layer to capture just the capture canvas.
|
||||
// capture everything after seeking each video node.
|
||||
renderPortionOfLayer(
|
||||
layer: Konva.Layer,
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
): HTMLCanvasElement {
|
||||
const canvas = layer.toCanvas({
|
||||
x: x,
|
||||
y: y,
|
||||
width: width,
|
||||
height: height,
|
||||
});
|
||||
return canvas;
|
||||
}
|
||||
|
||||
private findLongestVideoLength(): number {
|
||||
let maxLength = 0;
|
||||
// could simplify this logic to ensure that imageNodes has number of frames.
|
||||
if (this.imageNodes.length > 0 && this.videoNodes.length === 0) {
|
||||
return this.fps * 3; // three seconds determine whether to change this
|
||||
}
|
||||
|
||||
this.videoNodes.forEach((node) => {
|
||||
const videoLength = node.getNumberFrames();
|
||||
if (videoLength > maxLength) {
|
||||
maxLength = videoLength;
|
||||
}
|
||||
});
|
||||
return maxLength;
|
||||
}
|
||||
|
||||
public addNodes(node: MediaNode) {
|
||||
if (node instanceof VideoNode) {
|
||||
this.videoNodes.push(node);
|
||||
} else if (node instanceof ImageNode || node instanceof TextNode) {
|
||||
this.imageNodes.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
public removeNodes(node: MediaNode) {
|
||||
if (node instanceof VideoNode) {
|
||||
const index = this.videoNodes.indexOf(node);
|
||||
if (index > -1) {
|
||||
this.videoNodes.splice(index, 1);
|
||||
}
|
||||
} else if (node instanceof ImageNode || node instanceof TextNode) {
|
||||
const index = this.imageNodes.indexOf(node);
|
||||
if (index > -1) {
|
||||
this.imageNodes.splice(index, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Do a bunch of precondition checks and error out early on.
|
||||
public async startProcessing(renderingOptions?: RenderingOptions) {
|
||||
// Start processing and lock everything
|
||||
|
||||
this.isProcessing = true;
|
||||
|
||||
try {
|
||||
// or not loaded
|
||||
if (this.videoNodes.length + this.imageNodes.length < 1) {
|
||||
throw Error("Must at least have 1 item on the board.");
|
||||
}
|
||||
// error out if nodes are not all loaded.
|
||||
// todo remove when we have error handling + and ui
|
||||
var failed = false;
|
||||
|
||||
// if there are atleast 1 video node images are all covered.
|
||||
for (let i = 0; i < this.videoNodes.length; i++) {
|
||||
const item = this.videoNodes[i];
|
||||
if (!item.kNode) {
|
||||
return;
|
||||
}
|
||||
item.kNode.listening(false);
|
||||
item.unhighlight();
|
||||
if (item.didFinishLoading == false) {
|
||||
// error out and show error message
|
||||
//this.startProcessing();
|
||||
failed = true;
|
||||
setTimeout(this.startProcessing.bind(this), 1000);
|
||||
break;
|
||||
}
|
||||
item.setProcessing(true);
|
||||
}
|
||||
|
||||
// todo remove
|
||||
if (failed) {
|
||||
// throw error
|
||||
throw Error("Wait For Items to Finish Processing.");
|
||||
}
|
||||
|
||||
//this.videoNodes.forEach((item: VideoNode) => {});
|
||||
|
||||
// find the longest video node
|
||||
let numberOfFrames = this.findLongestVideoLength();
|
||||
numberOfFrames = Math.min(numberOfFrames, this.upperMaxFrames);
|
||||
console.log(`Number Of Frames: ${numberOfFrames}`);
|
||||
|
||||
await this.render(numberOfFrames, renderingOptions);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
throw error;
|
||||
} finally {
|
||||
this.isProcessing = false;
|
||||
|
||||
// enable all nodes again.
|
||||
for (let i = 0; i < this.videoNodes.length; i++) {
|
||||
const item = this.videoNodes[i];
|
||||
if (!item.kNode) {
|
||||
return;
|
||||
}
|
||||
item.setProcessing(false);
|
||||
item.kNode.listening(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// public stopProcessing() {
|
||||
// this.isProcessing = false;
|
||||
// }
|
||||
|
||||
// find the frame time given the frame number
|
||||
private calculateFrameTime(frameNumber: number, frameRate: number): number {
|
||||
return frameNumber / frameRate;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param config
|
||||
*/
|
||||
private async renderFrame(config: {
|
||||
layerOfInterest: Konva.Layer; // layer where the element that you want to clip lives.
|
||||
// XY and height of a captureCanvas ( region of interest )
|
||||
x?: number; // x position of the region of interest
|
||||
y?: number; // y position of the region of interest
|
||||
width?: number; // size of the region of interest
|
||||
height?: number; // size of the region of interest
|
||||
pixelRatio?: number; // higher means higher quality
|
||||
mimeType?: string; // image/jpeg or image/png
|
||||
quality?: number; // 1.0 is the best.
|
||||
test: boolean; // true == blob else Image Bitmap
|
||||
}): Promise<ImageBitmap | Blob> {
|
||||
try {
|
||||
const box = config.layerOfInterest.getClientRect();
|
||||
const stage = config.layerOfInterest.getStage();
|
||||
|
||||
const x = config.x !== undefined ? config.x : Math.floor(box.x);
|
||||
const y = config.y !== undefined ? config.y : Math.floor(box.y);
|
||||
const pixelRatio = config.pixelRatio || 1;
|
||||
|
||||
const container = config.layerOfInterest as Container<Group | Shape>;
|
||||
|
||||
const offScreenSceneCanvas = new OffScreenSceneCanvas({
|
||||
width:
|
||||
config.width || Math.ceil(box.width) || (stage ? stage.width() : 0),
|
||||
height:
|
||||
config.height ||
|
||||
Math.ceil(box.height) ||
|
||||
(stage ? stage.height() : 0),
|
||||
pixelRatio: pixelRatio,
|
||||
});
|
||||
|
||||
// TODO: fill canvas white properly
|
||||
const context = offScreenSceneCanvas.getContext();
|
||||
// context.fillStyle = "white";
|
||||
// context.fillRect(
|
||||
// 0,
|
||||
// 0,
|
||||
// offScreenSceneCanvas.width,
|
||||
// offScreenSceneCanvas.height,
|
||||
// );
|
||||
|
||||
const buffer = new OffScreenSceneCanvas({
|
||||
width:
|
||||
offScreenSceneCanvas.width / offScreenSceneCanvas.pixelRatio +
|
||||
Math.abs(x),
|
||||
height:
|
||||
offScreenSceneCanvas.height / offScreenSceneCanvas.pixelRatio +
|
||||
Math.abs(y),
|
||||
pixelRatio: offScreenSceneCanvas.pixelRatio,
|
||||
});
|
||||
|
||||
context.save();
|
||||
|
||||
if (x || y) {
|
||||
context.translate(-1 * x, -1 * y);
|
||||
}
|
||||
container.drawScene(offScreenSceneCanvas, undefined, buffer);
|
||||
// Not a type mistake ... DO NOT FIX
|
||||
// @ts-ignore
|
||||
const offscreenCanvas = offScreenSceneCanvas._canvas as OffscreenCanvas;
|
||||
let result = undefined;
|
||||
|
||||
// if config.test is true, the result is downloaded to the local files
|
||||
// config.test = true;
|
||||
if (config.test) {
|
||||
const blob = await offscreenCanvas.convertToBlob({
|
||||
quality: config.quality ?? 1.0,
|
||||
type: "image/jpeg",
|
||||
});
|
||||
await FileUtilities.blobToFileJpeg(blob, "1");
|
||||
result = blob;
|
||||
} else {
|
||||
result = offscreenCanvas.transferToImageBitmap();
|
||||
}
|
||||
context.restore();
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
find longest video
|
||||
then seek through each node 1 step.
|
||||
stop ignore stepping if the duration is less.
|
||||
**/
|
||||
private async render(
|
||||
largestNumberOfFrames: number,
|
||||
renderingOptions?: RenderingOptions,
|
||||
) {
|
||||
if (!this.isProcessing) return;
|
||||
|
||||
// Stop all nodes first
|
||||
console.log(`LargestNumberOfFrames:${largestNumberOfFrames}`);
|
||||
for (let k = 0; k < this.videoNodes.length; k++) {
|
||||
const videoNode = this.videoNodes[k];
|
||||
if (videoNode.didFinishLoading === false) {
|
||||
throw Error("Videos Did Not Finish Loading Please Try Again.");
|
||||
}
|
||||
await videoNode.reset();
|
||||
}
|
||||
|
||||
// only pick nodes that intersect with the canvas on screen bounds to freeze.
|
||||
for (let j = 0; j < largestNumberOfFrames; j++) {
|
||||
// Seek Video Nodes first then draw
|
||||
let frameTime = undefined;
|
||||
|
||||
for (let i = 0; i < this.videoNodes.length; i++) {
|
||||
const currentVideoNode = this.videoNodes[i];
|
||||
frameTime = this.calculateFrameTime(j, currentVideoNode.fps);
|
||||
frameTime = parseFloat(frameTime.toFixed(2));
|
||||
if (frameTime < currentVideoNode.duration) {
|
||||
// console.log(`CurrentFrame:${j}`);
|
||||
// console.log(`FrameTime:${frameTime}`);
|
||||
// console.log(`Duration:${currentVideoNode.duration}`);
|
||||
await currentVideoNode.seek(frameTime);
|
||||
} // end of if context
|
||||
} // End frame time
|
||||
this.mediaLayerRef.draw();
|
||||
|
||||
// use main thread
|
||||
if (this.canUseSharedWorker === false) {
|
||||
// SCOPES the capture for the context
|
||||
// Correct size for the mobile canvas.
|
||||
this.offScreenCanvas.width = this.width;
|
||||
this.offScreenCanvas.height = this.height;
|
||||
if (this.context) {
|
||||
// This crops it starting at position X / Y where the mobile canvas is
|
||||
// Then picks the height and width range
|
||||
// then we draw it at 0,0,width and height of the canvas
|
||||
this.context.drawImage(
|
||||
this.mediaLayerRef.canvas._canvas,
|
||||
this.positionX,
|
||||
this.positionY,
|
||||
this.width,
|
||||
this.height,
|
||||
0,
|
||||
0,
|
||||
this.width,
|
||||
this.height,
|
||||
);
|
||||
//TODO write the non webworker version
|
||||
const blob = await this.offScreenCanvas.convertToBlob({
|
||||
quality: 1.0,
|
||||
type: "image/jpeg",
|
||||
});
|
||||
await FileUtilities.blobToFileJpeg(blob, "1");
|
||||
|
||||
break;
|
||||
} // end of for each frame
|
||||
} else {
|
||||
// decode on the shared webworker.
|
||||
if (!this.context) {
|
||||
console.log("Context Didn't Initialize");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.diffusionWorker) {
|
||||
console.log("Didn't Initialize Diffusion");
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(
|
||||
`context: x:${this.positionX} y:${this.positionY} ${this.width} x ${this.height}`,
|
||||
);
|
||||
|
||||
const bitmap = await this.renderFrame({
|
||||
layerOfInterest: this.mediaLayerRef,
|
||||
x: this.captureCanvas.x(),
|
||||
y: this.captureCanvas.y(),
|
||||
width: this.width,
|
||||
height: this.height,
|
||||
mimeType: "image/jpeg",
|
||||
pixelRatio: 1,
|
||||
quality: 1.0,
|
||||
test: false,
|
||||
});
|
||||
|
||||
const data: DiffusionSharedWorkerItemData = {
|
||||
height: this.height,
|
||||
width: this.width,
|
||||
imageBitmap: bitmap as ImageBitmap,
|
||||
frame: j,
|
||||
totalFrames: largestNumberOfFrames,
|
||||
prompt: renderingOptions,
|
||||
};
|
||||
console.log(
|
||||
`Processing Frame:${j + 1} out of ${largestNumberOfFrames}`,
|
||||
);
|
||||
this.diffusionWorker.sendData(1, data, false);
|
||||
}
|
||||
} // end of largest number of frames loop
|
||||
|
||||
// finished looping
|
||||
if (!this.diffusionWorker) {
|
||||
console.log("Didn't Initialize Diffusion");
|
||||
return;
|
||||
}
|
||||
|
||||
const jobID = 1;
|
||||
this.diffusionWorker.sendData(
|
||||
jobID,
|
||||
{
|
||||
height: this.height,
|
||||
width: this.width,
|
||||
imageBitmap: undefined,
|
||||
frame: -1,
|
||||
totalFrames: largestNumberOfFrames,
|
||||
prompt: renderingOptions,
|
||||
},
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,396 +0,0 @@
|
||||
// Example of this working.
|
||||
|
||||
import { BlobReader, BlobWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { MediaUploadApi, VideoApi, MediaFilesApi } from "~/Classes/ApiManager";
|
||||
import { Visibility } from "~/Classes/ApiManager/enums/Visibility";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { JobsApi } from "~/Classes/ApiManager";
|
||||
import {
|
||||
ProgressData,
|
||||
WorkResult,
|
||||
} from "~/KonvaApp/WorkerPrimitives/GenericWorker";
|
||||
|
||||
import {
|
||||
SharedWorkerBase,
|
||||
SharedWorkerRequest,
|
||||
SharedWorkerResponse,
|
||||
ResponseType,
|
||||
} from "~/KonvaApp/WorkerPrimitives/SharedWorkerBase";
|
||||
import { JobStatus } from "~/Classes/ApiManager/enums/Job";
|
||||
import { RenderingOptions } from "~/KonvaApp/Engine";
|
||||
import { MediaFile } from "~/Classes/ApiManager/models/MediaFile";
|
||||
|
||||
export interface DiffusionSharedWorkerProgressData {
|
||||
url: string;
|
||||
status: JobStatus;
|
||||
progress: number;
|
||||
mediaToken: string;
|
||||
}
|
||||
|
||||
export interface DiffusionSharedWorkerItemData {
|
||||
imageBitmap: ImageBitmap | undefined;
|
||||
totalFrames: number;
|
||||
frame: number;
|
||||
height: number;
|
||||
width: number;
|
||||
prompt?: RenderingOptions;
|
||||
}
|
||||
|
||||
export interface DiffusionSharedWorkerErrorData {
|
||||
error: string;
|
||||
}
|
||||
export interface DiffusionSharedWorkerResponseData {
|
||||
videoUrl: string;
|
||||
}
|
||||
|
||||
export class DiffusionSharedWorker extends SharedWorkerBase<
|
||||
DiffusionSharedWorkerItemData,
|
||||
DiffusionSharedWorkerResponseData | MediaFile,
|
||||
DiffusionSharedWorkerProgressData
|
||||
> {
|
||||
public name: string;
|
||||
public zipFileWriter: BlobWriter;
|
||||
public zipWriter: ZipWriter<Blob>;
|
||||
public imageType: string;
|
||||
public totalFrames: number;
|
||||
|
||||
public offscreenCanvas: OffscreenCanvas | undefined;
|
||||
public bitmapContext: ImageBitmapRenderingContext | undefined | null;
|
||||
|
||||
public mediaAPI: MediaUploadApi;
|
||||
public mediaFilesAPI: MediaFilesApi;
|
||||
public videoAPI: VideoApi;
|
||||
public jobsAPI: JobsApi;
|
||||
public blobs: Blob[];
|
||||
|
||||
constructor(port: MessagePort) {
|
||||
super(port);
|
||||
this.name = "DiffusionWorker";
|
||||
this.setup(this.workFunction.bind(this), this.progressFunction.bind(this));
|
||||
this.offscreenCanvas = undefined;
|
||||
this.bitmapContext = undefined;
|
||||
this.imageType = "image/jpeg";
|
||||
this.zipFileWriter = new BlobWriter(this.imageType);
|
||||
this.zipWriter = new ZipWriter(this.zipFileWriter);
|
||||
this.totalFrames = 0;
|
||||
|
||||
this.videoAPI = new VideoApi();
|
||||
this.jobsAPI = new JobsApi();
|
||||
this.mediaAPI = new MediaUploadApi();
|
||||
this.mediaFilesAPI = new MediaFilesApi();
|
||||
|
||||
this.blobs = [];
|
||||
|
||||
this.totalFrames = 0;
|
||||
}
|
||||
|
||||
async zipBlobs(): Promise<Blob> {
|
||||
for (let i = 0; i < this.blobs.length; i++) {
|
||||
const blob = this.blobs[i];
|
||||
const name = String(i).padStart(5, "0"); // '0009'
|
||||
await this.zipWriter.add(`${name}.jpg`, new BlobReader(blob));
|
||||
}
|
||||
const zipBlob = await this.zipWriter.close();
|
||||
|
||||
return zipBlob;
|
||||
}
|
||||
|
||||
async reset() {
|
||||
this.zipFileWriter = new BlobWriter(this.imageType);
|
||||
this.zipWriter = new ZipWriter(this.zipFileWriter);
|
||||
this.totalFrames = 0;
|
||||
this.blobs = [];
|
||||
}
|
||||
// Data here will be shipped off for progressive loading
|
||||
async workFunction(
|
||||
isDoneStreaming: boolean,
|
||||
item: DiffusionSharedWorkerItemData,
|
||||
reportProgress: (data: DiffusionSharedWorkerProgressData) => void,
|
||||
): Promise<
|
||||
[DiffusionSharedWorkerResponseData | MediaFile | undefined, boolean]
|
||||
> {
|
||||
// make request via api with options
|
||||
|
||||
try {
|
||||
this.totalFrames = item.totalFrames;
|
||||
|
||||
if (this.offscreenCanvas === undefined) {
|
||||
this.offscreenCanvas = new OffscreenCanvas(item.width, item.height);
|
||||
this.bitmapContext = this.offscreenCanvas.getContext("bitmaprenderer");
|
||||
}
|
||||
|
||||
if (!this.bitmapContext) {
|
||||
console.log("Failed to create bitmap context.");
|
||||
throw Error("Bitmap Rendering Context Not Availible.");
|
||||
}
|
||||
|
||||
if (item.imageBitmap !== undefined) {
|
||||
this.bitmapContext.transferFromImageBitmap(item.imageBitmap);
|
||||
|
||||
const blob = await this.offscreenCanvas.convertToBlob({
|
||||
quality: 1.0,
|
||||
type: this.imageType,
|
||||
});
|
||||
|
||||
this.blobs.push(blob);
|
||||
console.log("Length of blob");
|
||||
console.log(this.blobs.length);
|
||||
}
|
||||
|
||||
// progress
|
||||
const aproxSteps = this.totalFrames;
|
||||
const totalPercent = item.prompt ? 0.25 : 0.9;
|
||||
|
||||
const progressData: DiffusionSharedWorkerProgressData = {
|
||||
url: "",
|
||||
status: JobStatus.PENDING,
|
||||
progress: (item.frame / aproxSteps) * totalPercent,
|
||||
mediaToken: "",
|
||||
};
|
||||
|
||||
console.log("Lets report progress.");
|
||||
reportProgress(progressData); // once finished gives you up to 50%
|
||||
|
||||
if (isDoneStreaming === false) {
|
||||
return [undefined, false];
|
||||
}
|
||||
|
||||
console.log("Prepare to Zip");
|
||||
const zipBlob = await this.zipBlobs();
|
||||
console.log("Zipped", zipBlob);
|
||||
|
||||
const progressMedia: DiffusionSharedWorkerProgressData = {
|
||||
url: "",
|
||||
status: JobStatus.PENDING,
|
||||
progress: ((item.frame + 0.5) / aproxSteps) * totalPercent,
|
||||
mediaToken: "",
|
||||
};
|
||||
|
||||
console.log("Lets report progress.");
|
||||
reportProgress(progressMedia); // once finished gives you up to 50%
|
||||
|
||||
const response = await this.mediaAPI.UploadStudioShot({
|
||||
maybe_title: "",
|
||||
uuid_idempotency_token: uuidv4(),
|
||||
blob: zipBlob,
|
||||
fileName: "media.zip",
|
||||
maybe_visibility: Visibility.Public,
|
||||
});
|
||||
|
||||
const mediaToken = response.data;
|
||||
|
||||
if (!mediaToken) {
|
||||
this.reset();
|
||||
throw Error(`Server Failed Try Again: ${response.errorMessage}`);
|
||||
}
|
||||
if (!item.prompt) {
|
||||
console.log("got video >>", response);
|
||||
const videoRepsonse = await this.mediaFilesAPI.GetMediaFileByToken({
|
||||
mediaFileToken: mediaToken,
|
||||
});
|
||||
this.reset();
|
||||
return [videoRepsonse.data, true];
|
||||
}
|
||||
console.log(item.prompt);
|
||||
const studioResponse = await this.videoAPI.EnqueueStudio({
|
||||
enqueueVideo: {
|
||||
disable_lcm: false,
|
||||
enable_lipsync: item.prompt.lipSync,
|
||||
input_file: mediaToken, // Replace with actual media token
|
||||
negative_prompt: item.prompt.negativePrompt,
|
||||
prompt: item.prompt.positivePrompt,
|
||||
remove_watermark: false,
|
||||
style: item.prompt.artstyle, // Map to the appropriate art style
|
||||
frame_skip: 2,
|
||||
travel_prompt: "",
|
||||
trim_end_millis: 7000,
|
||||
trim_start_millis: 0,
|
||||
use_cinematic: item.prompt.cinematic,
|
||||
use_face_detailer: item.prompt.faceDetail,
|
||||
use_strength: item.prompt.styleStrength,
|
||||
use_upscaler: item.prompt.upscale,
|
||||
uuid_idempotency_token: uuidv4(),
|
||||
global_ipa_media_token: "",
|
||||
input_depth_file: "",
|
||||
input_normal_file: "",
|
||||
input_outline_file: "",
|
||||
creator_set_visibility: Visibility.Public,
|
||||
},
|
||||
});
|
||||
|
||||
let resultURL = undefined;
|
||||
|
||||
if (studioResponse.success && studioResponse.data?.inference_job_token) {
|
||||
console.log("Start Streaming Result");
|
||||
if (!studioResponse.data.inference_job_token) {
|
||||
await this.reset(); // reset on error
|
||||
throw Error("No Job Token Returned Try Again");
|
||||
}
|
||||
const jobToken = studioResponse.data.inference_job_token;
|
||||
|
||||
// if error send it back through the pipe
|
||||
let jobIsProcessing = true;
|
||||
|
||||
while (jobIsProcessing) {
|
||||
const job = await this.jobsAPI.GetJobByToken({ token: jobToken });
|
||||
|
||||
// TODO: MAKE REQUEST FOR PREVIEW HERE
|
||||
console.log(job);
|
||||
if (!job.data) {
|
||||
console.log("No Job Data resetting the zip state");
|
||||
await this.reset();
|
||||
console.log(job.data);
|
||||
continue;
|
||||
}
|
||||
const status = job.data.status.status;
|
||||
const progress = job.data.status.progress_percentage;
|
||||
|
||||
let computedProgress = 30;
|
||||
if (progress === 0) {
|
||||
computedProgress = 30;
|
||||
}
|
||||
computedProgress = 30 + progress * 0.7;
|
||||
|
||||
let renderProgressData: DiffusionSharedWorkerProgressData = {
|
||||
url: "",
|
||||
status: status,
|
||||
progress: computedProgress / 100,
|
||||
mediaToken: mediaToken,
|
||||
};
|
||||
|
||||
renderProgressData.status = status;
|
||||
|
||||
switch (status) {
|
||||
case JobStatus.PENDING:
|
||||
console.log("Pending");
|
||||
reportProgress(renderProgressData); // once finished gives you up to 50%
|
||||
break;
|
||||
case JobStatus.STARTED:
|
||||
console.log("Started");
|
||||
reportProgress(renderProgressData);
|
||||
break;
|
||||
case JobStatus.ATTEMPT_FAILED:
|
||||
console.log("Attempt Failed");
|
||||
reportProgress(renderProgressData);
|
||||
break;
|
||||
case JobStatus.COMPLETE_SUCCESS:
|
||||
console.log("Complete Success");
|
||||
renderProgressData.progress = 100;
|
||||
jobIsProcessing = false;
|
||||
if (!job.data.maybe_result.media_links.cdn_url) {
|
||||
await this.reset();
|
||||
throw Error("Server Failed To Return Result");
|
||||
}
|
||||
resultURL = job.data.maybe_result.media_links.cdn_url;
|
||||
reportProgress(renderProgressData);
|
||||
break;
|
||||
case JobStatus.COMPLETE_FAILURE:
|
||||
console.log("Complete Failure");
|
||||
jobIsProcessing = false;
|
||||
renderProgressData.progress = 0;
|
||||
reportProgress(renderProgressData);
|
||||
break;
|
||||
case JobStatus.DEAD:
|
||||
console.log("Dead");
|
||||
jobIsProcessing = false;
|
||||
reportProgress(renderProgressData);
|
||||
throw Error("Server Failed to Process Please Try Again.");
|
||||
case JobStatus.CANCELLED_BY_SYSTEM:
|
||||
console.log("Cancelled by system");
|
||||
jobIsProcessing = false;
|
||||
reportProgress(renderProgressData);
|
||||
break;
|
||||
case JobStatus.CANCELLED_BY_USER:
|
||||
console.log("Cancelled by user");
|
||||
jobIsProcessing = false;
|
||||
reportProgress(renderProgressData);
|
||||
break;
|
||||
}
|
||||
await this.sleep(500);
|
||||
} // end while loop
|
||||
}
|
||||
if (!resultURL) {
|
||||
await this.reset(); // reset on error
|
||||
throw Error("Media URL Result Missing");
|
||||
}
|
||||
|
||||
const responseData: DiffusionSharedWorkerResponseData = {
|
||||
videoUrl: resultURL,
|
||||
};
|
||||
await this.reset();
|
||||
return [responseData, true];
|
||||
} catch (error) {
|
||||
await this.reset();
|
||||
console.log(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
progressFunction(progress: ProgressData<DiffusionSharedWorkerProgressData>) {
|
||||
console.log(
|
||||
`Progress Function JobID:${progress.jobID} Data:${progress.data}`,
|
||||
);
|
||||
|
||||
// send out to node as a worker response
|
||||
this.send({
|
||||
jobID: progress.jobID,
|
||||
responseType: ResponseType.progress,
|
||||
data: progress.data,
|
||||
});
|
||||
}
|
||||
|
||||
async reportResult(result: WorkResult<DiffusionSharedWorkerResponseData>) {
|
||||
this.send({
|
||||
jobID: result.jobID,
|
||||
responseType: ResponseType.result,
|
||||
data: result.data,
|
||||
});
|
||||
}
|
||||
|
||||
async errorFunction(
|
||||
error: SharedWorkerResponse<
|
||||
DiffusionSharedWorkerItemData,
|
||||
DiffusionSharedWorkerResponseData
|
||||
>,
|
||||
) {
|
||||
this.send({
|
||||
jobID: error.jobID,
|
||||
responseType: ResponseType.error,
|
||||
data: error.data?.toString(),
|
||||
});
|
||||
}
|
||||
|
||||
async receive(request: SharedWorkerRequest<DiffusionSharedWorkerItemData>) {
|
||||
console.log("Received Request");
|
||||
console.log(request);
|
||||
this.submitWork({
|
||||
jobID: request.jobID,
|
||||
data: request.data,
|
||||
isDoneStreaming: request.isDoneStreaming,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// This is a copy paste to create a worker now.
|
||||
//@ts-ignore
|
||||
self.onconnect = (e: any) => {
|
||||
const port = e.ports[0];
|
||||
console.log("DiffusionSharedWorker Started");
|
||||
let worker: DiffusionSharedWorker | undefined = undefined;
|
||||
let started = false;
|
||||
|
||||
if (started === false) {
|
||||
started = true;
|
||||
worker = new DiffusionSharedWorker(port);
|
||||
worker.start();
|
||||
}
|
||||
|
||||
// Response For Start.
|
||||
const workerResult = "DiffusionSharedWorker Started";
|
||||
port.postMessage(workerResult);
|
||||
port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
|
||||
};
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import {
|
||||
SharedWorkerRequest,
|
||||
SharedWorkerResponse,
|
||||
} from "~/KonvaApp/WorkerPrimitives/SharedWorkerBase";
|
||||
import { ResponseType } from "~/KonvaApp/WorkerPrimitives/SharedWorkerBase";
|
||||
import DiffusionSharedWorker from "./DiffusionSharedWorker?sharedworker";
|
||||
|
||||
export class DiffusionSharedWorkerClient<
|
||||
DiffusionSharedWorkerItemData,
|
||||
DiffusionSharedWorkerResponseData,
|
||||
DiffusionSharedWorkerProgressData,
|
||||
> {
|
||||
private port: MessagePort;
|
||||
private sharedWorker: SharedWorker;
|
||||
private messageReceived: (
|
||||
response: SharedWorkerResponse<
|
||||
DiffusionSharedWorkerResponseData,
|
||||
DiffusionSharedWorkerProgressData
|
||||
>,
|
||||
) => void;
|
||||
constructor(
|
||||
messageReceived: (
|
||||
response: SharedWorkerResponse<
|
||||
DiffusionSharedWorkerResponseData,
|
||||
DiffusionSharedWorkerProgressData
|
||||
>,
|
||||
) => void,
|
||||
) {
|
||||
this.messageReceived = messageReceived;
|
||||
try {
|
||||
console.log("This is running a worker in production");
|
||||
this.sharedWorker = new DiffusionSharedWorker({
|
||||
name: "DiffusionWorker-" + uuidv4(),
|
||||
});
|
||||
|
||||
this.sharedWorker.addEventListener("error", (value) => {
|
||||
console.log("Shared worker ERROR:");
|
||||
console.log(value);
|
||||
});
|
||||
|
||||
this.port = this.sharedWorker.port;
|
||||
this.port.onmessage = this.onMessage.bind(this);
|
||||
this.port.start();
|
||||
|
||||
console.log("launched shared worker (?)");
|
||||
} catch (error) {
|
||||
console.log("ERROR with shared worker!");
|
||||
console.log(error);
|
||||
throw Error("Could Not Start Worker");
|
||||
}
|
||||
}
|
||||
|
||||
async onMessage(event: MessageEvent) {
|
||||
// returns progress and returns result need to check error tomorrow then were good to go.
|
||||
//console.log(`incoming`);
|
||||
// console.log(event);
|
||||
if (event.data.responseType === ResponseType.error) {
|
||||
console.log(`DiffusionSharedWorkerClient Error`);
|
||||
console.log(event.data);
|
||||
this.messageReceived(event.data);
|
||||
} else if (event.data.responseType === ResponseType.progress) {
|
||||
// console.log(`DiffusionSharedWorkerClient Progress`);
|
||||
//console.log(event.data);
|
||||
this.messageReceived(event.data);
|
||||
} else if (event.data.responseType === ResponseType.result) {
|
||||
// console.log(`DiffusionSharedWorkerClient Result`);
|
||||
//console.log(event.data);
|
||||
this.messageReceived(event.data);
|
||||
} else {
|
||||
console.log(`DiffusionSharedWorkerClient Message Unknown:`);
|
||||
console.log(event.data);
|
||||
}
|
||||
}
|
||||
|
||||
async sendData(
|
||||
jobID: number,
|
||||
data: DiffusionSharedWorkerItemData,
|
||||
isDoneStreaming: boolean,
|
||||
) {
|
||||
const payload: SharedWorkerRequest<DiffusionSharedWorkerItemData> = {
|
||||
jobID: jobID,
|
||||
data: data,
|
||||
isDoneStreaming: isDoneStreaming,
|
||||
};
|
||||
this.port.postMessage(payload);
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,9 @@ import { Toaster } from "~/components/ui/Toast";
|
||||
import { JobProvider } from "~/components/JobContext";
|
||||
import "./global.css";
|
||||
import { useRenderCounter } from "~/hooks/useRenderCounter";
|
||||
|
||||
import { FetchProxy as fetch } from "@storyteller/tauri-utils";
|
||||
function PostHogInit() {
|
||||
const apiKey = "phc_jBFgac0mVALAFk3negnSfYCcHgvkT00yBLQDmCDYNBb";
|
||||
const apiKey = import.meta.env.VITE_POSTHOG_API_KEY;
|
||||
posthog.init(apiKey, {
|
||||
api_host: "https://us.i.posthog.com/",
|
||||
ui_host: "https://us.i.posthog.com/",
|
||||
@@ -41,10 +41,12 @@ const App = () => {
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<JobProvider>
|
||||
<RouterProvider router={router} />
|
||||
<Toaster />
|
||||
</JobProvider>
|
||||
<PostHogProvider client={posthog}>
|
||||
<JobProvider>
|
||||
<RouterProvider router={router} />
|
||||
<Toaster />
|
||||
</JobProvider>
|
||||
</PostHogProvider>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -44,10 +44,10 @@ export const Login = () => {
|
||||
|
||||
const usernameOrEmail = form.get("usernameOrEmail")?.toString();
|
||||
const password = form.get("password")?.toString();
|
||||
|
||||
|
||||
if (usernameOrEmail && password) {
|
||||
let api = new UsersApi();
|
||||
|
||||
|
||||
let response = await api.Login({
|
||||
usernameOrEmail,
|
||||
password,
|
||||
@@ -77,6 +77,12 @@ export const Login = () => {
|
||||
|
||||
return (
|
||||
<div className="pegboard fixed flex h-full w-full flex-col items-center justify-center bg-center bg-repeat">
|
||||
<Button
|
||||
className="absolute left-4 top-4 px-3 py-2 text-sm"
|
||||
onClick={() => navigate("/")}
|
||||
>
|
||||
Back to Home
|
||||
</Button>
|
||||
<div className="mb-7 flex w-10/12 max-w-2xl items-center justify-center gap-4">
|
||||
<img
|
||||
src="/brand/artcraft-logo.png"
|
||||
@@ -99,7 +105,6 @@ export const Login = () => {
|
||||
shouldShowLoader && "opacity-0",
|
||||
)}
|
||||
>
|
||||
|
||||
<Input
|
||||
label="Username or Email"
|
||||
icon={faUser}
|
||||
@@ -127,12 +132,12 @@ export const Login = () => {
|
||||
)}
|
||||
</div>
|
||||
<div className="align-items flex w-full max-w-xl rounded-b-xl bg-ui-controls px-6 py-4">
|
||||
<a
|
||||
{/* <a
|
||||
href="https://storyteller.ai/password-reset"
|
||||
className="grow text-sm !text-primary-400 transition-all duration-150 hover:!text-primary-300"
|
||||
>
|
||||
Forgot your password?
|
||||
</a>
|
||||
</a> */}
|
||||
<div className="flex justify-end gap-1 text-sm">
|
||||
<p className="opacity-75">Don't have an account?</p>
|
||||
<Link to="/signup">Sign Up</Link>
|
||||
|
||||
@@ -75,6 +75,12 @@ export const Signup = () => {
|
||||
|
||||
return (
|
||||
<div className="pegboard fixed flex h-full w-full flex-col items-center justify-center bg-center bg-repeat">
|
||||
<Button
|
||||
className="absolute left-4 top-4 px-3 py-2 text-sm"
|
||||
onClick={() => navigate("/")}
|
||||
>
|
||||
Back to Home
|
||||
</Button>
|
||||
<div className="mb-7 flex w-10/12 max-w-2xl items-center justify-center gap-4">
|
||||
<img
|
||||
src="/brand/artcraft-logo.png"
|
||||
|
||||
@@ -1,524 +0,0 @@
|
||||
import React, { useEffect, useState, useRef } from "react";
|
||||
import {
|
||||
ServerClient,
|
||||
fileToBase64,
|
||||
base64ToImageUrl,
|
||||
} from "../PyServer/ServerClient";
|
||||
import {
|
||||
ProgressUpdateMessage,
|
||||
SetupResponse,
|
||||
GenerateResponse,
|
||||
StatusResponse,
|
||||
UpdateSettingsResponse,
|
||||
} from "../PyServer/ServerTypes";
|
||||
|
||||
// Default server URL
|
||||
const DEFAULT_SERVER_URL = "ws://localhost:8765";
|
||||
|
||||
export const ImageGenerator: React.FC = () => {
|
||||
// Server connection state
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
const [serverUrl, setServerUrl] = useState(DEFAULT_SERVER_URL);
|
||||
const clientRef = useRef<ServerClient | null>(null);
|
||||
|
||||
// Model state
|
||||
const [modelPath, setModelPath] = useState("");
|
||||
const [loraPath, setLoraPath] = useState("");
|
||||
const [isModelInitialized, setIsModelInitialized] = useState(false);
|
||||
|
||||
// Generation parameters
|
||||
const [sourceImage, setSourceImage] = useState<File | null>(null);
|
||||
const [sourceImageUrl, setSourceImageUrl] = useState<string | null>(null);
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [loraStrength, setLoraStrength] = useState(1.0);
|
||||
const [imageToImageStrength, setImageToImageStrength] = useState(0.75);
|
||||
const [steps, setSteps] = useState(4);
|
||||
const [guidanceScale, setGuidanceScale] = useState(1.0);
|
||||
const [width, setWidth] = useState(1024);
|
||||
const [height, setHeight] = useState(1024);
|
||||
|
||||
// Results and UI state
|
||||
const [generatedImageUrl, setGeneratedImageUrl] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [progress, setProgress] = useState<ProgressUpdateMessage | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
// Initialize the client
|
||||
useEffect(() => {
|
||||
const client = new ServerClient(serverUrl, {
|
||||
onOpen: () => {
|
||||
console.log("Connected to server");
|
||||
setIsConnected(true);
|
||||
setErrorMessage(null);
|
||||
|
||||
// Request status to see if model is already initialized
|
||||
client.requestStatus().catch((error) => {
|
||||
console.error("Error requesting status:", error);
|
||||
});
|
||||
},
|
||||
|
||||
onClose: () => {
|
||||
console.log("Disconnected from server");
|
||||
setIsConnected(false);
|
||||
setIsModelInitialized(false);
|
||||
},
|
||||
|
||||
onError: (error) => {
|
||||
console.error("Error:", error);
|
||||
setErrorMessage(error.error);
|
||||
setIsLoading(false);
|
||||
},
|
||||
|
||||
onProgressUpdate: (update) => {
|
||||
console.log("Progress:", update);
|
||||
setProgress(update);
|
||||
|
||||
if (update.stage !== "error") {
|
||||
setErrorMessage(null);
|
||||
}
|
||||
},
|
||||
|
||||
onSetupResponse: (response) => {
|
||||
console.log("Setup response:", response);
|
||||
setIsLoading(false);
|
||||
|
||||
if (response.success) {
|
||||
setIsModelInitialized(true);
|
||||
setErrorMessage(null);
|
||||
} else {
|
||||
setErrorMessage(response.error || "Unknown error during setup");
|
||||
}
|
||||
},
|
||||
|
||||
onUpdateSettingsResponse: (response) => {
|
||||
console.log("Update settings response:", response);
|
||||
setIsLoading(false);
|
||||
|
||||
if (response.success) {
|
||||
setErrorMessage(null);
|
||||
} else {
|
||||
setErrorMessage(response.error || "Unknown error updating settings");
|
||||
}
|
||||
},
|
||||
|
||||
onGenerateResponse: (response) => {
|
||||
console.log("Generate response:", response);
|
||||
setIsLoading(false);
|
||||
|
||||
if (response.success && response.image) {
|
||||
setGeneratedImageUrl(base64ToImageUrl(response.image));
|
||||
setErrorMessage(null);
|
||||
} else {
|
||||
setErrorMessage(response.error || "Unknown error generating image");
|
||||
}
|
||||
},
|
||||
|
||||
onStatusResponse: (response) => {
|
||||
console.log("Status response:", response);
|
||||
|
||||
if (response.success) {
|
||||
setIsModelInitialized(response.model_initialized);
|
||||
|
||||
if (response.current_settings) {
|
||||
// Update UI with current settings
|
||||
setModelPath(response.current_settings.sdxl_checkpoint_path || "");
|
||||
setLoraPath(response.current_settings.lora_path || "");
|
||||
|
||||
// Update generation parameters if they exist
|
||||
if (response.current_settings.default_lora_strength !== undefined) {
|
||||
setLoraStrength(response.current_settings.default_lora_strength);
|
||||
}
|
||||
|
||||
if (
|
||||
response.current_settings.default_image_to_image_strength !==
|
||||
undefined
|
||||
) {
|
||||
setImageToImageStrength(
|
||||
response.current_settings.default_image_to_image_strength,
|
||||
);
|
||||
}
|
||||
|
||||
if (response.current_settings.default_steps !== undefined) {
|
||||
setSteps(response.current_settings.default_steps);
|
||||
}
|
||||
|
||||
if (
|
||||
response.current_settings.default_guidance_scale !== undefined
|
||||
) {
|
||||
setGuidanceScale(
|
||||
response.current_settings.default_guidance_scale,
|
||||
);
|
||||
}
|
||||
|
||||
if (response.current_settings.default_width !== undefined) {
|
||||
setWidth(response.current_settings.default_width);
|
||||
}
|
||||
|
||||
if (response.current_settings.default_height !== undefined) {
|
||||
setHeight(response.current_settings.default_height);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
clientRef.current = client;
|
||||
|
||||
// Connect to the server
|
||||
client.connect().catch((error) => {
|
||||
console.error("Error connecting to server:", error);
|
||||
setErrorMessage(`Failed to connect to server: ${error.message}`);
|
||||
});
|
||||
|
||||
return () => {
|
||||
client.disconnect();
|
||||
clientRef.current = null;
|
||||
};
|
||||
}, [serverUrl]);
|
||||
|
||||
// Handle source image selection
|
||||
const handleImageChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setSourceImage(file);
|
||||
setSourceImageUrl(URL.createObjectURL(file));
|
||||
}
|
||||
};
|
||||
|
||||
// Handle setup submission
|
||||
const handleSetup = async () => {
|
||||
if (!clientRef.current) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setErrorMessage(null);
|
||||
|
||||
try {
|
||||
await clientRef.current.setup(modelPath, loraPath || undefined);
|
||||
} catch (error) {
|
||||
console.error("Error setting up model:", error);
|
||||
setErrorMessage(`Error setting up model: ${(error as Error).message}`);
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle update settings
|
||||
const handleUpdateSettings = async () => {
|
||||
if (!clientRef.current) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setErrorMessage(null);
|
||||
|
||||
try {
|
||||
await clientRef.current.updateSettings({
|
||||
lora_path: loraPath || null,
|
||||
default_lora_strength: loraStrength,
|
||||
default_image_to_image_strength: imageToImageStrength,
|
||||
default_steps: steps,
|
||||
default_guidance_scale: guidanceScale,
|
||||
default_width: width,
|
||||
default_height: height,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error updating settings:", error);
|
||||
setErrorMessage(`Error updating settings: ${(error as Error).message}`);
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle generation
|
||||
const handleGenerate = async () => {
|
||||
if (!clientRef.current || !sourceImage) {
|
||||
setErrorMessage("Please select a source image first");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setErrorMessage(null);
|
||||
setGeneratedImageUrl(null);
|
||||
|
||||
try {
|
||||
const base64Image = await fileToBase64(sourceImage);
|
||||
|
||||
await clientRef.current.generate({
|
||||
image: base64Image,
|
||||
prompt,
|
||||
lora_strength: loraStrength,
|
||||
image_to_image_strength: imageToImageStrength,
|
||||
num_inference_steps: steps,
|
||||
guidance_scale: guidanceScale,
|
||||
generated_image_width: width,
|
||||
generated_image_height: height,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error generating image:", error);
|
||||
setErrorMessage(`Error generating image: ${(error as Error).message}`);
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl p-6">
|
||||
<h1 className="mb-6 text-2xl font-bold">SDXL Image Generator</h1>
|
||||
|
||||
{/* Connection and Setup */}
|
||||
<div className="mb-6 rounded-lg bg-gray-100 p-4">
|
||||
<h2 className="mb-2 text-xl font-semibold">Server Connection</h2>
|
||||
<div className="mb-4 flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={serverUrl}
|
||||
onChange={(e) => setServerUrl(e.target.value)}
|
||||
className="flex-grow rounded border p-2"
|
||||
placeholder="WebSocket URL"
|
||||
/>
|
||||
<button
|
||||
onClick={() => clientRef.current?.connect()}
|
||||
disabled={isConnected}
|
||||
className="rounded bg-blue-500 px-4 py-2 text-white disabled:bg-gray-400"
|
||||
>
|
||||
Connect
|
||||
</button>
|
||||
<button
|
||||
onClick={() => clientRef.current?.disconnect()}
|
||||
disabled={!isConnected}
|
||||
className="rounded bg-red-500 px-4 py-2 text-white disabled:bg-gray-400"
|
||||
>
|
||||
Disconnect
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mb-2 flex items-center">
|
||||
<span className="mr-2">Status:</span>
|
||||
<span
|
||||
className={`rounded px-2 py-1 text-white ${isConnected ? "bg-green-500" : "bg-red-500"}`}
|
||||
>
|
||||
{isConnected ? "Connected" : "Disconnected"}
|
||||
</span>
|
||||
<span className="ml-4 mr-2">Model:</span>
|
||||
<span
|
||||
className={`rounded px-2 py-1 text-white ${isModelInitialized ? "bg-green-500" : "bg-yellow-500"}`}
|
||||
>
|
||||
{isModelInitialized ? "Initialized" : "Not Initialized"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Model Setup */}
|
||||
<div className="mb-6 rounded-lg bg-gray-100 p-4">
|
||||
<h2 className="mb-2 text-xl font-semibold">Model Setup</h2>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="mb-1 block">SDXL Checkpoint Path:</label>
|
||||
<input
|
||||
type="text"
|
||||
value={modelPath}
|
||||
onChange={(e) => setModelPath(e.target.value)}
|
||||
className="w-full rounded border p-2"
|
||||
placeholder="/path/to/sdxl/model"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block">LoRA Path (optional):</label>
|
||||
<input
|
||||
type="text"
|
||||
value={loraPath}
|
||||
onChange={(e) => setLoraPath(e.target.value)}
|
||||
className="w-full rounded border p-2"
|
||||
placeholder="/path/to/lora"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={handleSetup}
|
||||
disabled={!isConnected || !modelPath || isLoading}
|
||||
className="rounded bg-green-500 px-4 py-2 text-white disabled:bg-gray-400"
|
||||
>
|
||||
Initialize Model
|
||||
</button>
|
||||
<button
|
||||
onClick={handleUpdateSettings}
|
||||
disabled={!isConnected || !isModelInitialized || isLoading}
|
||||
className="rounded bg-purple-500 px-4 py-2 text-white disabled:bg-gray-400"
|
||||
>
|
||||
Update Settings
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Generation Parameters */}
|
||||
<div className="mb-6 rounded-lg bg-gray-100 p-4">
|
||||
<h2 className="mb-2 text-xl font-semibold">Generation Parameters</h2>
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<label className="mb-1 block">Prompt:</label>
|
||||
<textarea
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
className="h-20 w-full rounded border p-2"
|
||||
placeholder="Enter your prompt..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="mb-1 block">Source Image:</label>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={handleImageChange}
|
||||
className="mb-2"
|
||||
/>
|
||||
{sourceImageUrl && (
|
||||
<img
|
||||
src={sourceImageUrl}
|
||||
alt="Source"
|
||||
className="max-h-40 rounded border"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="mb-1 block">
|
||||
LoRA Strength: {loraStrength.toFixed(2)}
|
||||
</label>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="1"
|
||||
step="0.05"
|
||||
value={loraStrength}
|
||||
onChange={(e) => setLoraStrength(parseFloat(e.target.value))}
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="mb-1 block">
|
||||
Image-to-Image Strength: {imageToImageStrength.toFixed(2)}
|
||||
</label>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="1"
|
||||
step="0.05"
|
||||
value={imageToImageStrength}
|
||||
onChange={(e) =>
|
||||
setImageToImageStrength(parseFloat(e.target.value))
|
||||
}
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="mb-1 block">Steps: {steps}</label>
|
||||
<input
|
||||
type="range"
|
||||
min="1"
|
||||
max="20"
|
||||
step="1"
|
||||
value={steps}
|
||||
onChange={(e) => setSteps(parseInt(e.target.value))}
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="mb-1 block">
|
||||
Guidance Scale: {guidanceScale.toFixed(2)}
|
||||
</label>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="10"
|
||||
step="0.1"
|
||||
value={guidanceScale}
|
||||
onChange={(e) => setGuidanceScale(parseFloat(e.target.value))}
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="mb-1 block">Width:</label>
|
||||
<select
|
||||
value={width}
|
||||
onChange={(e) => setWidth(parseInt(e.target.value))}
|
||||
className="w-full rounded border p-2"
|
||||
>
|
||||
<option value="512">512</option>
|
||||
<option value="768">768</option>
|
||||
<option value="1024">1024</option>
|
||||
<option value="1280">1280</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="mb-1 block">Height:</label>
|
||||
<select
|
||||
value={height}
|
||||
onChange={(e) => setHeight(parseInt(e.target.value))}
|
||||
className="w-full rounded border p-2"
|
||||
>
|
||||
<option value="512">512</option>
|
||||
<option value="768">768</option>
|
||||
<option value="1024">1024</option>
|
||||
<option value="1280">1280</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleGenerate}
|
||||
disabled={
|
||||
!isConnected || !isModelInitialized || !sourceImage || isLoading
|
||||
}
|
||||
className="mt-4 rounded bg-blue-500 px-6 py-2 text-white disabled:bg-gray-400"
|
||||
>
|
||||
Generate Image
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Progress and Results */}
|
||||
{isLoading && progress && (
|
||||
<div className="mb-6 rounded-lg bg-gray-100 p-4">
|
||||
<h2 className="mb-2 text-xl font-semibold">Progress</h2>
|
||||
<div className="mb-2">
|
||||
<div className="mb-1 flex justify-between">
|
||||
<span>{progress.stage}</span>
|
||||
<span>{progress.progress}%</span>
|
||||
</div>
|
||||
<div className="h-2.5 w-full rounded-full bg-gray-300">
|
||||
<div
|
||||
className="h-2.5 rounded-full bg-blue-600"
|
||||
style={{ width: `${progress.progress}%` }}
|
||||
></div>
|
||||
</div>
|
||||
{progress.file && (
|
||||
<div className="mt-1 text-sm text-gray-600">{progress.file}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{errorMessage && (
|
||||
<div className="mb-6 rounded border border-red-400 bg-red-100 px-4 py-3 text-red-700">
|
||||
<p>{errorMessage}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{generatedImageUrl && (
|
||||
<div className="mb-6 rounded-lg bg-gray-100 p-4">
|
||||
<h2 className="mb-2 text-xl font-semibold">Generated Image</h2>
|
||||
<div className="flex justify-center">
|
||||
<img
|
||||
src={generatedImageUrl}
|
||||
alt="Generated"
|
||||
className="max-w-full rounded border"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -2,17 +2,12 @@ import { useState, useRef, useEffect } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { useSignals } from "@preact/signals-react/runtime";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
UploaderStates,
|
||||
// UploaderState,
|
||||
uploadImage,
|
||||
} from "~/components/UploadImage";
|
||||
import { UploaderStates, uploadImage } from "~/components/UploadImage";
|
||||
|
||||
import { PopoverMenu } from "~/components/reusable/Popover";
|
||||
import { Tooltip } from "~/components/reusable/Tooltip";
|
||||
import { Button } from "~/components/reusable/Button";
|
||||
import { Tooltip } from "@storyteller/ui-tooltip";
|
||||
import { Button } from "@storyteller/ui-button";
|
||||
import { ToggleButton } from "~/components/reusable/ToggleButton";
|
||||
import { Toaster } from "~/components/ui/Toast";
|
||||
import { Modal } from "@storyteller/ui-modal";
|
||||
import {
|
||||
faMessageXmark,
|
||||
@@ -25,7 +20,6 @@ import {
|
||||
faImages,
|
||||
} from "@fortawesome/pro-solid-svg-icons";
|
||||
import {
|
||||
faRectangleWide,
|
||||
faRectangleVertical,
|
||||
faSquare,
|
||||
faRectangle,
|
||||
@@ -34,11 +28,11 @@ import { getCanvasRenderBitmap } from "~/signal/canvasRenderBitmap";
|
||||
import { EncodeImageBitmapToBase64 } from "~/utilities/EncodeImageBitmapToBase64";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { PopoverItem } from "~/components/reusable/Popover";
|
||||
import { Api, ApiManager } from "~/KonvaApp/Api";
|
||||
|
||||
import { useJobContext } from "~/components/JobContext";
|
||||
import { IsDesktopApp } from "@storyteller/tauri-utils";
|
||||
import { GalleryItem, GalleryModal } from "@storyteller/ui-gallery-modal";
|
||||
|
||||
import { PromptsApi } from "@storyteller/api";
|
||||
interface ReferenceImage {
|
||||
id: string;
|
||||
url: string;
|
||||
@@ -221,7 +215,7 @@ export const PromptBox = () => {
|
||||
};
|
||||
|
||||
const handleTauriEnqueue = async () => {
|
||||
const api = new Api();
|
||||
const api = new PromptsApi();
|
||||
let image = getCanvasRenderBitmap();
|
||||
if (image === undefined) {
|
||||
return;
|
||||
@@ -267,7 +261,7 @@ export const PromptBox = () => {
|
||||
};
|
||||
|
||||
const handleWebEnqueue = async () => {
|
||||
const api = new Api();
|
||||
const api = new PromptsApi();
|
||||
let image = getCanvasRenderBitmap();
|
||||
if (image === undefined) {
|
||||
toast.error(
|
||||
|
||||
@@ -52,7 +52,7 @@ export const ToolbarTopLeft = () => {
|
||||
className="h-[28px] select-none"
|
||||
/>
|
||||
|
||||
<Button
|
||||
{/* <Button
|
||||
variant="secondary"
|
||||
icon={faChevronRight}
|
||||
iconClassName="text-xs"
|
||||
@@ -61,7 +61,7 @@ export const ToolbarTopLeft = () => {
|
||||
className="bg-transparent p-0 text-sm text-white/80 hover:bg-transparent hover:text-white hover:underline hover:underline-offset-2"
|
||||
>
|
||||
Go to 3D Stage Editor
|
||||
</Button>
|
||||
</Button> */}
|
||||
|
||||
{/* <TabSelector
|
||||
tabs={tabs}
|
||||
|
||||
+13
-8
@@ -1,4 +1,5 @@
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { Fragment } from "react";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import {
|
||||
faChevronDown,
|
||||
@@ -44,8 +45,12 @@ export function ProfileDropdown() {
|
||||
size={34}
|
||||
username={userInfo.value.display_name}
|
||||
email_hash={userInfo.value.email_gravatar_hash}
|
||||
avatarIndex={Number(userInfo.value.core_info.default_avatar.image_index) || 0}
|
||||
backgroundIndex={Number(userInfo.value.core_info.default_avatar.color_index) || 0}
|
||||
avatarIndex={
|
||||
Number(userInfo.value.core_info.default_avatar.image_index) || 0
|
||||
}
|
||||
backgroundIndex={
|
||||
Number(userInfo.value.core_info.default_avatar.color_index) || 0
|
||||
}
|
||||
/>
|
||||
<FontAwesomeIcon icon={faChevronDown} />
|
||||
</MenuButton>
|
||||
@@ -61,18 +66,18 @@ export function ProfileDropdown() {
|
||||
)}
|
||||
>
|
||||
<MenuItem
|
||||
as="a"
|
||||
as="button"
|
||||
href={profileUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={twMerge(
|
||||
"flex w-full items-center gap-3 rounded-lg px-3 py-2",
|
||||
"text-md font-medium text-gray-700 hover:bg-gray-100",
|
||||
"text-md font-medium text-white hover:bg-gray-100 hover:text-gray-700",
|
||||
"transition-colors duration-150",
|
||||
)}
|
||||
>
|
||||
<FontAwesomeIcon icon={faUser} className="w-4 text-gray-700" />
|
||||
<span className="text-gray-700">My Profile</span>
|
||||
<FontAwesomeIcon icon={faUser} className="w-4" />
|
||||
My Profile
|
||||
</MenuItem>
|
||||
|
||||
{menuOptions.map((option, index) => (
|
||||
@@ -81,7 +86,7 @@ export function ProfileDropdown() {
|
||||
as="button"
|
||||
className={twMerge(
|
||||
"flex w-full items-center gap-3 rounded-lg px-3 py-2",
|
||||
"text-md font-medium text-gray-700 hover:bg-gray-100",
|
||||
"text-md font-medium text-white hover:bg-gray-100 hover:text-gray-700",
|
||||
"transition-colors duration-150",
|
||||
)}
|
||||
onClick={(e) => {
|
||||
@@ -90,7 +95,7 @@ export function ProfileDropdown() {
|
||||
option.onClick();
|
||||
}}
|
||||
>
|
||||
<FontAwesomeIcon icon={option.icon} className="w-4 text-gray-700" />
|
||||
<FontAwesomeIcon icon={option.icon} className="w-4" />
|
||||
<span>{option.label}</span>
|
||||
</MenuItem>
|
||||
))}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { signals } from "./auth_signals";
|
||||
import { UsersApi } from "@storyteller/api";
|
||||
import { BillingApi } from "@ApiManager/BillingApi";
|
||||
import { BillingApi } from "@storyteller/api";
|
||||
|
||||
import {
|
||||
updateActiveSubscriptions,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { signals } from "./auth_signals";
|
||||
import * as fetchers from "./fetchers";
|
||||
import * as enums from "./enums";
|
||||
|
||||
import * as fetchers from "./fetchers";
|
||||
export const authentication = {
|
||||
signals,
|
||||
fetchers,
|
||||
|
||||
@@ -10,6 +10,11 @@ import path from 'path';
|
||||
export default defineConfig({
|
||||
server: {
|
||||
port: 5741,
|
||||
// Local development CORS for images
|
||||
headers: {
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
"Cross-Origin-Embedder-Policy": "require-corp"
|
||||
},
|
||||
},
|
||||
|
||||
//build: {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { GetBuildEnvironment } from "~/BuildEnvironment";
|
||||
import environmentVariables from "../EnvironmentVariables";
|
||||
import { Configs } from "~/configs";
|
||||
//import { fetch } from '@tauri-apps/plugin-http'
|
||||
import { FetchProxy as fetch } from "@storyteller/tauri-utils";
|
||||
|
||||
type NonNullableObject<T extends object> = NonNullable<T>;
|
||||
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
import { CloseButton, Button } from "~/components";
|
||||
import { Transition } from "@headlessui/react";
|
||||
import { createPortal } from "react-dom";
|
||||
import dayjs from "dayjs";
|
||||
import { faDownToLine } from "@fortawesome/pro-solid-svg-icons";
|
||||
|
||||
interface LightboxModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
imageUrl?: string | null;
|
||||
imageAlt?: string;
|
||||
onImageError?: () => void;
|
||||
title?: string;
|
||||
createdAt?: string;
|
||||
additionalInfo?: React.ReactNode;
|
||||
downloadUrl?: string;
|
||||
}
|
||||
|
||||
export function LightboxModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
imageUrl,
|
||||
imageAlt = "",
|
||||
onImageError,
|
||||
title,
|
||||
createdAt,
|
||||
additionalInfo,
|
||||
downloadUrl,
|
||||
}: LightboxModalProps) {
|
||||
return createPortal(
|
||||
<Transition appear show={isOpen}>
|
||||
<div className="fixed inset-0 z-[100]">
|
||||
<Transition.Child
|
||||
enter="ease-out duration-300"
|
||||
enterFrom="opacity-0"
|
||||
enterTo="opacity-100"
|
||||
leave="ease-in duration-200"
|
||||
leaveFrom="opacity-100"
|
||||
leaveTo="opacity-0"
|
||||
>
|
||||
<div
|
||||
className="fixed inset-0 cursor-pointer bg-black/60"
|
||||
onClick={onClose}
|
||||
/>
|
||||
</Transition.Child>
|
||||
<div
|
||||
className="fixed inset-0 flex items-center justify-center p-4"
|
||||
onClick={onClose}
|
||||
>
|
||||
<Transition.Child
|
||||
enter="ease-out duration-300"
|
||||
enterFrom="opacity-0 scale-95"
|
||||
enterTo="opacity-100 scale-100"
|
||||
leave="ease-in duration-200"
|
||||
leaveFrom="opacity-100 scale-100"
|
||||
leaveTo="opacity-0 scale-95"
|
||||
>
|
||||
<div
|
||||
className="relative h-[90vh] w-[80vw] rounded-xl bg-[#2C2C2C]"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<CloseButton
|
||||
onClick={onClose}
|
||||
className="absolute right-4 top-4 z-10"
|
||||
/>
|
||||
<div className="grid h-full grid-cols-3 gap-6">
|
||||
<div className="col-span-2 flex h-full items-center justify-center overflow-hidden rounded-l-xl bg-black/40">
|
||||
{!imageUrl ? (
|
||||
<div className="flex h-full w-full items-center justify-center bg-gray-800">
|
||||
<span className="text-white/60">Image not available</span>
|
||||
</div>
|
||||
) : (
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt={imageAlt}
|
||||
className="h-full w-full object-contain"
|
||||
onError={onImageError}
|
||||
crossOrigin="anonymous"
|
||||
referrerPolicy="no-referrer"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex h-full flex-col py-5 pe-5">
|
||||
<div className="flex-1 space-y-4">
|
||||
<div className="text-xl font-medium">
|
||||
{title || "Image Generation"}
|
||||
</div>
|
||||
{createdAt && (
|
||||
<div className="text-sm text-white/60">
|
||||
Created:{" "}
|
||||
{dayjs(createdAt).format("MMM D, YYYY HH:mm:ss")}
|
||||
</div>
|
||||
)}
|
||||
{additionalInfo}
|
||||
</div>
|
||||
{downloadUrl && (
|
||||
<div className="flex justify-end">
|
||||
<a
|
||||
href={downloadUrl}
|
||||
download
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="no-underline"
|
||||
>
|
||||
<Button
|
||||
icon={faDownToLine}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
Download
|
||||
</Button>
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Transition.Child>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -58,7 +58,7 @@ export const TopBar = ({ pageName }: Props) => {
|
||||
Back to Editor
|
||||
</ButtonLink>
|
||||
)}
|
||||
<Button
|
||||
{/* <Button
|
||||
variant="secondary"
|
||||
icon={faChevronRight}
|
||||
iconClassName="text-xs"
|
||||
@@ -67,7 +67,7 @@ export const TopBar = ({ pageName }: Props) => {
|
||||
className="bg-transparent p-0 text-sm text-white/80 hover:bg-transparent hover:text-white hover:underline hover:underline-offset-2"
|
||||
>
|
||||
Go to 2D Canvas
|
||||
</Button>
|
||||
</Button> */}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-center gap-2 font-medium">
|
||||
|
||||
@@ -1,52 +1,20 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { StrictMode, useEffect } from "react";
|
||||
import { useSignals, useSignalEffect } from "@preact/signals-react/runtime";
|
||||
import { useEffect } from "react";
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import * as ReactDOM from 'react-dom/client';
|
||||
import { authentication, persistLogin } from "~/signals";
|
||||
import { PageEnigma } from './pages/PageEnigma/PageEnigma';
|
||||
import { BrowserRouter } from "react-router-dom";
|
||||
import { PageEnigma } from "./pages/PageEnigma/PageEnigma";
|
||||
import { createRoot } from "react-dom/client";
|
||||
//import App from './app/app';
|
||||
//import { App } from './root';
|
||||
|
||||
import {
|
||||
Links,
|
||||
Meta,
|
||||
Outlet,
|
||||
Scripts,
|
||||
ScrollRestoration,
|
||||
useLoaderData,
|
||||
} from "@remix-run/react";
|
||||
|
||||
import "./styles/normalize.css";
|
||||
import "./styles/tailwind.css";
|
||||
import "./styles/base.css";
|
||||
import "@fortawesome/fontawesome-svg-core/styles.css";
|
||||
|
||||
import { config } from "@fortawesome/fontawesome-svg-core";
|
||||
|
||||
import EnvironmentVariables from "~/Classes/EnvironmentVariables";
|
||||
import { pageHeight, pageWidth } from "~/signals";
|
||||
|
||||
import { pageHeight, pageWidth, persistLogin } from "~/signals";
|
||||
import { showWizard } from "~/pages/PageEnigma/Wizard/signals/wizard";
|
||||
import { BuildEnvironmentType, GetBuildEnvironment } from "./BuildEnvironment";
|
||||
import { posthog } from "posthog-js";
|
||||
|
||||
config.autoAddCss = false; /* eslint-disable import/first */
|
||||
|
||||
//const root = ReactDOM.createRoot(
|
||||
// document.getElementById('root') as HTMLElement
|
||||
//);
|
||||
//
|
||||
//root.render(
|
||||
// <StrictMode>
|
||||
// <BrowserRouter>
|
||||
// <App/>
|
||||
// </BrowserRouter>
|
||||
// </StrictMode>
|
||||
//);
|
||||
|
||||
//createRoot(document.getElementById("root")!).render(<PageEnigma/>);
|
||||
|
||||
// TODO(bt,2025-04-19): Make these configurable
|
||||
const ENV = {
|
||||
BASE_API: "https://api.storyteller.ai",
|
||||
@@ -65,17 +33,18 @@ const GlobalSettingsManager = ({ env }: { env: Record<string, string> }) => {
|
||||
|
||||
/// Initizations that depends on ENV vars ///
|
||||
function PostHogInit() {
|
||||
const data = EnvironmentVariables.values;
|
||||
const apiKey = data.REACT_APP_PUBLIC_POSTHOG_KEY as string;
|
||||
//posthog.init(apiKey, {
|
||||
// //HACK: This is the default host from Netlify, but need to figure out why it isn't working on prod.
|
||||
// // api_host: data.DEPLOY_PRIME_URL + "/ingest" as string,
|
||||
// api_host: "https://studio.storyteller.ai/ingest" as string,
|
||||
// ui_host: data.REACT_APP_PUBLIC_POSTHOG_UI as string,
|
||||
//});
|
||||
const apiKey = import.meta.env.VITE_POSTHOG_API_KEY;
|
||||
posthog.init(apiKey, {
|
||||
api_host: "https://us.i.posthog.com/",
|
||||
ui_host: "https://us.i.posthog.com/",
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
EnvironmentVariables.initialize(env);
|
||||
if (import.meta.env.DEV) {
|
||||
return;
|
||||
}
|
||||
PostHogInit();
|
||||
}, [env]);
|
||||
|
||||
@@ -114,8 +83,8 @@ createRoot(document.getElementById("root")!).render(
|
||||
<BrowserRouter>
|
||||
<GlobalSettingsManager env={ENV} />
|
||||
<div className="topbar-spacer" />
|
||||
<PageEnigma/>
|
||||
<PageEnigma />
|
||||
</BrowserRouter>
|
||||
</StrictMode>
|
||||
</>
|
||||
</>,
|
||||
);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user