Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

style(rust): apply cargo fmt across the workspace

tonhowtf18d2f0c6b13f
diff --git a/src-tauri/omniget-core/src/core/ai.rs b/src-tauri/omniget-core/src/core/ai.rs
index 3e06825d..fa85ead6 100644
--- a/src-tauri/omniget-core/src/core/ai.rs
+++ b/src-tauri/omniget-core/src/core/ai.rs
@@ -209,9 +209,19 @@ async fn openai_chat(
serde_json::from_str(&text).map_err(|e| format!("Bad JSON: {}", e))?;
// Ledger de custo (Tools → Custos de IA): tokens que o provedor informou.
let usage = json.get("usage");
- let input = usage.and_then(|u| u.get("prompt_tokens")).and_then(|v| v.as_u64()).unwrap_or(0);
- let output = usage.and_then(|u| u.get("completion_tokens")).and_then(|v| v.as_u64()).unwrap_or(0);
- let provider = if endpoint.starts_with("https://api.openai.com") { "openai" } else { "local" };
+ let input = usage
+ .and_then(|u| u.get("prompt_tokens"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(0);
+ let output = usage
+ .and_then(|u| u.get("completion_tokens"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(0);
+ let provider = if endpoint.starts_with("https://api.openai.com") {
+ "openai"
+ } else {
+ "local"
+ };
let cost = if provider == "local" { Some(0.0) } else { None };
crate::core::tools::usage::record("chat", provider, model, input, output, cost);
json.get("choices")
@@ -258,8 +268,14 @@ async fn anthropic_chat(
let json: serde_json::Value =
serde_json::from_str(&text).map_err(|e| format!("Bad JSON: {}", e))?;
let usage = json.get("usage");
- let input = usage.and_then(|u| u.get("input_tokens")).and_then(|v| v.as_u64()).unwrap_or(0);
- let output = usage.and_then(|u| u.get("output_tokens")).and_then(|v| v.as_u64()).unwrap_or(0);
+ let input = usage
+ .and_then(|u| u.get("input_tokens"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(0);
+ let output = usage
+ .and_then(|u| u.get("output_tokens"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(0);
crate::core::tools::usage::record("chat", "anthropic", model, input, output, None);
json.get("content")
.and_then(|c| c.get(0))
diff --git a/src-tauri/omniget-core/src/core/errors.rs b/src-tauri/omniget-core/src/core/errors.rs
index 579a7be4..0ed1caf6 100644
--- a/src-tauri/omniget-core/src/core/errors.rs
+++ b/src-tauri/omniget-core/src/core/errors.rs
@@ -120,7 +120,11 @@ mod tests {
#[test]
fn network_and_rate_limit_still_retry() {
- assert!(!is_terminal_category(classify_download_error("HTTP Error 429").0));
- assert!(!is_terminal_category(classify_download_error("connection reset").0));
+ assert!(!is_terminal_category(
+ classify_download_error("HTTP Error 429").0
+ ));
+ assert!(!is_terminal_category(
+ classify_download_error("connection reset").0
+ ));
}
}
diff --git a/src-tauri/omniget-core/src/core/hls_downloader.rs b/src-tauri/omniget-core/src/core/hls_downloader.rs
index a6bd73b1..0946695b 100644
--- a/src-tauri/omniget-core/src/core/hls_downloader.rs
+++ b/src-tauri/omniget-core/src/core/hls_downloader.rs
@@ -503,7 +503,12 @@ fn select_best_variant(master: &MasterPlaylist, max_height: Option<u32>) -> Opti
sorted
.iter()
.rev()
- .find(|v| v.resolution.as_ref().map(|r| r.height <= max_h).unwrap_or(true))
+ .find(|v| {
+ v.resolution
+ .as_ref()
+ .map(|r| r.height <= max_h)
+ .unwrap_or(true)
+ })
.copied()
.or_else(|| sorted.first().copied())
}
diff --git a/src-tauri/omniget-core/src/core/http_fetcher.rs b/src-tauri/omniget-core/src/core/http_fetcher.rs
index 4299f9a8..d02f9054 100644
--- a/src-tauri/omniget-core/src/core/http_fetcher.rs
+++ b/src-tauri/omniget-core/src/core/http_fetcher.rs
@@ -681,7 +681,10 @@ pub async fn probe_remote(
None
}
Err(_) => {
- return Err(anyhow!("unreachable: connect timed out after {:?}", timeout));
+ return Err(anyhow!(
+ "unreachable: connect timed out after {:?}",
+ timeout
+ ));
}
};
@@ -1004,7 +1007,11 @@ async fn download_segment(
let cur_end = seg.end_ceiling.load(Ordering::Relaxed);
let target = (cur_end + 1).saturating_sub(range_start);
if written >= target {
- stop_reason = if cur_end < end { "ceiling shrank" } else { "done" };
+ stop_reason = if cur_end < end {
+ "ceiling shrank"
+ } else {
+ "done"
+ };
break;
}
let res = tokio::time::timeout(cfg.read_timeout, stream.next()).await;
@@ -1148,7 +1155,10 @@ mod tests {
#[test]
fn content_length_comes_from_the_header_not_the_body() {
let mut h = reqwest::header::HeaderMap::new();
- h.insert(reqwest::header::CONTENT_LENGTH, "104857600".parse().unwrap());
+ h.insert(
+ reqwest::header::CONTENT_LENGTH,
+ "104857600".parse().unwrap(),
+ );
assert_eq!(header_content_length(&h), Some(104857600));
h.insert(reqwest::header::CONTENT_LENGTH, "0".parse().unwrap());
assert_eq!(header_content_length(&h), None);
@@ -1159,9 +1169,15 @@ mod tests {
#[test]
fn content_range_total_parses_the_denominator() {
let mut h = reqwest::header::HeaderMap::new();
- h.insert(reqwest::header::CONTENT_RANGE, "bytes 0-0/1234".parse().unwrap());
+ h.insert(
+ reqwest::header::CONTENT_RANGE,
+ "bytes 0-0/1234".parse().unwrap(),
+ );
assert_eq!(content_range_total(&h), Some(1234));
- h.insert(reqwest::header::CONTENT_RANGE, "bytes 0-0/*".parse().unwrap());
+ h.insert(
+ reqwest::header::CONTENT_RANGE,
+ "bytes 0-0/*".parse().unwrap(),
+ );
assert_eq!(content_range_total(&h), None);
}
@@ -1180,7 +1196,10 @@ mod tests {
.unwrap(),
);
assert_eq!(header_filename(&h).as_deref(), Some("vídeo.mp4"));
- h.insert(reqwest::header::CONTENT_DISPOSITION, "inline".parse().unwrap());
+ h.insert(
+ reqwest::header::CONTENT_DISPOSITION,
+ "inline".parse().unwrap(),
+ );
assert_eq!(header_filename(&h), None);
}
diff --git a/src-tauri/omniget-core/src/core/mod.rs b/src-tauri/omniget-core/src/core/mod.rs
index cbfa4eed..b41f67e4 100644
--- a/src-tauri/omniget-core/src/core/mod.rs
+++ b/src-tauri/omniget-core/src/core/mod.rs
@@ -25,9 +25,9 @@ pub mod pokemon_names;
pub mod pot_provider;
pub mod process;
pub mod redirect;
-pub mod spicetify;
pub mod registry;
pub mod shell_words;
+pub mod spicetify;
pub mod subtitle_merge;
pub mod tools;
pub mod ytdlp;
diff --git a/src-tauri/omniget-core/src/core/shell_words.rs b/src-tauri/omniget-core/src/core/shell_words.rs
index dc6f5991..a6dee19e 100644
--- a/src-tauri/omniget-core/src/core/shell_words.rs
+++ b/src-tauri/omniget-core/src/core/shell_words.rs
@@ -97,8 +97,26 @@ fn needs_quoting(arg: &str) -> bool {
c.is_whitespace()
|| matches!(
c,
- '\'' | '"' | '\\' | '$' | '`' | '!' | '*' | '?' | '[' | ']' | '(' | ')' | '{'
- | '}' | '<' | '>' | '|' | '&' | ';' | '#' | '~'
+ '\'' | '"'
+ | '\\'
+ | '$'
+ | '`'
+ | '!'
+ | '*'
+ | '?'
+ | '['
+ | ']'
+ | '('
+ | ')'
+ | '{'
+ | '}'
+ | '<'
+ | '>'
+ | '|'
+ | '&'
+ | ';'
+ | '#'
+ | '~'
)
})
}
@@ -254,7 +272,14 @@ mod tests {
let v = split(r#"yt-dlp -f 'bv*+ba' --add-headers "Referer: https://x/" url"#).unwrap();
assert_eq!(
v,
- vec!["yt-dlp", "-f", "bv*+ba", "--add-headers", "Referer: https://x/", "url"]
+ vec![
+ "yt-dlp",
+ "-f",
+ "bv*+ba",
+ "--add-headers",
+ "Referer: https://x/",
+ "url"
+ ]
);
}
diff --git a/src-tauri/omniget-core/src/core/spicetify.rs b/src-tauri/omniget-core/src/core/spicetify.rs
index f041c24a..70c9105a 100644
--- a/src-tauri/omniget-core/src/core/spicetify.rs
+++ b/src-tauri/omniget-core/src/core/spicetify.rs
@@ -413,7 +413,10 @@ async fn latest_asset(
))
}
-async fn download_verified(client: &reqwest::Client, asset: &ReleaseAsset) -> anyhow::Result<Vec<u8>> {
+async fn download_verified(
+ client: &reqwest::Client,
+ asset: &ReleaseAsset,
+) -> anyhow::Result<Vec<u8>> {
let response = client.get(&asset.url).send().await?;
if !response.status().is_success() {
return Err(anyhow!(
@@ -425,10 +428,12 @@ async fn download_verified(client: &reqwest::Client, asset: &ReleaseAsset) -> an
let bytes = response.bytes().await?.to_vec();
// O GitHub publica o digest de todo asset; sem ele algo está errado na
// resposta, e o binário vai ser executado. Fail-closed.
- let expected = asset
- .digest
- .as_deref()
- .ok_or_else(|| anyhow!("{} veio sem digest da API do GitHub; download descartado", asset.name))?;
+ let expected = asset.digest.as_deref().ok_or_else(|| {
+ anyhow!(
+ "{} veio sem digest da API do GitHub; download descartado",
+ asset.name
+ )
+ })?;
integrity::verify_sha256(&bytes, expected, &asset.name)?;
Ok(bytes)
}
@@ -532,7 +537,9 @@ pub async fn install() -> anyhow::Result<PathBuf> {
let exe = staging.join(bin_name("spicetify"));
if !exe.exists() {
let _ = std::fs::remove_dir_all(&staging);
- return Err(anyhow!("o arquivo baixado nao contem o executavel do spicetify"));
+ return Err(anyhow!(
+ "o arquivo baixado nao contem o executavel do spicetify"
+ ));
}
make_executable(&exe);
@@ -545,7 +552,10 @@ pub async fn install() -> anyhow::Result<PathBuf> {
if old.exists() {
let _ = std::fs::rename(&old, &dir);
}
- return Err(anyhow!("nao foi possivel mover a instalacao para o lugar: {}", e));
+ return Err(anyhow!(
+ "nao foi possivel mover a instalacao para o lugar: {}",
+ e
+ ));
}
let _ = std::fs::remove_dir_all(&old);
@@ -598,14 +608,22 @@ pub async fn install_marketplace(bin: &Path, config_dir: &Path) -> anyhow::Resul
std::fs::write(theme_dir.join("color.ini"), color_ini.bytes().await?)?;
}
- run_ok(bin, &["config", "custom_apps", "spicetify-marketplace-"]).await.ok();
+ run_ok(bin, &["config", "custom_apps", "spicetify-marketplace-"])
+ .await
+ .ok();
run_ok(bin, &["config", "custom_apps", "marketplace"]).await?;
run_ok(bin, &["config", "inject_css", "1", "replace_colors", "1"]).await?;
let cfg = read_config(&config_dir.join("config-xpui.ini"));
if cfg.current_theme.trim().len() <= 3 {
run_ok(
bin,
- &["config", "current_theme", "marketplace", "color_scheme", "marketplace"],
+ &[
+ "config",
+ "current_theme",
+ "marketplace",
+ "color_scheme",
+ "marketplace",
+ ],
)
.await?;
}
diff --git a/src-tauri/omniget-core/src/core/tools/ai_keys.rs b/src-tauri/omniget-core/src/core/tools/ai_keys.rs
index 07e07422..ba8acac4 100644
--- a/src-tauri/omniget-core/src/core/tools/ai_keys.rs
+++ b/src-tauri/omniget-core/src/core/tools/ai_keys.rs
@@ -109,22 +109,97 @@ pub struct Kind {
}
pub const KINDS: &[Kind] = &[
- Kind { id: "openai", name: "OpenAI", base_url: "https://api.openai.com/v1", balance: false, env: "OPENAI_API_KEY" },
- Kind { id: "anthropic", name: "Anthropic", base_url: "https://api.anthropic.com/v1", balance: false, env: "ANTHROPIC_API_KEY" },
- Kind { id: "openrouter", name: "OpenRouter", base_url: "https://openrouter.ai/api/v1", balance: true, env: "OPENROUTER_API_KEY" },
- Kind { id: "deepseek", name: "DeepSeek", base_url: "https://api.deepseek.com", balance: true, env: "DEEPSEEK_API_KEY" },
- Kind { id: "gemini", name: "Google Gemini", base_url: "https://generativelanguage.googleapis.com/v1beta", balance: false, env: "GEMINI_API_KEY" },
- Kind { id: "groq", name: "Groq", base_url: "https://api.groq.com/openai/v1", balance: false, env: "GROQ_API_KEY" },
- Kind { id: "xai", name: "xAI (Grok)", base_url: "https://api.x.ai/v1", balance: false, env: "XAI_API_KEY" },
- Kind { id: "mistral", name: "Mistral", base_url: "https://api.mistral.ai/v1", balance: false, env: "MISTRAL_API_KEY" },
- Kind { id: "siliconflow", name: "SiliconFlow", base_url: "https://api.siliconflow.cn/v1", balance: true, env: "SILICONFLOW_API_KEY" },
- Kind { id: "newapi", name: "New API / One API (relay)", base_url: "https://seu-site.com/v1", balance: true, env: "OPENAI_API_KEY" },
- Kind { id: "ollama", name: "Ollama (local)", base_url: "http://localhost:11434/v1", balance: false, env: "" },
- Kind { id: "custom", name: "OpenAI-compatível", base_url: "https://…/v1", balance: false, env: "OPENAI_API_KEY" },
+ Kind {
+ id: "openai",
+ name: "OpenAI",
+ base_url: "https://api.openai.com/v1",
+ balance: false,
+ env: "OPENAI_API_KEY",
+ },
+ Kind {
+ id: "anthropic",
+ name: "Anthropic",
+ base_url: "https://api.anthropic.com/v1",
+ balance: false,
+ env: "ANTHROPIC_API_KEY",
+ },
+ Kind {
+ id: "openrouter",
+ name: "OpenRouter",
+ base_url: "https://openrouter.ai/api/v1",
+ balance: true,
+ env: "OPENROUTER_API_KEY",
+ },
+ Kind {
+ id: "deepseek",
+ name: "DeepSeek",
+ base_url: "https://api.deepseek.com",
+ balance: true,
+ env: "DEEPSEEK_API_KEY",
+ },
+ Kind {
+ id: "gemini",
+ name: "Google Gemini",
+ base_url: "https://generativelanguage.googleapis.com/v1beta",
+ balance: false,
+ env: "GEMINI_API_KEY",
+ },
+ Kind {
+ id: "groq",
+ name: "Groq",
+ base_url: "https://api.groq.com/openai/v1",
+ balance: false,
+ env: "GROQ_API_KEY",
+ },
+ Kind {
+ id: "xai",
+ name: "xAI (Grok)",
+ base_url: "https://api.x.ai/v1",
+ balance: false,
+ env: "XAI_API_KEY",
+ },
+ Kind {
+ id: "mistral",
+ name: "Mistral",
+ base_url: "https://api.mistral.ai/v1",
+ balance: false,
+ env: "MISTRAL_API_KEY",
+ },
+ Kind {
+ id: "siliconflow",
+ name: "SiliconFlow",
+ base_url: "https://api.siliconflow.cn/v1",
+ balance: true,
+ env: "SILICONFLOW_API_KEY",
+ },
+ Kind {
+ id: "newapi",
+ name: "New API / One API (relay)",
+ base_url: "https://seu-site.com/v1",
+ balance: true,
+ env: "OPENAI_API_KEY",
+ },
+ Kind {
+ id: "ollama",
+ name: "Ollama (local)",
+ base_url: "http://localhost:11434/v1",
+ balance: false,
+ env: "",
+ },
+ Kind {
+ id: "custom",
+ name: "OpenAI-compatível",
+ base_url: "https://…/v1",
+ balance: false,
+ env: "OPENAI_API_KEY",
+ },
];
fn kind_of(id: &str) -> &'static Kind {
- KINDS.iter().find(|k| k.id == id).unwrap_or(&KINDS[KINDS.len() - 1])
+ KINDS
+ .iter()
+ .find(|k| k.id == id)
+ .unwrap_or(&KINDS[KINDS.len() - 1])
}
// ── Armazenamento ──────────────────────────────────────────────────────
@@ -136,7 +211,10 @@ fn file() -> Option<std::path::PathBuf> {
}
fn load() -> Vec<KeyEntry> {
- file().and_then(|p| std::fs::read_to_string(p).ok()).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
+ file()
+ .and_then(|p| std::fs::read_to_string(p).ok())
+ .and_then(|s| serde_json::from_str(&s).ok())
+ .unwrap_or_default()
}
fn save(list: &[KeyEntry]) -> anyhow::Result<()> {
@@ -159,13 +237,19 @@ pub fn entry_with_secret(id: &str) -> anyhow::Result<KeyEntry> {
}
fn get(id: &str) -> anyhow::Result<KeyEntry> {
- load().into_iter().find(|e| e.id == id).ok_or_else(|| anyhow!("chave nao encontrada"))
+ load()
+ .into_iter()
+ .find(|e| e.id == id)
+ .ok_or_else(|| anyhow!("chave nao encontrada"))
}
fn update<F: FnOnce(&mut KeyEntry)>(id: &str, f: F) -> anyhow::Result<KeyView> {
let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
let mut list = load();
- let e = list.iter_mut().find(|e| e.id == id).ok_or_else(|| anyhow!("chave nao encontrada"))?;
+ let e = list
+ .iter_mut()
+ .find(|e| e.id == id)
+ .ok_or_else(|| anyhow!("chave nao encontrada"))?;
f(e);
let v = e.view();
save(&list)?;
@@ -184,7 +268,10 @@ pub fn upsert(mut entry: KeyEntry) -> anyhow::Result<KeyView> {
if entry.name.is_empty() {
entry.name = kind_of(&entry.kind).name.to_string();
}
- if let Some(existing) = list.iter_mut().find(|e| e.id == entry.id && !entry.id.is_empty()) {
+ if let Some(existing) = list
+ .iter_mut()
+ .find(|e| e.id == entry.id && !entry.id.is_empty())
+ {
if entry.key.trim().is_empty() {
entry.key = existing.key.clone();
}
@@ -216,12 +303,18 @@ pub fn delete(id: &str) -> anyhow::Result<()> {
// ── Rede ───────────────────────────────────────────────────────────────
fn client() -> anyhow::Result<reqwest::Client> {
- Ok(crate::core::http_client::apply_global_proxy(reqwest::Client::builder()).timeout(std::time::Duration::from_secs(30)).build()?)
+ Ok(
+ crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .timeout(std::time::Duration::from_secs(30))
+ .build()?,
+ )
}
/// Site do painel (New API): base sem o `/v1`.
fn site_of(base: &str) -> String {
- base.trim_end_matches('/').trim_end_matches("/v1").to_string()
+ base.trim_end_matches('/')
+ .trim_end_matches("/v1")
+ .to_string()
}
/// GET /models (ou equivalente) → ids dos modelos.
@@ -239,7 +332,18 @@ pub async fn models(entry: &KeyEntry) -> anyhow::Result<Vec<String>> {
.json()
.await?
}
- "gemini" => c.get(format!("{}/models?pageSize=1000&key={}", entry.base_url, entry.key)).send().await?.error_for_status().map_err(|e| anyhow!("Gemini: {}", e))?.json().await?,
+ "gemini" => {
+ c.get(format!(
+ "{}/models?pageSize=1000&key={}",
+ entry.base_url, entry.key
+ ))
+ .send()
+ .await?
+ .error_for_status()
+ .map_err(|e| anyhow!("Gemini: {}", e))?
+ .json()
+ .await?
+ }
_ => {
let mut req = c.get(format!("{}/models", entry.base_url));
if !entry.key.is_empty() {
@@ -249,15 +353,34 @@ pub async fn models(entry: &KeyEntry) -> anyhow::Result<Vec<String>> {
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
if !status.is_success() {
- return Err(anyhow!("HTTP {}: {}", status.as_u16(), text.chars().take(200).collect::<String>()));
+ return Err(anyhow!(
+ "HTTP {}: {}",
+ status.as_u16(),
+ text.chars().take(200).collect::<String>()
+ ));
}
- serde_json::from_str(&text).map_err(|_| anyhow!("resposta nao e JSON: {}", text.chars().take(120).collect::<String>()))?
+ serde_json::from_str(&text).map_err(|_| {
+ anyhow!(
+ "resposta nao e JSON: {}",
+ text.chars().take(120).collect::<String>()
+ )
+ })?
}
};
- let arr = json.get("data").or_else(|| json.get("models")).and_then(|v| v.as_array()).cloned().unwrap_or_default();
+ let arr = json
+ .get("data")
+ .or_else(|| json.get("models"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
let mut ids: Vec<String> = arr
.iter()
- .filter_map(|m| m.get("id").or_else(|| m.get("name")).and_then(|v| v.as_str()).map(|s| s.trim_start_matches("models/").to_string()))
+ .filter_map(|m| {
+ m.get("id")
+ .or_else(|| m.get("name"))
+ .and_then(|v| v.as_str())
+ .map(|s| s.trim_start_matches("models/").to_string())
+ })
.collect();
ids.sort();
Ok(ids)
@@ -298,24 +421,62 @@ pub async fn balance(id: &str) -> anyhow::Result<KeyView> {
let c = client()?;
let text: String = match entry.kind.as_str() {
"openrouter" => {
- let j: serde_json::Value = c.get(format!("{}/credits", entry.base_url)).bearer_auth(&entry.key).send().await?.error_for_status()?.json().await?;
+ let j: serde_json::Value = c
+ .get(format!("{}/credits", entry.base_url))
+ .bearer_auth(&entry.key)
+ .send()
+ .await?
+ .error_for_status()?
+ .json()
+ .await?;
let d = &j["data"];
let total = d["total_credits"].as_f64().unwrap_or(0.0);
let used = d["total_usage"].as_f64().unwrap_or(0.0);
- format!("{} ({} usados de {})", usd(total - used), usd(used), usd(total))
+ format!(
+ "{} ({} usados de {})",
+ usd(total - used),
+ usd(used),
+ usd(total)
+ )
}
"deepseek" => {
- let j: serde_json::Value = c.get(format!("{}/user/balance", site_of(&entry.base_url))).bearer_auth(&entry.key).send().await?.error_for_status()?.json().await?;
+ let j: serde_json::Value = c
+ .get(format!("{}/user/balance", site_of(&entry.base_url)))
+ .bearer_auth(&entry.key)
+ .send()
+ .await?
+ .error_for_status()?
+ .json()
+ .await?;
let info = &j["balance_infos"][0];
- format!("{} {}", info["total_balance"].as_str().unwrap_or("?"), info["currency"].as_str().unwrap_or(""))
+ format!(
+ "{} {}",
+ info["total_balance"].as_str().unwrap_or("?"),
+ info["currency"].as_str().unwrap_or("")
+ )
}
"siliconflow" => {
- let j: serde_json::Value = c.get(format!("{}/user/info", entry.base_url)).bearer_auth(&entry.key).send().await?.error_for_status()?.json().await?;
- format!("{} CNY", j["data"]["balance"].as_str().or_else(|| j["data"]["totalBalance"].as_str()).unwrap_or("?"))
+ let j: serde_json::Value = c
+ .get(format!("{}/user/info", entry.base_url))
+ .bearer_auth(&entry.key)
+ .send()
+ .await?
+ .error_for_status()?
+ .json()
+ .await?;
+ format!(
+ "{} CNY",
+ j["data"]["balance"]
+ .as_str()
+ .or_else(|| j["data"]["totalBalance"].as_str())
+ .unwrap_or("?")
+ )
}
"newapi" => {
if entry.access_token.is_empty() {
- return Err(anyhow!("informe o token de acesso e o ID de usuario do painel"));
+ return Err(anyhow!(
+ "informe o token de acesso e o ID de usuario do painel"
+ ));
}
let j: serde_json::Value = c
.get(format!("{}/api/user/self", site_of(&entry.base_url)))
@@ -327,7 +488,10 @@ pub async fn balance(id: &str) -> anyhow::Result<KeyView> {
.json()
.await?;
if j["success"].as_bool() == Some(false) {
- return Err(anyhow!("{}", j["message"].as_str().unwrap_or("painel recusou")));
+ return Err(anyhow!(
+ "{}",
+ j["message"].as_str().unwrap_or("painel recusou")
+ ));
}
let d = &j["data"];
let quota = d["quota"].as_f64().unwrap_or(0.0) / 500_000.0;
@@ -347,11 +511,24 @@ fn is_openai_compatible(kind: &str) -> bool {
pub fn export(format: &str, ids: &[String]) -> anyhow::Result<String> {
let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let list: Vec<KeyEntry> = load().into_iter().filter(|e| ids.is_empty() || ids.contains(&e.id)).collect();
+ let list: Vec<KeyEntry> = load()
+ .into_iter()
+ .filter(|e| ids.is_empty() || ids.contains(&e.id))
+ .collect();
if list.is_empty() {
return Err(anyhow!("nenhuma chave selecionada"));
}
- let slug = |s: &str| s.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '_' }).collect::<String>();
+ let slug = |s: &str| {
+ s.chars()
+ .map(|c| {
+ if c.is_ascii_alphanumeric() {
+ c.to_ascii_lowercase()
+ } else {
+ '_'
+ }
+ })
+ .collect::<String>()
+ };
Ok(match format {
"env" => {
let mut out = String::new();
diff --git a/src-tauri/omniget-core/src/core/tools/aria2.rs b/src-tauri/omniget-core/src/core/tools/aria2.rs
index 5189a94b..fc07029e 100644
--- a/src-tauri/omniget-core/src/core/tools/aria2.rs
+++ b/src-tauri/omniget-core/src/core/tools/aria2.rs
@@ -42,7 +42,11 @@ pub async fn status() -> Aria2Status {
Some(p) => crate::core::dependencies::check_version_at_path(p, "aria2c").await,
None => None,
};
- Aria2Status { installed: p.is_some(), path: p.map(|p| p.to_string_lossy().to_string()), version }
+ Aria2Status {
+ installed: p.is_some(),
+ path: p.map(|p| p.to_string_lossy().to_string()),
+ version,
+ }
}
/// `[#a1b2c3 12MiB/100MiB(12%) CN:16 DL:5.0MiB ETA:10s]`
@@ -52,15 +56,35 @@ pub fn parse_progress(line: &str) -> Option<(u64, String)> {
Some((c[1].parse().ok()?, c[2].to_string()))
}
-pub async fn download(opts: Aria2Options, progress: super::ProgressFn) -> anyhow::Result<Aria2Result> {
+pub async fn download(
+ opts: Aria2Options,
+ progress: super::ProgressFn,
+) -> anyhow::Result<Aria2Result> {
use tokio::io::{AsyncBufReadExt, BufReader};
- let bin = crate::core::dependencies::ensure_aria2c().await.ok_or_else(|| anyhow!("aria2c nao esta instalado (Linux/macOS: instale pelo gerenciador de pacotes)"))?;
+ let bin = crate::core::dependencies::ensure_aria2c()
+ .await
+ .ok_or_else(|| {
+ anyhow!("aria2c nao esta instalado (Linux/macOS: instale pelo gerenciador de pacotes)")
+ })?;
std::fs::create_dir_all(&opts.dest_dir)?;
let conns = opts.connections.clamp(1, 16).to_string();
let mut cmd = crate::core::process::command(&bin);
cmd.args([
- "--dir", &opts.dest_dir, "-x", &conns, "-s", &conns, "-k", "1M", "--continue=true", "--auto-file-renaming=false",
- "--allow-overwrite=true", "--summary-interval=1", "--console-log-level=warn", "--download-result=hide", "--file-allocation=none",
+ "--dir",
+ &opts.dest_dir,
+ "-x",
+ &conns,
+ "-s",
+ &conns,
+ "-k",
+ "1M",
+ "--continue=true",
+ "--auto-file-renaming=false",
+ "--allow-overwrite=true",
+ "--summary-interval=1",
+ "--console-log-level=warn",
+ "--download-result=hide",
+ "--file-allocation=none",
]);
if !opts.file_name.trim().is_empty() {
cmd.args(["--out", opts.file_name.trim()]);
@@ -73,8 +97,13 @@ pub async fn download(opts: Aria2Options, progress: super::ProgressFn) -> anyhow
cmd.arg(format!("--header={}", h.trim()));
}
}
- cmd.arg(&opts.url).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());
- let mut child = cmd.spawn().map_err(|e| anyhow!("nao foi possivel iniciar o aria2c: {}", e))?;
+ cmd.arg(&opts.url)
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped());
+ let mut child = cmd
+ .spawn()
+ .map_err(|e| anyhow!("nao foi possivel iniciar o aria2c: {}", e))?;
let stdout = child.stdout.take();
let id = format!("aria2:{}", opts.url);
let p2 = progress.clone();
@@ -111,14 +140,18 @@ pub async fn download(opts: Aria2Options, progress: super::ProgressFn) -> anyhow
};
let bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
super::report(&progress, &id, "done", 100, Some(100), None);
- Ok(Aria2Result { path: path.to_string_lossy().to_string(), bytes })
+ Ok(Aria2Result {
+ path: path.to_string_lossy().to_string(),
+ bytes,
+ })
}
#[cfg(test)]
mod tests {
#[test]
fn parses_line() {
- let (p, s) = super::parse_progress("[#2089b0 12MiB/100MiB(12%) CN:16 DL:5.0MiB ETA:10s]").unwrap();
+ let (p, s) =
+ super::parse_progress("[#2089b0 12MiB/100MiB(12%) CN:16 DL:5.0MiB ETA:10s]").unwrap();
assert_eq!(p, 12);
assert_eq!(s, "5.0MiB");
}
diff --git a/src-tauri/omniget-core/src/core/tools/autoclick.rs b/src-tauri/omniget-core/src/core/tools/autoclick.rs
index b740c567..1f00df78 100644
--- a/src-tauri/omniget-core/src/core/tools/autoclick.rs
+++ b/src-tauri/omniget-core/src/core/tools/autoclick.rs
@@ -200,7 +200,8 @@ pub fn toggle() -> anyhow::Result<bool> {
stop();
return Ok(false);
}
- let opts = last_options().ok_or_else(|| anyhow!("configure e inicie uma vez pela tela antes de usar o atalho"))?;
+ let opts = last_options()
+ .ok_or_else(|| anyhow!("configure e inicie uma vez pela tela antes de usar o atalho"))?;
start(opts)?;
Ok(true)
}
@@ -219,7 +220,11 @@ mod tests {
let t = Instant::now();
sleep_until(t + Duration::from_millis(5));
let e = t.elapsed();
- assert!(e >= Duration::from_millis(5) && e < Duration::from_millis(25), "{:?}", e);
+ assert!(
+ e >= Duration::from_millis(5) && e < Duration::from_millis(25),
+ "{:?}",
+ e
+ );
}
#[test]
diff --git a/src-tauri/omniget-core/src/core/tools/calameo.rs b/src-tauri/omniget-core/src/core/tools/calameo.rs
index d439ab49..f63e88b6 100644
--- a/src-tauri/omniget-core/src/core/tools/calameo.rs
+++ b/src-tauri/omniget-core/src/core/tools/calameo.rs
@@ -23,13 +23,24 @@ pub fn page_prefix(html: &str) -> Option<String> {
re2.captures(&img).map(|c| c[1].to_string())
}
-pub async fn download(url: &str, dest_dir: &str, progress: super::ProgressFn) -> anyhow::Result<CalameoResult> {
+pub async fn download(
+ url: &str,
+ dest_dir: &str,
+ progress: super::ProgressFn,
+) -> anyhow::Result<CalameoResult> {
if !url.contains("calameo.com") {
return Err(anyhow!("cole um link do calameo.com"));
}
let client = super::client()?;
- let html = client.get(url).send().await?.error_for_status()?.text().await?;
- let prefix = page_prefix(&html).ok_or_else(|| anyhow!("nao achei as paginas desse documento (privado ou layout novo)"))?;
+ let html = client
+ .get(url)
+ .send()
+ .await?
+ .error_for_status()?
+ .text()
+ .await?;
+ let prefix = page_prefix(&html)
+ .ok_or_else(|| anyhow!("nao achei as paginas desse documento (privado ou layout novo)"))?;
let title = super::slides::og_title(&html).unwrap_or_else(|| "calameo".to_string());
let folder = PathBuf::from(dest_dir).join(super::sanitize_name(&title));
std::fs::create_dir_all(&folder)?;
@@ -63,7 +74,9 @@ pub async fn download(url: &str, dest_dir: &str, progress: super::ProgressFn) ->
break;
}
if n == 0 {
- return Err(anyhow!("nenhuma pagina baixada; o documento pode exigir assinatura de URL"));
+ return Err(anyhow!(
+ "nenhuma pagina baixada; o documento pode exigir assinatura de URL"
+ ));
}
if format == "jpg" {
// com JPEG dá para montar o PDF na hora
@@ -75,7 +88,12 @@ pub async fn download(url: &str, dest_dir: &str, progress: super::ProgressFn) ->
tokio::fs::write(folder.with_extension("pdf"), pdf).await?;
}
super::report(&progress, &id, "done", n as u64, Some(n as u64), None);
- Ok(CalameoResult { title, pages: n, folder: folder.to_string_lossy().to_string(), format })
+ Ok(CalameoResult {
+ title,
+ pages: n,
+ folder: folder.to_string_lossy().to_string(),
+ format,
+ })
}
#[cfg(test)]
@@ -84,7 +102,11 @@ mod tests {
#[test]
fn prefix_from_og_image() {
- let html = r#"<meta property="og:image" content="https://i.calameoassets.com/240101/abc/p1.jpg">"#;
- assert_eq!(page_prefix(html).as_deref(), Some("https://i.calameoassets.com/240101/abc/"));
+ let html =
+ r#"<meta property="og:image" content="https://i.calameoassets.com/240101/abc/p1.jpg">"#;
+ assert_eq!(
+ page_prefix(html).as_deref(),
+ Some("https://i.calameoassets.com/240101/abc/")
+ );
}
}
diff --git a/src-tauri/omniget-core/src/core/tools/dictation.rs b/src-tauri/omniget-core/src/core/tools/dictation.rs
index 1466cbfc..a0002d4d 100644
--- a/src-tauri/omniget-core/src/core/tools/dictation.rs
+++ b/src-tauri/omniget-core/src/core/tools/dictation.rs
@@ -70,9 +70,27 @@ fn set_phase(p: &str) {
pub fn state() -> DictationState {
let phase = PHASE.lock().unwrap_or_else(|e| e.into_inner()).clone();
- let seconds = REC.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|r| r.started.elapsed().as_secs()).unwrap_or(0);
- let (last_text, error) = LAST.lock().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_default();
- DictationState { phase: if phase.is_empty() { "idle".into() } else { phase }, seconds, last_text, error }
+ let seconds = REC
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .as_ref()
+ .map(|r| r.started.elapsed().as_secs())
+ .unwrap_or(0);
+ let (last_text, error) = LAST
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .clone()
+ .unwrap_or_default();
+ DictationState {
+ phase: if phase.is_empty() {
+ "idle".into()
+ } else {
+ phase
+ },
+ seconds,
+ last_text,
+ error,
+ }
}
pub fn set_options(opts: DictationOptions) {
@@ -80,15 +98,31 @@ pub fn set_options(opts: DictationOptions) {
}
pub fn options() -> DictationOptions {
- OPTS.lock().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_else(|| serde_json::from_str("{}").unwrap())
+ OPTS.lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .clone()
+ .unwrap_or_else(|| serde_json::from_str("{}").unwrap())
}
/// Dispositivos de entrada de áudio que o FFmpeg enxerga.
pub async fn devices() -> Vec<AudioDevice> {
- let Ok(ffmpeg) = crate::core::dependencies::ensure_ffmpeg().await else { return vec![] };
+ let Ok(ffmpeg) = crate::core::dependencies::ensure_ffmpeg().await else {
+ return vec![];
+ };
let mut out = Vec::new();
if cfg!(target_os = "macos") {
- let o = crate::core::process::command(&ffmpeg).args(["-hide_banner", "-f", "avfoundation", "-list_devices", "true", "-i", ""]).output().await;
+ let o = crate::core::process::command(&ffmpeg)
+ .args([
+ "-hide_banner",
+ "-f",
+ "avfoundation",
+ "-list_devices",
+ "true",
+ "-i",
+ "",
+ ])
+ .output()
+ .await;
if let Ok(o) = o {
let text = String::from_utf8_lossy(&o.stderr);
let mut in_audio = false;
@@ -106,7 +140,10 @@ pub async fn devices() -> Vec<AudioDevice> {
let idx = &l[i + 1..i + j];
let name = l[i + j + 1..].trim();
if idx.chars().all(|c| c.is_ascii_digit()) {
- out.push(AudioDevice { id: idx.to_string(), name: name.to_string() });
+ out.push(AudioDevice {
+ id: idx.to_string(),
+ name: name.to_string(),
+ });
}
}
}
@@ -114,24 +151,48 @@ pub async fn devices() -> Vec<AudioDevice> {
}
}
} else if cfg!(target_os = "windows") {
- let o = crate::core::process::command(&ffmpeg).args(["-hide_banner", "-list_devices", "true", "-f", "dshow", "-i", "dummy"]).output().await;
+ let o = crate::core::process::command(&ffmpeg)
+ .args([
+ "-hide_banner",
+ "-list_devices",
+ "true",
+ "-f",
+ "dshow",
+ "-i",
+ "dummy",
+ ])
+ .output()
+ .await;
if let Ok(o) = o {
let text = String::from_utf8_lossy(&o.stderr);
for l in text.lines() {
if l.contains("(audio)") {
if let Some(name) = l.split('"').nth(1) {
- out.push(AudioDevice { id: name.to_string(), name: name.to_string() });
+ out.push(AudioDevice {
+ id: name.to_string(),
+ name: name.to_string(),
+ });
}
}
}
}
} else {
- out.push(AudioDevice { id: "default".into(), name: "PulseAudio / PipeWire (default)".into() });
- if let Ok(o) = crate::core::process::command("pactl").args(["list", "short", "sources"]).output().await {
+ out.push(AudioDevice {
+ id: "default".into(),
+ name: "PulseAudio / PipeWire (default)".into(),
+ });
+ if let Ok(o) = crate::core::process::command("pactl")
+ .args(["list", "short", "sources"])
+ .output()
+ .await
+ {
for l in String::from_utf8_lossy(&o.stdout).lines() {
let cols: Vec<&str> = l.split('\t').collect();
if cols.len() > 1 && !cols[1].ends_with(".monitor") {
- out.push(AudioDevice { id: cols[1].to_string(), name: cols[1].to_string() });
+ out.push(AudioDevice {
+ id: cols[1].to_string(),
+ name: cols[1].to_string(),
+ });
}
}
}
@@ -142,11 +203,30 @@ pub async fn devices() -> Vec<AudioDevice> {
fn input_args(device: &str) -> Vec<String> {
let dev = device.trim();
if cfg!(target_os = "macos") {
- vec!["-f".into(), "avfoundation".into(), "-i".into(), format!(":{}", if dev.is_empty() { "0" } else { dev })]
+ vec![
+ "-f".into(),
+ "avfoundation".into(),
+ "-i".into(),
+ format!(":{}", if dev.is_empty() { "0" } else { dev }),
+ ]
} else if cfg!(target_os = "windows") {
- vec!["-f".into(), "dshow".into(), "-i".into(), format!("audio={}", if dev.is_empty() { "default" } else { dev })]
+ vec![
+ "-f".into(),
+ "dshow".into(),
+ "-i".into(),
+ format!("audio={}", if dev.is_empty() { "default" } else { dev }),
+ ]
} else {
- vec!["-f".into(), "pulse".into(), "-i".into(), if dev.is_empty() { "default".into() } else { dev.to_string() }]
+ vec![
+ "-f".into(),
+ "pulse".into(),
+ "-i".into(),
+ if dev.is_empty() {
+ "default".into()
+ } else {
+ dev.to_string()
+ },
+ ]
}
}
@@ -163,10 +243,17 @@ pub async fn start(progress: super::ProgressFn) -> anyhow::Result<()> {
let mut cmd = crate::core::process::command(&ffmpeg);
cmd.args(["-y", "-hide_banner", "-loglevel", "error"]);
cmd.args(input_args(&opts.device));
- cmd.args(["-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le"]).arg(&wav);
- cmd.stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped());
+ cmd.args(["-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le"])
+ .arg(&wav);
+ cmd.stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::piped());
let child = cmd.spawn().map_err(|e| anyhow!("ffmpeg: {}", e))?;
- *REC.lock().unwrap_or_else(|e| e.into_inner()) = Some(Recording { child, wav, started: Instant::now() });
+ *REC.lock().unwrap_or_else(|e| e.into_inner()) = Some(Recording {
+ child,
+ wav,
+ started: Instant::now(),
+ });
set_phase("recording");
*LAST.lock().unwrap_or_else(|e| e.into_inner()) = None;
super::report(&progress, "dictation", "recording", 0, None, None);
@@ -176,7 +263,9 @@ pub async fn start(progress: super::ProgressFn) -> anyhow::Result<()> {
/// Para a gravação, transcreve e entrega o texto. Devolve o texto.
pub async fn stop(progress: super::ProgressFn) -> anyhow::Result<String> {
let rec = REC.lock().unwrap_or_else(|e| e.into_inner()).take();
- let Some(mut rec) = rec else { return Err(anyhow!("nao esta gravando")) };
+ let Some(mut rec) = rec else {
+ return Err(anyhow!("nao esta gravando"));
+ };
set_phase("transcribing");
super::report(&progress, "dictation", "transcribing", 0, None, None);
let result: anyhow::Result<String> = async {
@@ -189,7 +278,8 @@ pub async fn stop(progress: super::ProgressFn) -> anyhow::Result<String> {
let _ = stdin.write_all(b"q\n").await;
let _ = stdin.flush().await;
}
- let status = tokio::time::timeout(std::time::Duration::from_secs(8), rec.child.wait()).await;
+ let status =
+ tokio::time::timeout(std::time::Duration::from_secs(8), rec.child.wait()).await;
if status.is_err() {
let _ = rec.child.kill().await;
}
@@ -199,7 +289,10 @@ pub async fn stop(progress: super::ProgressFn) -> anyhow::Result<String> {
use tokio::io::AsyncReadExt;
let _ = e.read_to_string(&mut err).await;
}
- return Err(anyhow!("nada foi gravado (microfone/permissao?) {}", err.trim()));
+ return Err(anyhow!(
+ "nada foi gravado (microfone/permissao?) {}",
+ err.trim()
+ ));
}
let opts = options();
let out_dir = super::temp_dir().join("dictation-out");
@@ -234,12 +327,27 @@ pub async fn stop(progress: super::ProgressFn) -> anyhow::Result<String> {
match result {
Ok(text) => {
*LAST.lock().unwrap_or_else(|e| e.into_inner()) = Some((text.clone(), None));
- super::report(&progress, "dictation", "done", 1, Some(1), Some(text.clone()));
+ super::report(
+ &progress,
+ "dictation",
+ "done",
+ 1,
+ Some(1),
+ Some(text.clone()),
+ );
Ok(text)
}
Err(e) => {
- *LAST.lock().unwrap_or_else(|e| e.into_inner()) = Some((String::new(), Some(e.to_string())));
- super::report(&progress, "dictation", "error", 0, None, Some(e.to_string()));
+ *LAST.lock().unwrap_or_else(|e| e.into_inner()) =
+ Some((String::new(), Some(e.to_string())));
+ super::report(
+ &progress,
+ "dictation",
+ "error",
+ 0,
+ None,
+ Some(e.to_string()),
+ );
Err(e)
}
}
@@ -252,7 +360,8 @@ pub fn is_recording() -> bool {
/// Digita o texto onde o cursor estiver.
pub fn type_text(text: &str) -> anyhow::Result<()> {
use enigo::{Enigo, Keyboard, Settings};
- let mut enigo = Enigo::new(&Settings::default()).map_err(|e| anyhow!("teclado: {} (macOS: permissao de Acessibilidade)", e))?;
+ let mut enigo = Enigo::new(&Settings::default())
+ .map_err(|e| anyhow!("teclado: {} (macOS: permissao de Acessibilidade)", e))?;
// Um instante para o usuário soltar o atalho antes de digitar.
std::thread::sleep(std::time::Duration::from_millis(150));
enigo.text(text).map_err(|e| anyhow!("digitar: {}", e))?;
@@ -264,10 +373,20 @@ pub fn press_paste() -> anyhow::Result<()> {
use enigo::{Direction, Enigo, Key, Keyboard, Settings};
let mut enigo = Enigo::new(&Settings::default()).map_err(|e| anyhow!("teclado: {}", e))?;
std::thread::sleep(std::time::Duration::from_millis(150));
- let modifier = if cfg!(target_os = "macos") { Key::Meta } else { Key::Control };
- enigo.key(modifier, Direction::Press).map_err(|e| anyhow!("{}", e))?;
- enigo.key(Key::Unicode('v'), Direction::Click).map_err(|e| anyhow!("{}", e))?;
- enigo.key(modifier, Direction::Release).map_err(|e| anyhow!("{}", e))?;
+ let modifier = if cfg!(target_os = "macos") {
+ Key::Meta
+ } else {
+ Key::Control
+ };
+ enigo
+ .key(modifier, Direction::Press)
+ .map_err(|e| anyhow!("{}", e))?;
+ enigo
+ .key(Key::Unicode('v'), Direction::Click)
+ .map_err(|e| anyhow!("{}", e))?;
+ enigo
+ .key(modifier, Direction::Release)
+ .map_err(|e| anyhow!("{}", e))?;
Ok(())
}
diff --git a/src-tauri/omniget-core/src/core/tools/disk.rs b/src-tauri/omniget-core/src/core/tools/disk.rs
index dfd63901..37062d72 100644
--- a/src-tauri/omniget-core/src/core/tools/disk.rs
+++ b/src-tauri/omniget-core/src/core/tools/disk.rs
@@ -22,7 +22,12 @@ fn volume_at(path: &Path, name: &str) -> Option<Volume> {
if total == 0 {
return None;
}
- Some(Volume { path: path.to_string_lossy().to_string(), name: name.to_string(), total, free })
+ Some(Volume {
+ path: path.to_string_lossy().to_string(),
+ name: name.to_string(),
+ total,
+ free,
+ })
}
pub fn volumes() -> Vec<Volume> {
@@ -56,7 +61,11 @@ pub fn volumes() -> Vec<Volume> {
push(PathBuf::from("/"), "/".into());
push(PathBuf::from("/home"), "/home".into());
let user = std::env::var("USER").unwrap_or_default();
- for base in [format!("/media/{}", user), format!("/run/media/{}", user), "/mnt".to_string()] {
+ for base in [
+ format!("/media/{}", user),
+ format!("/run/media/{}", user),
+ "/mnt".to_string(),
+ ] {
if let Ok(rd) = std::fs::read_dir(&base) {
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().to_string();
@@ -98,7 +107,12 @@ pub struct DiskScan {
/// Varre `root` e devolve a árvore até `max_depth` níveis, com no máximo
/// `max_children` filhos por nó (o resto vira "outros").
-pub fn scan(root: &str, max_depth: usize, max_children: usize, progress: &super::ProgressFn) -> anyhow::Result<DiskScan> {
+pub fn scan(
+ root: &str,
+ max_depth: usize,
+ max_children: usize,
+ progress: &super::ProgressFn,
+) -> anyhow::Result<DiskScan> {
let root_path = PathBuf::from(root.trim());
if !root_path.is_dir() {
anyhow::bail!("pasta nao encontrada: {}", root_path.display());
@@ -113,20 +127,32 @@ pub fn scan(root: &str, max_depth: usize, max_children: usize, progress: &super:
let mut skipped = 0u64;
let mut last = std::time::Instant::now();
- let walker = walkdir::WalkDir::new(&root_path).follow_links(false).min_depth(1);
+ let walker = walkdir::WalkDir::new(&root_path)
+ .follow_links(false)
+ .min_depth(1);
// Pilha "caminho → bytes" para fechar diretórios ao sair deles: walkdir é
// pré-ordem, então guardamos o acumulado de cada diretório aberto.
let mut open: Vec<(PathBuf, u64, u64)> = vec![(root_path.clone(), 0, 0)];
let mut immediate: HashMap<PathBuf, Vec<(String, u64, bool, u64)>> = HashMap::new();
- fn close_until(open: &mut Vec<(PathBuf, u64, u64)>, immediate: &mut HashMap<PathBuf, Vec<(String, u64, bool, u64)>>, keep: &Path) {
+ fn close_until(
+ open: &mut Vec<(PathBuf, u64, u64)>,
+ immediate: &mut HashMap<PathBuf, Vec<(String, u64, bool, u64)>>,
+ keep: &Path,
+ ) {
while open.len() > 1 && !keep.starts_with(&open.last().unwrap().0) {
let (p, b, f) = open.pop().unwrap();
let parent = open.last_mut().unwrap();
parent.1 += b;
parent.2 += f;
- let name = p.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
- immediate.entry(parent.0.clone()).or_default().push((name, b, true, f));
+ let name = p
+ .file_name()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_default();
+ immediate
+ .entry(parent.0.clone())
+ .or_default()
+ .push((name, b, true, f));
}
}
@@ -140,7 +166,14 @@ pub fn scan(root: &str, max_depth: usize, max_children: usize, progress: &super:
};
scanned += 1;
if last.elapsed() > std::time::Duration::from_millis(250) {
- super::report(progress, "disk", "progress", scanned, None, Some(entry.path().to_string_lossy().to_string()));
+ super::report(
+ progress,
+ "disk",
+ "progress",
+ scanned,
+ None,
+ Some(entry.path().to_string_lossy().to_string()),
+ );
last = std::time::Instant::now();
}
let path = entry.path().to_path_buf();
@@ -155,9 +188,15 @@ pub fn scan(root: &str, max_depth: usize, max_children: usize, progress: &super:
top.2 += 1;
}
let name = entry.file_name().to_string_lossy().to_string();
- immediate.entry(parent).or_default().push((name, bytes, false, 1));
+ immediate
+ .entry(parent)
+ .or_default()
+ .push((name, bytes, false, 1));
if largest.len() < 60 || bytes > largest.last().map(|b| b.bytes).unwrap_or(0) {
- largest.push(BigFile { path: path.to_string_lossy().to_string(), bytes });
+ largest.push(BigFile {
+ path: path.to_string_lossy().to_string(),
+ bytes,
+ });
largest.sort_by_key(|b| std::cmp::Reverse(b.bytes));
largest.truncate(60);
}
@@ -167,7 +206,16 @@ pub fn scan(root: &str, max_depth: usize, max_children: usize, progress: &super:
let (_, root_bytes, root_files) = open.pop().unwrap_or((root_path.clone(), 0, 0));
#[allow(clippy::too_many_arguments)]
- fn build(path: &Path, name: String, bytes: u64, files: u64, depth: usize, max_depth: usize, max_children: usize, immediate: &HashMap<PathBuf, Vec<(String, u64, bool, u64)>>) -> Node {
+ fn build(
+ path: &Path,
+ name: String,
+ bytes: u64,
+ files: u64,
+ depth: usize,
+ max_depth: usize,
+ max_children: usize,
+ immediate: &HashMap<PathBuf, Vec<(String, u64, bool, u64)>>,
+ ) -> Node {
let mut children = Vec::new();
if depth < max_depth {
if let Some(list) = immediate.get(path) {
@@ -180,9 +228,25 @@ pub fn scan(root: &str, max_depth: usize, max_children: usize, progress: &super:
if i < max_children {
let child_path = path.join(&n);
if is_dir {
- children.push(build(&child_path, n, b, f, depth + 1, max_depth, max_children, immediate));
+ children.push(build(
+ &child_path,
+ n,
+ b,
+ f,
+ depth + 1,
+ max_depth,
+ max_children,
+ immediate,
+ ));
} else {
- children.push(Node { name: n, path: child_path.to_string_lossy().to_string(), bytes: b, is_dir: false, files: 1, children: vec![] });
+ children.push(Node {
+ name: n,
+ path: child_path.to_string_lossy().to_string(),
+ bytes: b,
+ is_dir: false,
+ files: 1,
+ children: vec![],
+ });
}
} else {
rest_bytes += b;
@@ -191,17 +255,48 @@ pub fn scan(root: &str, max_depth: usize, max_children: usize, progress: &super:
}
}
if rest_n > 0 {
- children.push(Node { name: format!("… {} itens", rest_n), path: String::new(), bytes: rest_bytes, is_dir: false, files: rest_files, children: vec![] });
+ children.push(Node {
+ name: format!("… {} itens", rest_n),
+ path: String::new(),
+ bytes: rest_bytes,
+ is_dir: false,
+ files: rest_files,
+ children: vec![],
+ });
}
}
}
- Node { name, path: path.to_string_lossy().to_string(), bytes, is_dir: true, files, children }
+ Node {
+ name,
+ path: path.to_string_lossy().to_string(),
+ bytes,
+ is_dir: true,
+ files,
+ children,
+ }
}
- let name = root_path.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| root_path.to_string_lossy().to_string());
- let root_node = build(&root_path, name, root_bytes, root_files, 0, max_depth, max_children, &immediate);
+ let name = root_path
+ .file_name()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| root_path.to_string_lossy().to_string());
+ let root_node = build(
+ &root_path,
+ name,
+ root_bytes,
+ root_files,
+ 0,
+ max_depth,
+ max_children,
+ &immediate,
+ );
super::report(progress, "disk", "done", scanned, Some(scanned), None);
- Ok(DiskScan { root: root_node, largest, scanned, skipped })
+ Ok(DiskScan {
+ root: root_node,
+ largest,
+ scanned,
+ skipped,
+ })
}
/// Move para a lixeira (nunca apaga direto).
@@ -231,7 +326,13 @@ mod tests {
std::fs::write(dir.join("a/x.bin"), vec![0u8; 300]).unwrap();
std::fs::write(dir.join("a/b/y.bin"), vec![0u8; 200]).unwrap();
std::fs::write(dir.join("z.bin"), vec![0u8; 100]).unwrap();
- let s = scan(&dir.to_string_lossy(), 3, 50, &super::super::noop_progress()).unwrap();
+ let s = scan(
+ &dir.to_string_lossy(),
+ 3,
+ 50,
+ &super::super::noop_progress(),
+ )
+ .unwrap();
assert_eq!(s.root.bytes, 600);
assert_eq!(s.root.files, 3);
let a = s.root.children.iter().find(|c| c.name == "a").unwrap();
diff --git a/src-tauri/omniget-core/src/core/tools/dub.rs b/src-tauri/omniget-core/src/core/tools/dub.rs
index 771cd5b5..eb5f8be3 100644
--- a/src-tauri/omniget-core/src/core/tools/dub.rs
+++ b/src-tauri/omniget-core/src/core/tools/dub.rs
@@ -64,7 +64,10 @@ pub fn atempo_chain(speed: f64) -> String {
pub async fn dub(opts: DubOptions, progress: super::ProgressFn) -> anyhow::Result<DubResult> {
let id = "dub";
let srt = tokio::fs::read_to_string(&opts.srt_path).await?;
- let cues: Vec<Cue> = parse_cues(&srt).into_iter().filter(|c| !c.text.trim().is_empty()).collect();
+ let cues: Vec<Cue> = parse_cues(&srt)
+ .into_iter()
+ .filter(|c| !c.text.trim().is_empty())
+ .collect();
if cues.is_empty() {
return Err(anyhow!("a legenda nao tem falas"));
}
@@ -72,7 +75,10 @@ pub async fn dub(opts: DubOptions, progress: super::ProgressFn) -> anyhow::Resul
let work = super::temp_dir().join(format!("dub-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&work)?;
let out_dir = if opts.output_dir.trim().is_empty() {
- Path::new(&opts.srt_path).parent().map(|p| p.to_path_buf()).unwrap_or_else(|| PathBuf::from("."))
+ Path::new(&opts.srt_path)
+ .parent()
+ .map(|p| p.to_path_buf())
+ .unwrap_or_else(|| PathBuf::from("."))
} else {
PathBuf::from(opts.output_dir.trim())
};
@@ -86,7 +92,14 @@ pub async fn dub(opts: DubOptions, progress: super::ProgressFn) -> anyhow::Resul
let mut pieces: Vec<(PathBuf, u64, u64)> = Vec::new(); // (mp3, start_ms, slot_ms)
let total = cues.len() as u64;
for (i, cue) in cues.iter().enumerate() {
- super::report(&progress, id, "synthesize", i as u64, Some(total), Some(cue.text.clone()));
+ super::report(
+ &progress,
+ id,
+ "synthesize",
+ i as u64,
+ Some(total),
+ Some(cue.text.clone()),
+ );
let mp3 = work.join(format!("{:05}.mp3", i));
let tts = TtsOptions {
text: cue.text.replace('\n', " "),
@@ -96,8 +109,16 @@ pub async fn dub(opts: DubOptions, progress: super::ProgressFn) -> anyhow::Resul
volume: "+0%".into(),
};
edge_tts::synthesize(tts, &mp3, super::noop_progress()).await?;
- let slot_end = cues.get(i + 1).map(|n| n.start_ms).unwrap_or(cue.end_ms).max(cue.end_ms);
- pieces.push((mp3, cue.start_ms, slot_end.saturating_sub(cue.start_ms).max(300)));
+ let slot_end = cues
+ .get(i + 1)
+ .map(|n| n.start_ms)
+ .unwrap_or(cue.end_ms)
+ .max(cue.end_ms);
+ pieces.push((
+ mp3,
+ cue.start_ms,
+ slot_end.saturating_sub(cue.start_ms).max(300),
+ ));
}
// 2) mede duração real e decide a velocidade
@@ -138,10 +159,21 @@ pub async fn dub(opts: DubOptions, progress: super::ProgressFn) -> anyhow::Resul
labels,
group.len()
));
- cmd.args(["-filter_complex", &filter, "-map", "[out]", "-c:a", "pcm_s16le"]).arg(&out);
+ cmd.args([
+ "-filter_complex",
+ &filter,
+ "-map",
+ "[out]",
+ "-c:a",
+ "pcm_s16le",
+ ])
+ .arg(&out);
let output = cmd.output().await?;
if !output.status.success() {
- return Err(anyhow!("ffmpeg (mix) falhou: {}", String::from_utf8_lossy(&output.stderr).trim()));
+ return Err(anyhow!(
+ "ffmpeg (mix) falhou: {}",
+ String::from_utf8_lossy(&output.stderr).trim()
+ ));
}
group_files.push(out);
}
@@ -156,11 +188,27 @@ pub async fn dub(opts: DubOptions, progress: super::ProgressFn) -> anyhow::Resul
for j in 0..group_files.len() {
filter.push_str(&format!("[{j}:a]"));
}
- filter.push_str(&format!("amix=inputs={}:dropout_transition=0:normalize=0[out]", group_files.len()));
- cmd.args(["-filter_complex", &filter, "-map", "[out]", "-c:a", "aac", "-b:a", "160k"]).arg(&dub_audio);
+ filter.push_str(&format!(
+ "amix=inputs={}:dropout_transition=0:normalize=0[out]",
+ group_files.len()
+ ));
+ cmd.args([
+ "-filter_complex",
+ &filter,
+ "-map",
+ "[out]",
+ "-c:a",
+ "aac",
+ "-b:a",
+ "160k",
+ ])
+ .arg(&dub_audio);
let output = cmd.output().await?;
if !output.status.success() {
- return Err(anyhow!("ffmpeg (final) falhou: {}", String::from_utf8_lossy(&output.stderr).trim()));
+ return Err(anyhow!(
+ "ffmpeg (final) falhou: {}",
+ String::from_utf8_lossy(&output.stderr).trim()
+ ));
}
}
@@ -169,10 +217,16 @@ pub async fn dub(opts: DubOptions, progress: super::ProgressFn) -> anyhow::Resul
if !opts.video_path.trim().is_empty() {
super::report(&progress, id, "mux", 0, Some(1), None);
let video = Path::new(opts.video_path.trim());
- let ext = video.extension().map(|e| e.to_string_lossy().to_string()).unwrap_or_else(|| "mp4".into());
+ let ext = video
+ .extension()
+ .map(|e| e.to_string_lossy().to_string())
+ .unwrap_or_else(|| "mp4".into());
let out = out_dir.join(format!("{}.dub.{}", stem, ext));
let mut cmd = crate::core::process::command(&ffmpeg);
- cmd.args(["-y", "-hide_banner", "-loglevel", "error", "-i"]).arg(video).arg("-i").arg(&dub_audio);
+ cmd.args(["-y", "-hide_banner", "-loglevel", "error", "-i"])
+ .arg(video)
+ .arg("-i")
+ .arg(&dub_audio);
if opts.keep_original_volume > 0.0 {
let f = format!(
"[0:a]volume={:.2}[o];[1:a]volume=1.0[d];[o][d]amix=inputs=2:dropout_transition=0:normalize=0[a]",
@@ -182,10 +236,14 @@ pub async fn dub(opts: DubOptions, progress: super::ProgressFn) -> anyhow::Resul
} else {
cmd.args(["-map", "0:v", "-map", "1:a"]);
}
- cmd.args(["-c:v", "copy", "-c:a", "aac", "-shortest"]).arg(&out);
+ cmd.args(["-c:v", "copy", "-c:a", "aac", "-shortest"])
+ .arg(&out);
let output = cmd.output().await?;
if !output.status.success() {
- return Err(anyhow!("ffmpeg (mux) falhou: {}", String::from_utf8_lossy(&output.stderr).trim()));
+ return Err(anyhow!(
+ "ffmpeg (mux) falhou: {}",
+ String::from_utf8_lossy(&output.stderr).trim()
+ ));
}
video_out = Some(out.to_string_lossy().to_string());
}
diff --git a/src-tauri/omniget-core/src/core/tools/dupes.rs b/src-tauri/omniget-core/src/core/tools/dupes.rs
index 861bcff5..7ff9e00d 100644
--- a/src-tauri/omniget-core/src/core/tools/dupes.rs
+++ b/src-tauri/omniget-core/src/core/tools/dupes.rs
@@ -49,7 +49,9 @@ pub struct DupesResult {
fn walk(root: &Path, skip_hidden: bool, out: &mut Vec<(PathBuf, u64)>, seen: &mut u64) {
let mut stack = vec![root.to_path_buf()];
while let Some(dir) = stack.pop() {
- let Ok(rd) = std::fs::read_dir(&dir) else { continue };
+ let Ok(rd) = std::fs::read_dir(&dir) else {
+ continue;
+ };
for entry in rd.flatten() {
let p = entry.path();
let name = entry.file_name().to_string_lossy().to_string();
@@ -94,21 +96,30 @@ pub fn scan(opts: &DupesOptions, progress: &super::ProgressFn) -> DupesResult {
for d in &opts.dirs {
walk(Path::new(d), opts.skip_hidden, &mut files, &mut scanned);
}
- let exts: Vec<String> = opts.extensions.iter().map(|e| e.trim().trim_start_matches('.').to_lowercase()).filter(|e| !e.is_empty()).collect();
+ let exts: Vec<String> = opts
+ .extensions
+ .iter()
+ .map(|e| e.trim().trim_start_matches('.').to_lowercase())
+ .filter(|e| !e.is_empty())
+ .collect();
let mut by_size: HashMap<u64, Vec<PathBuf>> = HashMap::new();
for (p, size) in files {
if size < opts.min_size {
continue;
}
if !exts.is_empty() {
- let ext = p.extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();
+ let ext = p
+ .extension()
+ .map(|e| e.to_string_lossy().to_lowercase())
+ .unwrap_or_default();
if !exts.contains(&ext) {
continue;
}
}
by_size.entry(size).or_default().push(p);
}
- let candidates: Vec<(u64, Vec<PathBuf>)> = by_size.into_iter().filter(|(_, v)| v.len() > 1).collect();
+ let candidates: Vec<(u64, Vec<PathBuf>)> =
+ by_size.into_iter().filter(|(_, v)| v.len() > 1).collect();
let total = candidates.iter().map(|(_, v)| v.len() as u64).sum::<u64>();
let mut done = 0u64;
let mut groups = Vec::new();
@@ -146,9 +157,16 @@ pub fn scan(opts: &DupesOptions, progress: &super::ProgressFn) -> DupesResult {
}
}
groups.sort_by_key(|b| std::cmp::Reverse(b.size * (b.files.len() as u64 - 1)));
- let wasted = groups.iter().map(|g| g.size * (g.files.len() as u64 - 1)).sum();
+ let wasted = groups
+ .iter()
+ .map(|g| g.size * (g.files.len() as u64 - 1))
+ .sum();
super::report(progress, id, "done", total, Some(total), None);
- DupesResult { scanned, groups, wasted_bytes: wasted }
+ DupesResult {
+ scanned,
+ groups,
+ wasted_bytes: wasted,
+ }
}
pub fn delete(paths: &[String]) -> (Vec<String>, Vec<String>) {
@@ -175,7 +193,12 @@ mod tests {
std::fs::write(dir.join("a.bin"), &big).unwrap();
std::fs::write(dir.join("sub").join("b.bin"), &big).unwrap();
std::fs::write(dir.join("c.bin"), vec![1u8; 70 * 1024]).unwrap();
- let opts = DupesOptions { dirs: vec![dir.to_string_lossy().to_string()], min_size: 1024, extensions: vec![], skip_hidden: true };
+ let opts = DupesOptions {
+ dirs: vec![dir.to_string_lossy().to_string()],
+ min_size: 1024,
+ extensions: vec![],
+ skip_hidden: true,
+ };
let r = scan(&opts, &super::super::noop_progress());
assert_eq!(r.groups.len(), 1);
assert_eq!(r.groups[0].files.len(), 2);
diff --git a/src-tauri/omniget-core/src/core/tools/edge_tts.rs b/src-tauri/omniget-core/src/core/tools/edge_tts.rs
index fa03c592..9253c816 100644
--- a/src-tauri/omniget-core/src/core/tools/edge_tts.rs
+++ b/src-tauri/omniget-core/src/core/tools/edge_tts.rs
@@ -77,16 +77,29 @@ pub async fn list_voices() -> anyhow::Result<Vec<Voice>> {
let resp = client
.get(&url)
.header("Authority", "speech.platform.bing.com")
- .header("Sec-CH-UA", format!("\" Not;A Brand\";v=\"99\", \"Microsoft Edge\";v=\"{0}\", \"Chromium\";v=\"{0}\"", chromium_major()))
+ .header(
+ "Sec-CH-UA",
+ format!(
+ "\" Not;A Brand\";v=\"99\", \"Microsoft Edge\";v=\"{0}\", \"Chromium\";v=\"{0}\"",
+ chromium_major()
+ ),
+ )
.header("Sec-CH-UA-Mobile", "?0")
.header("Accept", "*/*")
.send()
.await?;
if !resp.status().is_success() {
- return Err(anyhow!("lista de vozes do Edge indisponivel: HTTP {}", resp.status()));
+ return Err(anyhow!(
+ "lista de vozes do Edge indisponivel: HTTP {}",
+ resp.status()
+ ));
}
let mut voices: Vec<Voice> = resp.json().await?;
- voices.sort_by(|a, b| a.locale.cmp(&b.locale).then(a.short_name.cmp(&b.short_name)));
+ voices.sort_by(|a, b| {
+ a.locale
+ .cmp(&b.locale)
+ .then(a.short_name.cmp(&b.short_name))
+ });
if let Ok(mut g) = VOICES.lock() {
*g = Some((std::time::Instant::now(), voices.clone()));
}
@@ -129,7 +142,9 @@ pub struct TtsResult {
}
fn escape_xml(s: &str) -> String {
- s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
+ s.replace('&', "&amp;")
+ .replace('<', "&lt;")
+ .replace('>', "&gt;")
}
fn mkssml(text: &str, voice: &str, rate: &str, pitch: &str, volume: &str) -> String {
@@ -140,7 +155,9 @@ fn mkssml(text: &str, voice: &str, rate: &str, pitch: &str, volume: &str) -> Str
}
fn date_string() -> String {
- chrono::Utc::now().format("%a %b %d %Y %H:%M:%S GMT+0000 (Coordinated Universal Time)").to_string()
+ chrono::Utc::now()
+ .format("%a %b %d %Y %H:%M:%S GMT+0000 (Coordinated Universal Time)")
+ .to_string()
}
/// Divide por frases sem passar de `CHUNK_BYTES`, sem cortar UTF-8.
@@ -167,7 +184,11 @@ pub fn split_text(text: &str) -> Vec<String> {
if !current.trim().is_empty() {
chunks.push(current);
}
- chunks.into_iter().map(|c| c.trim().to_string()).filter(|c| !c.is_empty()).collect()
+ chunks
+ .into_iter()
+ .map(|c| c.trim().to_string())
+ .filter(|c| !c.is_empty())
+ .collect()
}
struct ChunkOut {
@@ -177,7 +198,9 @@ struct ChunkOut {
fn parse_metadata(json: &str) -> Vec<WordBoundary> {
let mut out = Vec::new();
- let Ok(v) = serde_json::from_str::<serde_json::Value>(json) else { return out };
+ let Ok(v) = serde_json::from_str::<serde_json::Value>(json) else {
+ return out;
+ };
if let Some(items) = v["Metadata"].as_array() {
for it in items {
if it["Type"].as_str() != Some("WordBoundary") {
@@ -187,7 +210,11 @@ fn parse_metadata(json: &str) -> Vec<WordBoundary> {
let offset = d["Offset"].as_u64().unwrap_or(0);
let dur = d["Duration"].as_u64().unwrap_or(0);
let text = d["text"]["Text"].as_str().unwrap_or("").to_string();
- out.push(WordBoundary { text, start_ms: offset / 10_000, duration_ms: dur / 10_000 });
+ out.push(WordBoundary {
+ text,
+ start_ms: offset / 10_000,
+ duration_ms: dur / 10_000,
+ });
}
}
out
@@ -208,7 +235,10 @@ async fn synth_chunk(text: &str, opts: &TtsOptions, skew: i64) -> anyhow::Result
let h = req.headers_mut();
h.insert("Pragma", "no-cache".parse()?);
h.insert("Cache-Control", "no-cache".parse()?);
- h.insert("Origin", "chrome-extension://jdiccldimpdaibmpdkjnbmckianbfold".parse()?);
+ h.insert(
+ "Origin",
+ "chrome-extension://jdiccldimpdaibmpdkjnbmckianbfold".parse()?,
+ );
h.insert("Accept-Encoding", "gzip, deflate, br".parse()?);
h.insert("Accept-Language", "en-US,en;q=0.9".parse()?);
h.insert(
@@ -229,7 +259,13 @@ async fn synth_chunk(text: &str, opts: &TtsOptions, skew: i64) -> anyhow::Result
date_string()
);
ws.send(Message::Text(cfg.into())).await?;
- let ssml = mkssml(&escape_xml(text), &opts.voice, &opts.rate, &opts.pitch, &opts.volume);
+ let ssml = mkssml(
+ &escape_xml(text),
+ &opts.voice,
+ &opts.rate,
+ &opts.pitch,
+ &opts.volume,
+ );
let req_id = connect_id();
let msg = format!(
"X-RequestId:{}\r\nContent-Type:application/ssml+xml\r\nX-Timestamp:{}Z\r\nPath:ssml\r\n\r\n{}",
@@ -294,8 +330,16 @@ pub fn words_to_cues(words: &[WordBoundary]) -> Vec<Cue> {
let start = buf[0].start_ms;
let last = buf[buf.len() - 1];
let end = last.start_ms + last.duration_ms.max(200);
- let text = buf.iter().map(|w| w.text.as_str()).collect::<Vec<_>>().join(" ");
- cues.push(Cue { start_ms: start, end_ms: end.max(start + 1), text });
+ let text = buf
+ .iter()
+ .map(|w| w.text.as_str())
+ .collect::<Vec<_>>()
+ .join(" ");
+ cues.push(Cue {
+ start_ms: start,
+ end_ms: end.max(start + 1),
+ text,
+ });
buf.clear();
};
for w in words {
@@ -312,7 +356,11 @@ pub fn words_to_cues(words: &[WordBoundary]) -> Vec<Cue> {
}
/// Sintetiza `opts.text` inteiro em `audio_path` (MP3) e escreve o SRT ao lado.
-pub async fn synthesize(opts: TtsOptions, audio_path: &std::path::Path, progress: super::ProgressFn) -> anyhow::Result<TtsResult> {
+pub async fn synthesize(
+ opts: TtsOptions,
+ audio_path: &std::path::Path,
+ progress: super::ProgressFn,
+) -> anyhow::Result<TtsResult> {
let chunks = split_text(&opts.text);
if chunks.is_empty() {
return Err(anyhow!("texto vazio"));
@@ -323,7 +371,14 @@ pub async fn synthesize(opts: TtsOptions, audio_path: &std::path::Path, progress
let mut offset_ms: u64 = 0;
let mut skew: i64 = 0;
for (i, chunk) in chunks.iter().enumerate() {
- super::report(&progress, &id, "synthesize", i as u64, Some(chunks.len() as u64), None);
+ super::report(
+ &progress,
+ &id,
+ "synthesize",
+ i as u64,
+ Some(chunks.len() as u64),
+ None,
+ );
let out = match synth_chunk(chunk, &opts, skew).await {
Ok(o) => o,
Err(e) => {
@@ -338,7 +393,12 @@ pub async fn synthesize(opts: TtsOptions, audio_path: &std::path::Path, progress
}
}
};
- let last_end = out.words.iter().map(|w| w.start_ms + w.duration_ms).max().unwrap_or(0);
+ let last_end = out
+ .words
+ .iter()
+ .map(|w| w.start_ms + w.duration_ms)
+ .max()
+ .unwrap_or(0);
for mut w in out.words {
w.start_ms += offset_ms;
words.push(w);
@@ -354,8 +414,19 @@ pub async fn synthesize(opts: TtsOptions, audio_path: &std::path::Path, progress
let cues = words_to_cues(&words);
let srt_path = audio_path.with_extension("srt");
tokio::fs::write(&srt_path, cues_to_srt(&cues)).await?;
- let duration_ms = words.iter().map(|w| w.start_ms + w.duration_ms).max().unwrap_or(0);
- super::report(&progress, &id, "done", chunks.len() as u64, Some(chunks.len() as u64), None);
+ let duration_ms = words
+ .iter()
+ .map(|w| w.start_ms + w.duration_ms)
+ .max()
+ .unwrap_or(0);
+ super::report(
+ &progress,
+ &id,
+ "done",
+ chunks.len() as u64,
+ Some(chunks.len() as u64),
+ None,
+ );
Ok(TtsResult {
audio_path: audio_path.to_string_lossy().to_string(),
srt_path: srt_path.to_string_lossy().to_string(),
@@ -372,7 +443,9 @@ mod tests {
fn gec_is_64_hex_upper() {
let g = sec_ms_gec(0);
assert_eq!(g.len(), 64);
- assert!(g.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_lowercase()));
+ assert!(g
+ .chars()
+ .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_lowercase()));
}
#[test]
@@ -386,7 +459,11 @@ mod tests {
#[test]
fn groups_words_into_cues() {
let words: Vec<WordBoundary> = (0..20)
- .map(|i| WordBoundary { text: format!("w{}", i), start_ms: i * 300, duration_ms: 250 })
+ .map(|i| WordBoundary {
+ text: format!("w{}", i),
+ start_ms: i * 300,
+ duration_ms: 250,
+ })
.collect();
let cues = words_to_cues(&words);
assert_eq!(cues.len(), 3);
diff --git a/src-tauri/omniget-core/src/core/tools/file_search.rs b/src-tauri/omniget-core/src/core/tools/file_search.rs
index 379c1f90..3f2d329c 100644
--- a/src-tauri/omniget-core/src/core/tools/file_search.rs
+++ b/src-tauri/omniget-core/src/core/tools/file_search.rs
@@ -20,7 +20,10 @@ async fn es_path() -> Option<PathBuf> {
if let Some(p) = crate::core::dependencies::find_tool("es").await {
return Some(p);
}
- for base in ["C:\\Program Files\\Everything", "C:\\Program Files (x86)\\Everything"] {
+ for base in [
+ "C:\\Program Files\\Everything",
+ "C:\\Program Files (x86)\\Everything",
+ ] {
let p = PathBuf::from(base).join("es.exe");
if p.exists() {
return Some(p);
@@ -42,13 +45,24 @@ pub async fn backend() -> SearchBackend {
}
#[cfg(target_os = "macos")]
{
- SearchBackend { name: "Spotlight".into(), available: true, path: Some("/usr/bin/mdfind".into()), install_hint: String::new() }
+ SearchBackend {
+ name: "Spotlight".into(),
+ available: true,
+ path: Some("/usr/bin/mdfind".into()),
+ install_hint: String::new(),
+ }
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
{
- let fd = crate::core::dependencies::find_tool("fd").await.or(crate::core::dependencies::find_tool("fdfind").await);
+ let fd = crate::core::dependencies::find_tool("fd")
+ .await
+ .or(crate::core::dependencies::find_tool("fdfind").await);
SearchBackend {
- name: if fd.is_some() { "fd".into() } else { "find".into() },
+ name: if fd.is_some() {
+ "fd".into()
+ } else {
+ "find".into()
+ },
available: true,
path: fd.map(|p| p.to_string_lossy().to_string()),
install_hint: "sudo apt install fd-find (opcional, mais rapido)".into(),
@@ -72,7 +86,9 @@ pub async fn search(query: &str, folder: &str, limit: usize) -> anyhow::Result<V
let output;
#[cfg(target_os = "windows")]
{
- let es = es_path().await.ok_or_else(|| anyhow!("Everything (es.exe) nao encontrado"))?;
+ let es = es_path()
+ .await
+ .ok_or_else(|| anyhow!("Everything (es.exe) nao encontrado"))?;
let mut cmd = crate::core::process::command(&es);
cmd.args(["-n", &limit.to_string()]);
if !folder.trim().is_empty() {
@@ -93,18 +109,35 @@ pub async fn search(query: &str, folder: &str, limit: usize) -> anyhow::Result<V
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
{
let root = if folder.trim().is_empty() {
- dirs::home_dir().map(|h| h.to_string_lossy().to_string()).unwrap_or_else(|| "/".into())
+ dirs::home_dir()
+ .map(|h| h.to_string_lossy().to_string())
+ .unwrap_or_else(|| "/".into())
} else {
folder.trim().to_string()
};
- let fd = crate::core::dependencies::find_tool("fd").await.or(crate::core::dependencies::find_tool("fdfind").await);
+ let fd = crate::core::dependencies::find_tool("fd")
+ .await
+ .or(crate::core::dependencies::find_tool("fdfind").await);
output = match fd {
- Some(fd) => crate::core::process::command(&fd).args(["-i", "--max-results", &limit.to_string(), q, &root]).output().await?,
- None => crate::core::process::command("find").args([&root, "-iname", &format!("*{}*", q)]).output().await?,
+ Some(fd) => {
+ crate::core::process::command(&fd)
+ .args(["-i", "--max-results", &limit.to_string(), q, &root])
+ .output()
+ .await?
+ }
+ None => {
+ crate::core::process::command("find")
+ .args([&root, "-iname", &format!("*{}*", q)])
+ .output()
+ .await?
+ }
};
}
if !output.status.success() && output.stdout.is_empty() {
- return Err(anyhow!("busca falhou: {}", String::from_utf8_lossy(&output.stderr).trim()));
+ return Err(anyhow!(
+ "busca falhou: {}",
+ String::from_utf8_lossy(&output.stderr).trim()
+ ));
}
let text = String::from_utf8_lossy(&output.stdout);
let hits = text
diff --git a/src-tauri/omniget-core/src/core/tools/gallery.rs b/src-tauri/omniget-core/src/core/tools/gallery.rs
index 7ea8eb28..1d8f4068 100644
--- a/src-tauri/omniget-core/src/core/tools/gallery.rs
+++ b/src-tauri/omniget-core/src/core/tools/gallery.rs
@@ -17,7 +17,11 @@ pub async fn status() -> GalleryStatus {
Some(p) => crate::core::dependencies::check_version_at_path(p, "gallery-dl").await,
None => None,
};
- GalleryStatus { installed: path.is_some(), path: path.map(|p| p.to_string_lossy().to_string()), version }
+ GalleryStatus {
+ installed: path.is_some(),
+ path: path.map(|p| p.to_string_lossy().to_string()),
+ version,
+ }
}
pub async fn install() -> anyhow::Result<String> {
@@ -34,7 +38,12 @@ pub struct GalleryResult {
pub log_tail: String,
}
-pub async fn download(url: &str, dest: &str, cookies_file: Option<&str>, progress: super::ProgressFn) -> anyhow::Result<GalleryResult> {
+pub async fn download(
+ url: &str,
+ dest: &str,
+ cookies_file: Option<&str>,
+ progress: super::ProgressFn,
+) -> anyhow::Result<GalleryResult> {
use tokio::io::{AsyncBufReadExt, BufReader};
let bin = crate::core::dependencies::ensure_gallerydl()
.await
@@ -49,7 +58,9 @@ pub async fn download(url: &str, dest: &str, cookies_file: Option<&str>, progres
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
- let mut child = cmd.spawn().map_err(|e| anyhow!("nao foi possivel iniciar o gallery-dl: {}", e))?;
+ let mut child = cmd
+ .spawn()
+ .map_err(|e| anyhow!("nao foi possivel iniciar o gallery-dl: {}", e))?;
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let id = format!("gallery:{}", url);
@@ -85,6 +96,17 @@ pub async fn download(url: &str, dest: &str, cookies_file: Option<&str>, progres
if !status.success() && files.is_empty() {
return Err(anyhow!("gallery-dl falhou: {}", tail));
}
- super::report(&progress, &id, "done", files.len() as u64, Some(files.len() as u64), None);
- Ok(GalleryResult { files, dest: dest.to_string(), log_tail: tail })
+ super::report(
+ &progress,
+ &id,
+ "done",
+ files.len() as u64,
+ Some(files.len() as u64),
+ None,
+ );
+ Ok(GalleryResult {
+ files,
+ dest: dest.to_string(),
+ log_tail: tail,
+ })
}
diff --git a/src-tauri/omniget-core/src/core/tools/gdocs.rs b/src-tauri/omniget-core/src/core/tools/gdocs.rs
index 53185cef..2f0a549f 100644
--- a/src-tauri/omniget-core/src/core/tools/gdocs.rs
+++ b/src-tauri/omniget-core/src/core/tools/gdocs.rs
@@ -14,7 +14,10 @@ pub struct GdocInfo {
}
pub fn parse(url: &str) -> Option<GdocInfo> {
- let re = regex::Regex::new(r"docs\.google\.com/(document|presentation|spreadsheets)/d/([A-Za-z0-9_-]+)").ok()?;
+ let re = regex::Regex::new(
+ r"docs\.google\.com/(document|presentation|spreadsheets)/d/([A-Za-z0-9_-]+)",
+ )
+ .ok()?;
let c = re.captures(url)?;
let kind = c[1].to_string();
let formats = match kind.as_str() {
@@ -22,11 +25,18 @@ pub fn parse(url: &str) -> Option<GdocInfo> {
"presentation" => vec!["pdf", "pptx", "odp", "txt"],
_ => vec!["pdf", "xlsx", "ods", "csv"],
};
- Some(GdocInfo { kind, id: c[2].to_string(), formats: formats.into_iter().map(String::from).collect() })
+ Some(GdocInfo {
+ kind,
+ id: c[2].to_string(),
+ formats: formats.into_iter().map(String::from).collect(),
+ })
}
pub fn export_url(info: &GdocInfo, format: &str) -> String {
- format!("https://docs.google.com/{}/d/{}/export?format={}", info.kind, info.id, format)
+ format!(
+ "https://docs.google.com/{}/d/{}/export?format={}",
+ info.kind, info.id, format
+ )
}
fn filename_from_disposition(v: &str) -> Option<String> {
@@ -42,16 +52,29 @@ fn filename_from_disposition(v: &str) -> Option<String> {
Some(s[..end].trim_matches('"').to_string())
}
-pub async fn download(url: &str, format: &str, dest_dir: &str, progress: super::ProgressFn) -> anyhow::Result<String> {
- let info = parse(url).ok_or_else(|| anyhow!("cole um link de docs.google.com (Documentos, Apresentações ou Planilhas)"))?;
+pub async fn download(
+ url: &str,
+ format: &str,
+ dest_dir: &str,
+ progress: super::ProgressFn,
+) -> anyhow::Result<String> {
+ let info = parse(url).ok_or_else(|| {
+ anyhow!("cole um link de docs.google.com (Documentos, Apresentações ou Planilhas)")
+ })?;
if !info.formats.iter().any(|f| f == format) {
- return Err(anyhow!("formato {} nao disponivel para {}", format, info.kind));
+ return Err(anyhow!(
+ "formato {} nao disponivel para {}",
+ format,
+ info.kind
+ ));
}
let client = super::client()?;
let export = export_url(&info, format);
let resp = client.get(&export).send().await?;
if resp.status().as_u16() == 401 || resp.status().as_u16() == 403 {
- return Err(anyhow!("o arquivo nao e publico; abra no navegador e use Arquivo > Fazer download"));
+ return Err(anyhow!(
+ "o arquivo nao e publico; abra no navegador e use Arquivo > Fazer download"
+ ));
}
if !resp.status().is_success() {
return Err(anyhow!("Google Docs: HTTP {}", resp.status()));
@@ -67,7 +90,14 @@ pub async fn download(url: &str, format: &str, dest_dir: &str, progress: super::
let dest = dir.join(super::sanitize_name(&name));
let bytes = resp.bytes().await?;
tokio::fs::write(&dest, &bytes).await?;
- super::report(&progress, "gdocs", "done", bytes.len() as u64, Some(bytes.len() as u64), None);
+ super::report(
+ &progress,
+ "gdocs",
+ "done",
+ bytes.len() as u64,
+ Some(bytes.len() as u64),
+ None,
+ );
Ok(dest.to_string_lossy().to_string())
}
@@ -81,12 +111,21 @@ mod tests {
assert_eq!(i.kind, "presentation");
assert_eq!(i.id, "1AbC_d-e");
assert!(parse("https://drive.google.com/x").is_none());
- assert_eq!(export_url(&i, "pdf"), "https://docs.google.com/presentation/d/1AbC_d-e/export?format=pdf");
+ assert_eq!(
+ export_url(&i, "pdf"),
+ "https://docs.google.com/presentation/d/1AbC_d-e/export?format=pdf"
+ );
}
#[test]
fn disposition() {
- assert_eq!(filename_from_disposition("attachment; filename=\"a b.pdf\"").as_deref(), Some("a b.pdf"));
- assert_eq!(filename_from_disposition("attachment; filename*=UTF-8''caf%C3%A9.pdf").as_deref(), Some("café.pdf"));
+ assert_eq!(
+ filename_from_disposition("attachment; filename=\"a b.pdf\"").as_deref(),
+ Some("a b.pdf")
+ );
+ assert_eq!(
+ filename_from_disposition("attachment; filename*=UTF-8''caf%C3%A9.pdf").as_deref(),
+ Some("café.pdf")
+ );
}
}
diff --git a/src-tauri/omniget-core/src/core/tools/github.rs b/src-tauri/omniget-core/src/core/tools/github.rs
index 1f9e4d49..362b9a28 100644
--- a/src-tauri/omniget-core/src/core/tools/github.rs
+++ b/src-tauri/omniget-core/src/core/tools/github.rs
@@ -13,11 +13,16 @@ pub fn client() -> anyhow::Result<reqwest::Client> {
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, USER_AGENT};
let mut headers = HeaderMap::new();
headers.insert(USER_AGENT, HeaderValue::from_static("OmniGet"));
- headers.insert(ACCEPT, HeaderValue::from_static("application/vnd.github+json"));
- Ok(crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .default_headers(headers)
- .timeout(std::time::Duration::from_secs(600))
- .build()?)
+ headers.insert(
+ ACCEPT,
+ HeaderValue::from_static("application/vnd.github+json"),
+ );
+ Ok(
+ crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .default_headers(headers)
+ .timeout(std::time::Duration::from_secs(600))
+ .build()?,
+ )
}
#[derive(Debug, Clone)]
@@ -61,11 +66,17 @@ pub async fn asset(
name: name.to_string(),
url: a["browser_download_url"].as_str().unwrap_or("").to_string(),
size: a["size"].as_u64().unwrap_or(0),
- digest: a["digest"].as_str().and_then(integrity::parse_github_digest),
+ digest: a["digest"]
+ .as_str()
+ .and_then(integrity::parse_github_digest),
});
}
}
- Err(anyhow!("release {} de {} nao tem um asset para este sistema", tag, repo))
+ Err(anyhow!(
+ "release {} de {} nao tem um asset para este sistema",
+ tag,
+ repo
+ ))
}
/// Baixa e confere o hash. Sem digest na API o download é aceito só se
@@ -84,9 +95,17 @@ pub async fn download(
match asset.digest.as_deref() {
Some(expected) => integrity::verify_sha256(&bytes, expected, &asset.name)?,
None if allow_unverified => {
- tracing::warn!("[tools] {} veio sem digest; aceito sem verificacao", asset.name)
+ tracing::warn!(
+ "[tools] {} veio sem digest; aceito sem verificacao",
+ asset.name
+ )
+ }
+ None => {
+ return Err(anyhow!(
+ "{} veio sem digest da API do GitHub; download descartado",
+ asset.name
+ ))
}
- None => return Err(anyhow!("{} veio sem digest da API do GitHub; download descartado", asset.name)),
}
Ok(bytes)
}
@@ -98,7 +117,9 @@ pub fn unpack(data: &[u8], name: &str, dest: &Path) -> anyhow::Result<()> {
.map_err(|e| anyhow!("zip invalido: {}", e))?;
for i in 0..archive.len() {
let mut file = archive.by_index(i)?;
- let Some(rel) = file.enclosed_name() else { continue };
+ let Some(rel) = file.enclosed_name() else {
+ continue;
+ };
let out = dest.join(rel);
if file.is_dir() {
std::fs::create_dir_all(&out)?;
@@ -115,12 +136,16 @@ pub fn unpack(data: &[u8], name: &str, dest: &Path) -> anyhow::Result<()> {
let decoder = flate2::read::GzDecoder::new(std::io::Cursor::new(data));
let mut archive = tar::Archive::new(decoder);
archive.set_preserve_permissions(true);
- archive.unpack(dest).map_err(|e| anyhow!("tar.gz invalido: {}", e))
+ archive
+ .unpack(dest)
+ .map_err(|e| anyhow!("tar.gz invalido: {}", e))
} else if name.ends_with(".tar.xz") {
let decoder = xz2::read::XzDecoder::new(std::io::Cursor::new(data));
let mut archive = tar::Archive::new(decoder);
archive.set_preserve_permissions(true);
- archive.unpack(dest).map_err(|e| anyhow!("tar.xz invalido: {}", e))
+ archive
+ .unpack(dest)
+ .map_err(|e| anyhow!("tar.xz invalido: {}", e))
} else {
Err(anyhow!("formato de pacote desconhecido: {}", name))
}
@@ -131,7 +156,9 @@ pub fn unpack(data: &[u8], name: &str, dest: &Path) -> anyhow::Result<()> {
pub fn find_file(root: &Path, file_name: &str) -> Option<PathBuf> {
let mut stack = vec![root.to_path_buf()];
while let Some(dir) = stack.pop() {
- let Ok(rd) = std::fs::read_dir(&dir) else { continue };
+ let Ok(rd) = std::fs::read_dir(&dir) else {
+ continue;
+ };
for entry in rd.flatten() {
let p = entry.path();
if p.is_dir() {
@@ -164,7 +191,10 @@ pub fn swap_dir(staging: &Path, dir: &Path) -> anyhow::Result<()> {
if old.exists() {
let _ = std::fs::rename(&old, dir);
}
- return Err(anyhow!("nao foi possivel mover a instalacao para o lugar: {}", e));
+ return Err(anyhow!(
+ "nao foi possivel mover a instalacao para o lugar: {}",
+ e
+ ));
}
let _ = std::fs::remove_dir_all(&old);
Ok(())
diff --git a/src-tauri/omniget-core/src/core/tools/humanize.rs b/src-tauri/omniget-core/src/core/tools/humanize.rs
index 52217b08..c8d7745a 100644
--- a/src-tauri/omniget-core/src/core/tools/humanize.rs
+++ b/src-tauri/omniget-core/src/core/tools/humanize.rs
@@ -57,7 +57,11 @@ fn strip_fence(s: &str) -> &str {
if let Some(end) = inner.rfind("```") {
let body = &inner[..end];
// pula o identificador de linguagem na primeira linha, se houver
- return body.split_once('\n').map(|(_, rest)| rest).unwrap_or(body).trim();
+ return body
+ .split_once('\n')
+ .map(|(_, rest)| rest)
+ .unwrap_or(body)
+ .trim();
}
}
t
diff --git a/src-tauri/omniget-core/src/core/tools/image_resize.rs b/src-tauri/omniget-core/src/core/tools/image_resize.rs
index 79bf377c..dc7db352 100644
--- a/src-tauri/omniget-core/src/core/tools/image_resize.rs
+++ b/src-tauri/omniget-core/src/core/tools/image_resize.rs
@@ -38,7 +38,11 @@ pub struct ResizeResult {
pub fn scale_filter(mode: &str, v: u32, v2: u32) -> String {
match mode {
"height" => format!("scale=-2:{}", v.max(1)),
- "fit" => format!("scale='min({w},iw)':'min({h},ih)':force_original_aspect_ratio=decrease", w = v.max(1), h = v2.max(1)),
+ "fit" => format!(
+ "scale='min({w},iw)':'min({h},ih)':force_original_aspect_ratio=decrease",
+ w = v.max(1),
+ h = v2.max(1)
+ ),
"percent" => format!("scale=iw*{p}/100:ih*{p}/100", p = v.max(1)),
_ => format!("scale={}:-2", v.max(1)),
}
@@ -53,10 +57,19 @@ pub async fn run(opts: ResizeOptions, progress: super::ProgressFn) -> anyhow::Re
// ffmpeg: -q:v 2 (melhor) … 31 (pior) para JPEG; mapeia 100..0 → 2..31
let qv = (2.0 + (100.0 - opts.quality.min(100) as f64) * 0.29).round() as u32;
for (i, input) in opts.inputs.iter().enumerate() {
- super::report(&progress, "resize", "progress", i as u64, Some(total), Some(input.clone()));
+ super::report(
+ &progress,
+ "resize",
+ "progress",
+ i as u64,
+ Some(total),
+ Some(input.clone()),
+ );
let inp = Path::new(input);
let ext = if opts.format.trim().is_empty() {
- inp.extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_else(|| "jpg".into())
+ inp.extension()
+ .map(|e| e.to_string_lossy().to_lowercase())
+ .unwrap_or_else(|| "jpg".into())
} else {
opts.format.trim().to_lowercase()
};
@@ -66,11 +79,20 @@ pub async fn run(opts: ResizeOptions, progress: super::ProgressFn) -> anyhow::Re
PathBuf::from(opts.output_dir.trim())
};
std::fs::create_dir_all(&out_dir)?;
- let stem = inp.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "imagem".into());
- let suffix = if opts.suffix.is_empty() { "-resized" } else { opts.suffix.as_str() };
+ let stem = inp
+ .file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| "imagem".into());
+ let suffix = if opts.suffix.is_empty() {
+ "-resized"
+ } else {
+ opts.suffix.as_str()
+ };
let out = out_dir.join(format!("{}{}.{}", stem, suffix, ext));
let mut cmd = crate::core::process::command(&ffmpeg);
- cmd.args(["-y", "-hide_banner", "-loglevel", "error", "-i"]).arg(inp).args(["-vf", &filter]);
+ cmd.args(["-y", "-hide_banner", "-loglevel", "error", "-i"])
+ .arg(inp)
+ .args(["-vf", &filter]);
if ext == "jpg" || ext == "jpeg" {
cmd.args(["-q:v", &qv.to_string()]);
} else if ext == "webp" {
@@ -80,7 +102,11 @@ pub async fn run(opts: ResizeOptions, progress: super::ProgressFn) -> anyhow::Re
match cmd.output().await {
Ok(o) if o.status.success() => outputs.push(out.to_string_lossy().to_string()),
Ok(o) => {
- tracing::warn!("[resize] {}: {}", input, String::from_utf8_lossy(&o.stderr).trim());
+ tracing::warn!(
+ "[resize] {}: {}",
+ input,
+ String::from_utf8_lossy(&o.stderr).trim()
+ );
failed.push(input.clone());
}
Err(e) => return Err(anyhow!("ffmpeg nao iniciou: {}", e)),
diff --git a/src-tauri/omniget-core/src/core/tools/instagram/analytics.rs b/src-tauri/omniget-core/src/core/tools/instagram/analytics.rs
index e4b832db..4d6bbcda 100644
--- a/src-tauri/omniget-core/src/core/tools/instagram/analytics.rs
+++ b/src-tauri/omniget-core/src/core/tools/instagram/analytics.rs
@@ -76,7 +76,11 @@ fn top_counts(items: impl Iterator<Item = String>, n: usize) -> Vec<(String, u32
pub fn compute(user: UserInfo, posts: &[MediaItem]) -> ProfileStats {
let n = posts.len();
- let mut st = ProfileStats { user, posts_analyzed: n, ..Default::default() };
+ let mut st = ProfileStats {
+ user,
+ posts_analyzed: n,
+ ..Default::default()
+ };
if n == 0 {
return st;
}
@@ -86,7 +90,11 @@ pub fn compute(user: UserInfo, posts: &[MediaItem]) -> ProfileStats {
let videos: Vec<&MediaItem> = posts.iter().filter(|p| p.play_count > 0).collect();
st.avg_likes = f(total_likes) / n as f64;
st.avg_comments = f(total_comments) / n as f64;
- st.avg_plays = if videos.is_empty() { 0.0 } else { videos.iter().map(|p| f(p.play_count)).sum::<f64>() / videos.len() as f64 };
+ st.avg_plays = if videos.is_empty() {
+ 0.0
+ } else {
+ videos.iter().map(|p| f(p.play_count)).sum::<f64>() / videos.len() as f64
+ };
let mut likes: Vec<u64> = posts.iter().map(|p| p.like_count).collect();
likes.sort_unstable();
st.median_likes = likes[n / 2];
@@ -99,11 +107,17 @@ pub fn compute(user: UserInfo, posts: &[MediaItem]) -> ProfileStats {
if st.user.following_count > 0 {
st.follow_ratio = f(st.user.follower_count) / f(st.user.following_count);
}
- let count = |pred: &dyn Fn(&MediaItem) -> bool| posts.iter().filter(|p| pred(p)).count() as f64 / n as f64 * 100.0;
+ let count = |pred: &dyn Fn(&MediaItem) -> bool| {
+ posts.iter().filter(|p| pred(p)).count() as f64 / n as f64 * 100.0
+ };
st.share_carousel = count(&|p| p.media_type == 8);
st.share_video = count(&|p| p.media_type == 2);
st.share_photo = count(&|p| p.media_type == 1);
- st.avg_caption_len = posts.iter().map(|p| p.caption.chars().count() as f64).sum::<f64>() / n as f64;
+ st.avg_caption_len = posts
+ .iter()
+ .map(|p| p.caption.chars().count() as f64)
+ .sum::<f64>()
+ / n as f64;
st.avg_hashtags = posts.iter().map(|p| p.hashtags.len() as f64).sum::<f64>() / n as f64;
st.top_hashtags = top_counts(posts.iter().flat_map(|p| p.hashtags.iter().cloned()), 15);
st.top_mentions = top_counts(posts.iter().flat_map(|p| p.mentions.iter().cloned()), 10);
@@ -121,15 +135,31 @@ pub fn compute(user: UserInfo, posts: &[MediaItem]) -> ProfileStats {
}
#[allow(clippy::needless_range_loop)]
for i in 0..7 {
- st.weekday_engagement[i] = if st.weekday_counts[i] > 0 { eng_sum[i] / st.weekday_counts[i] as f64 } else { 0.0 };
+ st.weekday_engagement[i] = if st.weekday_counts[i] > 0 {
+ eng_sum[i] / st.weekday_counts[i] as f64
+ } else {
+ 0.0
+ };
}
- st.best_weekday = (0..7).max_by(|a, b| st.weekday_engagement[*a].partial_cmp(&st.weekday_engagement[*b]).unwrap()).unwrap_or(0) as u8;
+ st.best_weekday = (0..7)
+ .max_by(|a, b| {
+ st.weekday_engagement[*a]
+ .partial_cmp(&st.weekday_engagement[*b])
+ .unwrap()
+ })
+ .unwrap_or(0) as u8;
st.best_hour = (0..24).max_by_key(|h| st.hour_counts[*h]).unwrap_or(0) as u8;
- let (min_t, max_t) = posts.iter().fold((i64::MAX, 0i64), |(lo, hi), p| (lo.min(p.taken_at), hi.max(p.taken_at)));
+ let (min_t, max_t) = posts.iter().fold((i64::MAX, 0i64), |(lo, hi), p| {
+ (lo.min(p.taken_at), hi.max(p.taken_at))
+ });
st.first_post_at = min_t;
st.last_post_at = max_t;
st.span_days = ((max_t - min_t).max(0) as f64) / 86400.0;
- st.posts_per_week = if st.span_days >= 1.0 { n as f64 / (st.span_days / 7.0) } else { n as f64 };
+ st.posts_per_week = if st.span_days >= 1.0 {
+ n as f64 / (st.span_days / 7.0)
+ } else {
+ n as f64
+ };
let mut ranked: Vec<&MediaItem> = posts.iter().collect();
ranked.sort_by_key(|p| std::cmp::Reverse(p.like_count + p.comment_count));
st.top_posts = ranked
@@ -163,7 +193,15 @@ pub struct GhostReport {
}
/// Seguidores que não curtiram nem comentaram nenhum dos últimos N posts.
-pub async fn ghosts(client: &IgClient, followers: Vec<MiniUser>, posts: &[MediaItem], comment_pages: usize, flag: &AtomicBool, progress: &super::super::ProgressFn, job: &str) -> Result<GhostReport, super::IgError> {
+pub async fn ghosts(
+ client: &IgClient,
+ followers: Vec<MiniUser>,
+ posts: &[MediaItem],
+ comment_pages: usize,
+ flag: &AtomicBool,
+ progress: &super::super::ProgressFn,
+ job: &str,
+) -> Result<GhostReport, super::IgError> {
let id = format!("ig:{}", job);
let mut engagement: HashMap<String, u32> = HashMap::new();
let total = posts.len() as u64;
@@ -171,7 +209,14 @@ pub async fn ghosts(client: &IgClient, followers: Vec<MiniUser>, posts: &[MediaI
if super::cancelled(flag) {
break;
}
- super::super::report(progress, &id, "likers", i as u64, Some(total), Some(post.code.clone()));
+ super::super::report(
+ progress,
+ &id,
+ "likers",
+ i as u64,
+ Some(total),
+ Some(post.code.clone()),
+ );
if let Ok((_, users)) = super::social::likers(client, &post.pk).await {
for u in users {
*engagement.entry(u.pk).or_default() += 1;
@@ -180,7 +225,9 @@ pub async fn ghosts(client: &IgClient, followers: Vec<MiniUser>, posts: &[MediaI
client.pause().await;
if comment_pages > 0 {
let limit = comment_pages * 20;
- if let Ok(cs) = super::social::comments(client, &post.pk, limit, flag, progress, job).await {
+ if let Ok(cs) =
+ super::social::comments(client, &post.pk, limit, flag, progress, job).await
+ {
for c in cs {
*engagement.entry(c.user.pk).or_default() += 1;
}
@@ -189,12 +236,25 @@ pub async fn ghosts(client: &IgClient, followers: Vec<MiniUser>, posts: &[MediaI
}
}
let engaged_set: HashSet<&String> = engagement.keys().collect();
- let ghosts: Vec<MiniUser> = followers.iter().filter(|f| !engaged_set.contains(&f.pk)).cloned().collect();
- let mut top_fans: Vec<(MiniUser, u32)> = followers.iter().filter_map(|f| engagement.get(&f.pk).map(|n| (f.clone(), *n))).collect();
+ let ghosts: Vec<MiniUser> = followers
+ .iter()
+ .filter(|f| !engaged_set.contains(&f.pk))
+ .cloned()
+ .collect();
+ let mut top_fans: Vec<(MiniUser, u32)> = followers
+ .iter()
+ .filter_map(|f| engagement.get(&f.pk).map(|n| (f.clone(), *n)))
+ .collect();
top_fans.sort_by_key(|b| std::cmp::Reverse(b.1));
top_fans.truncate(30);
super::super::report(progress, &id, "done", total, Some(total), None);
- Ok(GhostReport { posts_checked: posts.len(), followers_total: followers.len(), engaged: followers.len() - ghosts.len(), ghosts, top_fans })
+ Ok(GhostReport {
+ posts_checked: posts.len(),
+ followers_total: followers.len(),
+ engaged: followers.len() - ghosts.len(),
+ ghosts,
+ top_fans,
+ })
}
// ── Export oficial ───────────────────────────────────────────────────────
@@ -238,11 +298,21 @@ fn collect_users(v: &Value, out: &mut Vec<ExportUser>) {
for e in list {
let value = e.get("value").and_then(|x| x.as_str()).unwrap_or("");
let href = e.get("href").and_then(|x| x.as_str()).unwrap_or("");
- let username = if !value.is_empty() { value } else if !title.is_empty() { title } else { href.trim_end_matches('/').rsplit('/').next().unwrap_or("") };
+ let username = if !value.is_empty() {
+ value
+ } else if !title.is_empty() {
+ title
+ } else {
+ href.trim_end_matches('/').rsplit('/').next().unwrap_or("")
+ };
if username.is_empty() {
continue;
}
- out.push(ExportUser { username: username.to_lowercase(), href: href.to_string(), timestamp: e.get("timestamp").and_then(|x| x.as_i64()).unwrap_or(0) });
+ out.push(ExportUser {
+ username: username.to_lowercase(),
+ href: href.to_string(),
+ timestamp: e.get("timestamp").and_then(|x| x.as_i64()).unwrap_or(0),
+ });
}
} else {
o.values().for_each(|x| collect_users(x, out));
@@ -256,7 +326,19 @@ fn read_export_files(path: &Path) -> anyhow::Result<Vec<(String, Vec<u8>)>> {
let mut files = Vec::new();
let wanted = |name: &str| {
let n = name.to_lowercase();
- n.ends_with(".json") && (n.contains("followers_and_following") || n.contains("connections/") || n.starts_with("followers") || n.contains("following") || n.contains("close_friends") || n.contains("pending_follow") || n.contains("blocked") || n.contains("unfollowed") || n.contains("follow_requests") || n.contains("restricted") || n.contains("hide_story") || n.contains("removed_suggestions"))
+ n.ends_with(".json")
+ && (n.contains("followers_and_following")
+ || n.contains("connections/")
+ || n.starts_with("followers")
+ || n.contains("following")
+ || n.contains("close_friends")
+ || n.contains("pending_follow")
+ || n.contains("blocked")
+ || n.contains("unfollowed")
+ || n.contains("follow_requests")
+ || n.contains("restricted")
+ || n.contains("hide_story")
+ || n.contains("removed_suggestions"))
};
if path.is_dir() {
fn walk(dir: &Path, out: &mut Vec<(String, Vec<u8>)>, wanted: &dyn Fn(&str) -> bool) {
@@ -297,10 +379,20 @@ fn read_export_files(path: &Path) -> anyhow::Result<Vec<(String, Vec<u8>)>> {
pub fn analyze_export(path: &str) -> anyhow::Result<ExportReport> {
let files = read_export_files(Path::new(path))?;
- let mut rep = ExportReport { source: path.to_string(), ..Default::default() };
+ let mut rep = ExportReport {
+ source: path.to_string(),
+ ..Default::default()
+ };
for (name, bytes) in &files {
- let Ok(v) = serde_json::from_slice::<Value>(bytes) else { continue };
- let base = name.replace('\\', "/").rsplit('/').next().unwrap_or("").to_lowercase();
+ let Ok(v) = serde_json::from_slice::<Value>(bytes) else {
+ continue;
+ };
+ let base = name
+ .replace('\\', "/")
+ .rsplit('/')
+ .next()
+ .unwrap_or("")
+ .to_lowercase();
let mut users = Vec::new();
collect_users(&v, &mut users);
rep.files_found.push(base.clone());
@@ -335,9 +427,23 @@ pub fn analyze_export(path: &str) -> anyhow::Result<ExportReport> {
}
let fset: HashSet<&str> = rep.followers.iter().map(|u| u.username.as_str()).collect();
let gset: HashSet<&str> = rep.following.iter().map(|u| u.username.as_str()).collect();
- rep.not_following_back = rep.following.iter().filter(|u| !fset.contains(u.username.as_str())).cloned().collect();
- rep.fans = rep.followers.iter().filter(|u| !gset.contains(u.username.as_str())).cloned().collect();
- rep.mutuals = rep.following.iter().filter(|u| fset.contains(u.username.as_str())).count();
+ rep.not_following_back = rep
+ .following
+ .iter()
+ .filter(|u| !fset.contains(u.username.as_str()))
+ .cloned()
+ .collect();
+ rep.fans = rep
+ .followers
+ .iter()
+ .filter(|u| !gset.contains(u.username.as_str()))
+ .cloned()
+ .collect();
+ rep.mutuals = rep
+ .following
+ .iter()
+ .filter(|u| fset.contains(u.username.as_str()))
+ .count();
let mut by_month: HashMap<String, u32> = HashMap::new();
for u in &rep.followers {
if let Some(dt) = chrono::DateTime::from_timestamp(u.timestamp, 0) {
@@ -347,8 +453,10 @@ pub fn analyze_export(path: &str) -> anyhow::Result<ExportReport> {
let mut months: Vec<(String, u32)> = by_month.into_iter().collect();
months.sort();
rep.followers_by_month = months;
- rep.followers.sort_by_key(|u| std::cmp::Reverse(u.timestamp));
- rep.following.sort_by_key(|u| std::cmp::Reverse(u.timestamp));
+ rep.followers
+ .sort_by_key(|u| std::cmp::Reverse(u.timestamp));
+ rep.following
+ .sort_by_key(|u| std::cmp::Reverse(u.timestamp));
Ok(rep)
}
@@ -365,17 +473,46 @@ mod tests {
let mut g = Vec::new();
collect_users(&following, &mut g);
assert_eq!(f.len(), 1);
- assert_eq!(g.iter().map(|u| u.username.as_str()).collect::<Vec<_>>(), vec!["bob", "alice"]);
+ assert_eq!(
+ g.iter().map(|u| u.username.as_str()).collect::<Vec<_>>(),
+ vec!["bob", "alice"]
+ );
}
#[test]
fn stats_basics() {
let mk = |likes: u64, ts: i64, mt: u8| MediaItem {
- pk: String::new(), code: String::new(), media_type: mt, product_type: String::new(), taken_at: ts, expiring_at: None, caption: "#a #b".into(), like_count: likes, comment_count: 1, play_count: 0,
- owner_id: String::new(), username: String::new(), full_name: String::new(), thumbnail: String::new(), files: vec![], duration: 0.0, location: None, url: String::new(), width: 0, height: 0,
- hashtags: vec!["a".into(), "b".into()], mentions: vec![], is_paid_partnership: false, coauthors: vec![], title: None,
+ pk: String::new(),
+ code: String::new(),
+ media_type: mt,
+ product_type: String::new(),
+ taken_at: ts,
+ expiring_at: None,
+ caption: "#a #b".into(),
+ like_count: likes,
+ comment_count: 1,
+ play_count: 0,
+ owner_id: String::new(),
+ username: String::new(),
+ full_name: String::new(),
+ thumbnail: String::new(),
+ files: vec![],
+ duration: 0.0,
+ location: None,
+ url: String::new(),
+ width: 0,
+ height: 0,
+ hashtags: vec!["a".into(), "b".into()],
+ mentions: vec![],
+ is_paid_partnership: false,
+ coauthors: vec![],
+ title: None,
+ };
+ let user = UserInfo {
+ follower_count: 1000,
+ following_count: 100,
+ ..Default::default()
};
- let user = UserInfo { follower_count: 1000, following_count: 100, ..Default::default() };
let st = compute(user, &[mk(100, 0, 1), mk(200, 7 * 86400, 8)]);
assert_eq!(st.avg_likes, 150.0);
assert!((st.engagement_rate - 15.1).abs() < 0.01);
diff --git a/src-tauri/omniget-core/src/core/tools/instagram/follow.rs b/src-tauri/omniget-core/src/core/tools/instagram/follow.rs
index 6a8aabe9..f0b01fd5 100644
--- a/src-tauri/omniget-core/src/core/tools/instagram/follow.rs
+++ b/src-tauri/omniget-core/src/core/tools/instagram/follow.rs
@@ -27,7 +27,11 @@ impl MiniUser {
MiniUser {
pk: {
let p = s(v, "pk");
- if p.is_empty() { s(v, "id") } else { p }
+ if p.is_empty() {
+ s(v, "id")
+ } else {
+ p
+ }
},
username: s(v, "username"),
full_name: s(v, "full_name"),
@@ -38,23 +42,55 @@ impl MiniUser {
}
}
-async fn friendship_list(client: &IgClient, user_id: &str, which: &str, limit: usize, flag: &AtomicBool, progress: &super::super::ProgressFn, job: &str) -> Result<Vec<MiniUser>, IgError> {
+async fn friendship_list(
+ client: &IgClient,
+ user_id: &str,
+ which: &str,
+ limit: usize,
+ flag: &AtomicBool,
+ progress: &super::super::ProgressFn,
+ job: &str,
+) -> Result<Vec<MiniUser>, IgError> {
let mut out = Vec::new();
let mut max_id: Option<String> = None;
let id = format!("ig:{}", job);
loop {
- let mut q = vec![("count", "50".to_string()), ("search_surface", "follow_list_page".to_string())];
+ let mut q = vec![
+ ("count", "50".to_string()),
+ ("search_surface", "follow_list_page".to_string()),
+ ];
if let Some(m) = &max_id {
q.push(("max_id", m.clone()));
}
- let json = client.get_json(&format!("/api/v1/friendships/{}/{}/", user_id, which), &q).await?;
- let users = json.get("users").and_then(|u| u.as_array()).cloned().unwrap_or_default();
+ let json = client
+ .get_json(&format!("/api/v1/friendships/{}/{}/", user_id, which), &q)
+ .await?;
+ let users = json
+ .get("users")
+ .and_then(|u| u.as_array())
+ .cloned()
+ .unwrap_or_default();
for us in &users {
out.push(MiniUser::from_value(us));
}
- super::super::report(progress, &id, which, out.len() as u64, if limit > 0 { Some(limit as u64) } else { None }, None);
- max_id = json.get("next_max_id").and_then(|m| match m { Value::String(x) => Some(x.clone()), Value::Number(n) => Some(n.to_string()), _ => None });
- if users.is_empty() || max_id.is_none() || (limit > 0 && out.len() >= limit) || super::cancelled(flag) {
+ super::super::report(
+ progress,
+ &id,
+ which,
+ out.len() as u64,
+ if limit > 0 { Some(limit as u64) } else { None },
+ None,
+ );
+ max_id = json.get("next_max_id").and_then(|m| match m {
+ Value::String(x) => Some(x.clone()),
+ Value::Number(n) => Some(n.to_string()),
+ _ => None,
+ });
+ if users.is_empty()
+ || max_id.is_none()
+ || (limit > 0 && out.len() >= limit)
+ || super::cancelled(flag)
+ {
break;
}
client.pause().await;
@@ -62,11 +98,25 @@ async fn friendship_list(client: &IgClient, user_id: &str, which: &str, limit: u
Ok(out)
}
-pub async fn followers(client: &IgClient, user_id: &str, limit: usize, flag: &AtomicBool, progress: &super::super::ProgressFn, job: &str) -> Result<Vec<MiniUser>, IgError> {
+pub async fn followers(
+ client: &IgClient,
+ user_id: &str,
+ limit: usize,
+ flag: &AtomicBool,
+ progress: &super::super::ProgressFn,
+ job: &str,
+) -> Result<Vec<MiniUser>, IgError> {
friendship_list(client, user_id, "followers", limit, flag, progress, job).await
}
-pub async fn following(client: &IgClient, user_id: &str, limit: usize, flag: &AtomicBool, progress: &super::super::ProgressFn, job: &str) -> Result<Vec<MiniUser>, IgError> {
+pub async fn following(
+ client: &IgClient,
+ user_id: &str,
+ limit: usize,
+ flag: &AtomicBool,
+ progress: &super::super::ProgressFn,
+ job: &str,
+) -> Result<Vec<MiniUser>, IgError> {
friendship_list(client, user_id, "following", limit, flag, progress, job).await
}
@@ -84,7 +134,11 @@ pub struct FollowAnalysis {
pub following: Vec<MiniUser>,
}
-pub fn analyze(followers: Vec<MiniUser>, following: Vec<MiniUser>, whitelist: &HashSet<String>) -> FollowAnalysis {
+pub fn analyze(
+ followers: Vec<MiniUser>,
+ following: Vec<MiniUser>,
+ whitelist: &HashSet<String>,
+) -> FollowAnalysis {
let fset: HashSet<&str> = followers.iter().map(|u| u.pk.as_str()).collect();
let gset: HashSet<&str> = following.iter().map(|u| u.pk.as_str()).collect();
let mut whitelisted = 0;
@@ -100,27 +154,63 @@ pub fn analyze(followers: Vec<MiniUser>, following: Vec<MiniUser>, whitelist: &H
})
.cloned()
.collect();
- let fans = followers.iter().filter(|u| !gset.contains(u.pk.as_str())).cloned().collect();
- let mutuals = following.iter().filter(|u| fset.contains(u.pk.as_str())).cloned().collect();
- FollowAnalysis { followers_count: followers.len(), following_count: following.len(), not_following_back, fans, mutuals, whitelisted, followers, following }
+ let fans = followers
+ .iter()
+ .filter(|u| !gset.contains(u.pk.as_str()))
+ .cloned()
+ .collect();
+ let mutuals = following
+ .iter()
+ .filter(|u| fset.contains(u.pk.as_str()))
+ .cloned()
+ .collect();
+ FollowAnalysis {
+ followers_count: followers.len(),
+ following_count: following.len(),
+ not_following_back,
+ fans,
+ mutuals,
+ whitelisted,
+ followers,
+ following,
+ }
}
// ── Ações ────────────────────────────────────────────────────────────────
pub async fn unfollow(client: &IgClient, user_id: &str) -> Result<(), IgError> {
- let r = client.post_form(&format!("/api/v1/web/friendships/{}/unfollow/", user_id), &[]).await;
+ let r = client
+ .post_form(
+ &format!("/api/v1/web/friendships/{}/unfollow/", user_id),
+ &[],
+ )
+ .await;
match r {
Ok(_) => Ok(()),
- Err(IgError::NotFound(_)) | Err(IgError::Other(_)) => client.post_form(&format!("/web/friendships/{}/unfollow/", user_id), &[]).await.map(|_| ()),
+ Err(IgError::NotFound(_)) | Err(IgError::Other(_)) => client
+ .post_form(&format!("/web/friendships/{}/unfollow/", user_id), &[])
+ .await
+ .map(|_| ()),
Err(e) => Err(e),
}
}
pub async fn remove_follower(client: &IgClient, user_id: &str) -> Result<(), IgError> {
- let r = client.post_form(&format!("/api/v1/web/friendships/{}/remove_follower/", user_id), &[]).await;
+ let r = client
+ .post_form(
+ &format!("/api/v1/web/friendships/{}/remove_follower/", user_id),
+ &[],
+ )
+ .await;
match r {
Ok(_) => Ok(()),
- Err(IgError::NotFound(_)) | Err(IgError::Other(_)) => client.post_form(&format!("/web/friendships/{}/remove_follower/", user_id), &[]).await.map(|_| ()),
+ Err(IgError::NotFound(_)) | Err(IgError::Other(_)) => client
+ .post_form(
+ &format!("/web/friendships/{}/remove_follower/", user_id),
+ &[],
+ )
+ .await
+ .map(|_| ()),
Err(e) => Err(e),
}
}
@@ -138,7 +228,13 @@ pub struct Pacing {
impl Default for Pacing {
fn default() -> Self {
- Pacing { delay_min_ms: 6000, delay_max_ms: 14000, pause_every: 5, pause_ms: 300_000, daily_cap: 100 }
+ Pacing {
+ delay_min_ms: 6000,
+ delay_max_ms: 14000,
+ pause_every: 5,
+ pause_ms: 300_000,
+ daily_cap: 100,
+ }
}
}
@@ -154,14 +250,21 @@ fn counter_path(owner: &str) -> std::path::PathBuf {
pub fn actions_today(owner: &str) -> u32 {
let c: DailyCounter = super::read_json(&counter_path(owner));
- if c.day == chrono::Local::now().format("%Y-%m-%d").to_string() { c.count } else { 0 }
+ if c.day == chrono::Local::now().format("%Y-%m-%d").to_string() {
+ c.count
+ } else {
+ 0
+ }
}
fn bump_today(owner: &str) -> u32 {
let today = chrono::Local::now().format("%Y-%m-%d").to_string();
let mut c: DailyCounter = super::read_json(&counter_path(owner));
if c.day != today {
- c = DailyCounter { day: today, count: 0 };
+ c = DailyCounter {
+ day: today,
+ count: 0,
+ };
}
c.count += 1;
let _ = super::write_json(&counter_path(owner), &c);
@@ -181,7 +284,15 @@ pub struct ActionReport {
/// Executa `unfollow` ou `remove_follower` numa lista com ritmo humano.
/// Para em 429 (espera 10 min e tenta mais uma vez), em bloqueio, em
/// sessão caída, no teto diário e quando o job é cancelado.
-pub async fn run_actions(client: &IgClient, action: &str, users: Vec<MiniUser>, pacing: &Pacing, flag: &AtomicBool, progress: &super::super::ProgressFn, job: &str) -> ActionReport {
+pub async fn run_actions(
+ client: &IgClient,
+ action: &str,
+ users: Vec<MiniUser>,
+ pacing: &Pacing,
+ flag: &AtomicBool,
+ progress: &super::super::ProgressFn,
+ job: &str,
+) -> ActionReport {
let owner = client.session.user_id.clone();
let id = format!("ig:{}", job);
let total = users.len() as u64;
@@ -196,15 +307,34 @@ pub async fn run_actions(client: &IgClient, action: &str, users: Vec<MiniUser>,
stopped = "cancelled".into();
let mut rest = vec![user];
rest.extend(iter);
- return ActionReport { actions_today: actions_today(&owner), done, failed, remaining: rest, stopped };
+ return ActionReport {
+ actions_today: actions_today(&owner),
+ done,
+ failed,
+ remaining: rest,
+ stopped,
+ };
}
if actions_today(&owner) >= pacing.daily_cap {
stopped = "daily_cap".into();
let mut rest = vec![user];
rest.extend(iter);
- return ActionReport { actions_today: actions_today(&owner), done, failed, remaining: rest, stopped };
+ return ActionReport {
+ actions_today: actions_today(&owner),
+ done,
+ failed,
+ remaining: rest,
+ stopped,
+ };
}
- super::super::report(progress, &id, action, done.len() as u64, Some(total), Some(format!("@{}", user.username)));
+ super::super::report(
+ progress,
+ &id,
+ action,
+ done.len() as u64,
+ Some(total),
+ Some(format!("@{}", user.username)),
+ );
let result = match action {
"remove_follower" => remove_follower(client, &user.pk).await,
_ => unfollow(client, &user.pk).await,
@@ -217,9 +347,20 @@ pub async fn run_actions(client: &IgClient, action: &str, users: Vec<MiniUser>,
}
Err(IgError::RateLimited) if !waited_429 => {
waited_429 = true;
- super::super::report(progress, &id, "waiting", done.len() as u64, Some(total), Some("429".into()));
+ super::super::report(
+ progress,
+ &id,
+ "waiting",
+ done.len() as u64,
+ Some(total),
+ Some("429".into()),
+ );
tokio::time::sleep(std::time::Duration::from_secs(600)).await;
- match if action == "remove_follower" { remove_follower(client, &user.pk).await } else { unfollow(client, &user.pk).await } {
+ match if action == "remove_follower" {
+ remove_follower(client, &user.pk).await
+ } else {
+ unfollow(client, &user.pk).await
+ } {
Ok(()) => {
bump_today(&owner);
done.push(user);
@@ -227,11 +368,22 @@ pub async fn run_actions(client: &IgClient, action: &str, users: Vec<MiniUser>,
Err(e) => {
stopped = "rate_limited".into();
failed.push((user, e.to_string()));
- return ActionReport { actions_today: actions_today(&owner), done, failed, remaining: iter.collect(), stopped };
+ return ActionReport {
+ actions_today: actions_today(&owner),
+ done,
+ failed,
+ remaining: iter.collect(),
+ stopped,
+ };
}
}
}
- Err(e @ (IgError::RateLimited | IgError::ActionBlocked | IgError::Checkpoint | IgError::LoginRequired)) => {
+ Err(
+ e @ (IgError::RateLimited
+ | IgError::ActionBlocked
+ | IgError::Checkpoint
+ | IgError::LoginRequired),
+ ) => {
stopped = match e {
IgError::RateLimited => "rate_limited",
IgError::ActionBlocked => "blocked",
@@ -240,19 +392,38 @@ pub async fn run_actions(client: &IgClient, action: &str, users: Vec<MiniUser>,
}
.into();
failed.push((user, e.to_string()));
- return ActionReport { actions_today: actions_today(&owner), done, failed, remaining: iter.collect(), stopped };
+ return ActionReport {
+ actions_today: actions_today(&owner),
+ done,
+ failed,
+ remaining: iter.collect(),
+ stopped,
+ };
}
Err(e) => failed.push((user, e.to_string())),
}
super::super::report(progress, &id, action, done.len() as u64, Some(total), None);
if pacing.pause_every > 0 && n > 0 && n.is_multiple_of(pacing.pause_every) {
- super::super::report(progress, &id, "pause", done.len() as u64, Some(total), Some(format!("{}s", pacing.pause_ms / 1000)));
+ super::super::report(
+ progress,
+ &id,
+ "pause",
+ done.len() as u64,
+ Some(total),
+ Some(format!("{}s", pacing.pause_ms / 1000)),
+ );
tokio::time::sleep(std::time::Duration::from_millis(pacing.pause_ms)).await;
} else {
super::sleep_jitter(pacing.delay_min_ms, pacing.delay_max_ms).await;
}
}
- ActionReport { actions_today: actions_today(&owner), done, failed, remaining: Vec::new(), stopped }
+ ActionReport {
+ actions_today: actions_today(&owner),
+ done,
+ failed,
+ remaining: Vec::new(),
+ stopped,
+ }
}
// ── Lista branca ─────────────────────────────────────────────────────────
@@ -275,7 +446,11 @@ pub fn whitelist_set(owner: &str, wl: &Whitelist) -> anyhow::Result<()> {
}
pub fn whitelist_keys(wl: &Whitelist) -> HashSet<String> {
- wl.users.iter().flat_map(|u| [u.pk.clone(), u.username.to_lowercase()]).filter(|k| !k.is_empty()).collect()
+ wl.users
+ .iter()
+ .flat_map(|u| [u.pk.clone(), u.username.to_lowercase()])
+ .filter(|k| !k.is_empty())
+ .collect()
}
// ── Snapshots ────────────────────────────────────────────────────────────
@@ -315,7 +490,12 @@ pub fn snapshots_list(owner: &str) -> Vec<SnapshotMeta> {
if p.extension().map(|x| x == "json").unwrap_or(false) {
let snap: Snapshot = super::read_json(&p);
if snap.taken_at > 0 {
- out.push(SnapshotMeta { file: p.to_string_lossy().to_string(), taken_at: snap.taken_at, followers: snap.followers.len(), following: snap.following.len() });
+ out.push(SnapshotMeta {
+ file: p.to_string_lossy().to_string(),
+ taken_at: snap.taken_at,
+ followers: snap.followers.len(),
+ following: snap.following.len(),
+ });
}
}
}
@@ -339,15 +519,28 @@ pub struct SnapshotDiff {
}
pub fn snapshot_diff(a: &Snapshot, b: &Snapshot) -> SnapshotDiff {
- let by_pk = |v: &[MiniUser]| -> HashMap<String, MiniUser> { v.iter().map(|u| (u.pk.clone(), u.clone())).collect() };
+ let by_pk = |v: &[MiniUser]| -> HashMap<String, MiniUser> {
+ v.iter().map(|u| (u.pk.clone(), u.clone())).collect()
+ };
let (fa, fb) = (by_pk(&a.followers), by_pk(&b.followers));
let (ga, gb) = (by_pk(&a.following), by_pk(&b.following));
let only = |x: &HashMap<String, MiniUser>, y: &HashMap<String, MiniUser>| -> Vec<MiniUser> {
- let mut v: Vec<MiniUser> = x.iter().filter(|(k, _)| !y.contains_key(*k)).map(|(_, u)| u.clone()).collect();
+ let mut v: Vec<MiniUser> = x
+ .iter()
+ .filter(|(k, _)| !y.contains_key(*k))
+ .map(|(_, u)| u.clone())
+ .collect();
v.sort_by(|p, q| p.username.cmp(&q.username));
v
};
- SnapshotDiff { from: a.taken_at, to: b.taken_at, new_followers: only(&fb, &fa), lost_followers: only(&fa, &fb), new_following: only(&gb, &ga), lost_following: only(&ga, &gb) }
+ SnapshotDiff {
+ from: a.taken_at,
+ to: b.taken_at,
+ new_followers: only(&fb, &fa),
+ lost_followers: only(&fa, &fb),
+ new_following: only(&gb, &ga),
+ lost_following: only(&ga, &gb),
+ }
}
#[cfg(test)]
@@ -355,7 +548,11 @@ mod tests {
use super::*;
fn u(pk: &str) -> MiniUser {
- MiniUser { pk: pk.into(), username: format!("u{}", pk), ..Default::default() }
+ MiniUser {
+ pk: pk.into(),
+ username: format!("u{}", pk),
+ ..Default::default()
+ }
}
#[test]
@@ -364,16 +561,38 @@ mod tests {
let following = vec![u("2"), u("3"), u("4")];
let wl: HashSet<String> = ["4".to_string()].into_iter().collect();
let a = analyze(followers, following, &wl);
- assert_eq!(a.not_following_back.iter().map(|x| x.pk.as_str()).collect::<Vec<_>>(), vec!["3"]);
- assert_eq!(a.fans.iter().map(|x| x.pk.as_str()).collect::<Vec<_>>(), vec!["1"]);
- assert_eq!(a.mutuals.iter().map(|x| x.pk.as_str()).collect::<Vec<_>>(), vec!["2"]);
+ assert_eq!(
+ a.not_following_back
+ .iter()
+ .map(|x| x.pk.as_str())
+ .collect::<Vec<_>>(),
+ vec!["3"]
+ );
+ assert_eq!(
+ a.fans.iter().map(|x| x.pk.as_str()).collect::<Vec<_>>(),
+ vec!["1"]
+ );
+ assert_eq!(
+ a.mutuals.iter().map(|x| x.pk.as_str()).collect::<Vec<_>>(),
+ vec!["2"]
+ );
assert_eq!(a.whitelisted, 1);
}
#[test]
fn diff_snapshots() {
- let a = Snapshot { taken_at: 1, owner: "me".into(), followers: vec![u("1"), u("2")], following: vec![u("9")] };
- let b = Snapshot { taken_at: 2, owner: "me".into(), followers: vec![u("2"), u("3")], following: vec![] };
+ let a = Snapshot {
+ taken_at: 1,
+ owner: "me".into(),
+ followers: vec![u("1"), u("2")],
+ following: vec![u("9")],
+ };
+ let b = Snapshot {
+ taken_at: 2,
+ owner: "me".into(),
+ followers: vec![u("2"), u("3")],
+ following: vec![],
+ };
let d = snapshot_diff(&a, &b);
assert_eq!(d.new_followers[0].pk, "3");
assert_eq!(d.lost_followers[0].pk, "1");
diff --git a/src-tauri/omniget-core/src/core/tools/instagram/media.rs b/src-tauri/omniget-core/src/core/tools/instagram/media.rs
index dcecd32e..bc9259ff 100644
--- a/src-tauri/omniget-core/src/core/tools/instagram/media.rs
+++ b/src-tauri/omniget-core/src/core/tools/instagram/media.rs
@@ -75,10 +75,24 @@ fn best_video(v: &Value) -> Option<(String, u64, u64)> {
fn file_of(v: &Value) -> Option<MediaFile> {
let image = best_candidate(v, "image_versions2");
if let Some((url, w, h)) = best_video(v) {
- return Some(MediaFile { url, kind: "video".into(), width: w, height: h, poster: image.map(|i| i.0), pk: s(v, "pk") });
+ return Some(MediaFile {
+ url,
+ kind: "video".into(),
+ width: w,
+ height: h,
+ poster: image.map(|i| i.0),
+ pk: s(v, "pk"),
+ });
}
let (url, w, h) = image?;
- Some(MediaFile { url, kind: "image".into(), width: w, height: h, poster: None, pk: s(v, "pk") })
+ Some(MediaFile {
+ url,
+ kind: "image".into(),
+ width: w,
+ height: h,
+ poster: None,
+ pk: s(v, "pk"),
+ })
}
fn tags(text: &str, prefix: char) -> Vec<String> {
@@ -86,7 +100,9 @@ fn tags(text: &str, prefix: char) -> Vec<String> {
for word in text.split(|c: char| c.is_whitespace() || c == ',' || c == '.' && false) {
let mut chars = word.chars();
if chars.next() == Some(prefix) {
- let tag: String = chars.take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '.').collect();
+ let tag: String = chars
+ .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '.')
+ .collect();
let tag = tag.trim_end_matches('.').to_lowercase();
if !tag.is_empty() && !out.contains(&tag) {
out.push(tag);
@@ -101,8 +117,16 @@ fn tags(text: &str, prefix: char) -> Vec<String> {
pub fn parse_item(v: &Value) -> Option<MediaItem> {
let user = v.get("user").cloned().unwrap_or(Value::Null);
let username = s(&user, "username");
- let caption = v.get("caption").and_then(|c| c.get("text")).and_then(|t| t.as_str()).unwrap_or("").to_string();
- let expiring_at = v.get("expiring_at").and_then(|x| x.as_i64()).filter(|x| *x > 0);
+ let caption = v
+ .get("caption")
+ .and_then(|c| c.get("text"))
+ .and_then(|t| t.as_str())
+ .unwrap_or("")
+ .to_string();
+ let expiring_at = v
+ .get("expiring_at")
+ .and_then(|x| x.as_i64())
+ .filter(|x| *x > 0);
let mut files = Vec::new();
if let Some(children) = v.get("carousel_media").and_then(|c| c.as_array()) {
for child in children {
@@ -118,10 +142,18 @@ pub fn parse_item(v: &Value) -> Option<MediaItem> {
}
let code = {
let c = s(v, "code");
- if c.is_empty() { super::pk_to_shortcode(u(v, "pk")) } else { c }
+ if c.is_empty() {
+ super::pk_to_shortcode(u(v, "pk"))
+ } else {
+ c
+ }
};
let pk = s(v, "pk");
- let product_type = if expiring_at.is_some() || v.get("expiring_at").is_some() { "story".to_string() } else { s(v, "product_type") };
+ let product_type = if expiring_at.is_some() || v.get("expiring_at").is_some() {
+ "story".to_string()
+ } else {
+ s(v, "product_type")
+ };
let url = if product_type == "story" {
format!("{}/stories/{}/{}/", super::BASE, username, pk)
} else if product_type == "clips" {
@@ -129,11 +161,23 @@ pub fn parse_item(v: &Value) -> Option<MediaItem> {
} else {
format!("{}/p/{}/", super::BASE, code)
};
- let thumbnail = best_candidate(v, "image_versions2").map(|c| c.0).or_else(|| files.first().and_then(|f| f.poster.clone().or(Some(f.url.clone())))).unwrap_or_default();
+ let thumbnail = best_candidate(v, "image_versions2")
+ .map(|c| c.0)
+ .or_else(|| {
+ files
+ .first()
+ .and_then(|f| f.poster.clone().or(Some(f.url.clone())))
+ })
+ .unwrap_or_default();
let coauthors = v
.get("coauthor_producers")
.and_then(|c| c.as_array())
- .map(|a| a.iter().map(|x| s(x, "username")).filter(|x| !x.is_empty()).collect())
+ .map(|a| {
+ a.iter()
+ .map(|x| s(x, "username"))
+ .filter(|x| !x.is_empty())
+ .collect()
+ })
.unwrap_or_default();
Some(MediaItem {
media_type: u(v, "media_type") as u8,
@@ -142,13 +186,22 @@ pub fn parse_item(v: &Value) -> Option<MediaItem> {
expiring_at,
like_count: u(v, "like_count"),
comment_count: u(v, "comment_count"),
- play_count: u(v, "play_count").max(u(v, "view_count")).max(u(v, "ig_play_count")),
+ play_count: u(v, "play_count")
+ .max(u(v, "view_count"))
+ .max(u(v, "ig_play_count")),
owner_id: s(&user, "pk"),
full_name: s(&user, "full_name"),
username,
thumbnail,
- duration: v.get("video_duration").and_then(|x| x.as_f64()).unwrap_or(0.0),
- location: v.get("location").and_then(|l| l.get("name")).and_then(|n| n.as_str()).map(|x| x.to_string()),
+ duration: v
+ .get("video_duration")
+ .and_then(|x| x.as_f64())
+ .unwrap_or(0.0),
+ location: v
+ .get("location")
+ .and_then(|l| l.get("name"))
+ .and_then(|n| n.as_str())
+ .map(|x| x.to_string()),
width: u(v, "original_width"),
height: u(v, "original_height"),
hashtags: tags(&caption, '#'),
@@ -166,10 +219,18 @@ pub fn parse_item(v: &Value) -> Option<MediaItem> {
/// `GET /api/v1/media/{pk}/info/` — post, reel, carrossel ou IGTV.
pub async fn post_info(client: &IgClient, shortcode: &str) -> Result<MediaItem, IgError> {
- let pk = super::shortcode_to_pk(shortcode).ok_or_else(|| IgError::NotFound(format!("shortcode {}", shortcode)))?;
- let json = client.get_json(&format!("/api/v1/media/{}/info/", pk), &[]).await?;
- let item = json.get("items").and_then(|i| i.as_array()).and_then(|a| a.first()).ok_or_else(|| IgError::NotFound(format!("post {}", shortcode)))?;
- parse_item(item).ok_or_else(|| IgError::Other("o post nao tem midia que eu saiba baixar".into()))
+ let pk = super::shortcode_to_pk(shortcode)
+ .ok_or_else(|| IgError::NotFound(format!("shortcode {}", shortcode)))?;
+ let json = client
+ .get_json(&format!("/api/v1/media/{}/info/", pk), &[])
+ .await?;
+ let item = json
+ .get("items")
+ .and_then(|i| i.as_array())
+ .and_then(|a| a.first())
+ .ok_or_else(|| IgError::NotFound(format!("post {}", shortcode)))?;
+ parse_item(item)
+ .ok_or_else(|| IgError::Other("o post nao tem midia que eu saiba baixar".into()))
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -197,7 +258,10 @@ pub struct DownloadResult {
fn ext_of(url: &str, kind: &str) -> String {
let path = url.split('?').next().unwrap_or(url);
let ext = path.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
- if matches!(ext.as_str(), "jpg" | "jpeg" | "png" | "webp" | "heic" | "mp4" | "mov") {
+ if matches!(
+ ext.as_str(),
+ "jpg" | "jpeg" | "png" | "webp" | "heic" | "mp4" | "mov"
+ ) {
ext
} else if kind == "video" {
"mp4".into()
@@ -207,8 +271,14 @@ fn ext_of(url: &str, kind: &str) -> String {
}
pub fn base_name(item: &MediaItem) -> String {
- let date = chrono::DateTime::from_timestamp(item.taken_at, 0).map(|d| d.format("%Y-%m-%d").to_string()).unwrap_or_else(|| "sem-data".into());
- let user = if item.username.is_empty() { "instagram".to_string() } else { item.username.clone() };
+ let date = chrono::DateTime::from_timestamp(item.taken_at, 0)
+ .map(|d| d.format("%Y-%m-%d").to_string())
+ .unwrap_or_else(|| "sem-data".into());
+ let user = if item.username.is_empty() {
+ "instagram".to_string()
+ } else {
+ item.username.clone()
+ };
super::super::sanitize_name(&format!("{}_{}_{}", user, date, item.code))
}
@@ -216,16 +286,26 @@ async fn extract_audio(video: &Path, format: &str) -> anyhow::Result<PathBuf> {
let ffmpeg = crate::core::dependencies::ensure_ffmpeg().await?;
let out = video.with_extension(format);
let mut cmd = crate::core::process::command(&ffmpeg);
- cmd.args(["-y", "-hide_banner", "-loglevel", "error", "-i"]).arg(video).arg("-vn");
+ cmd.args(["-y", "-hide_banner", "-loglevel", "error", "-i"])
+ .arg(video)
+ .arg("-vn");
if format == "mp3" {
cmd.args(["-c:a", "libmp3lame", "-q:a", "2"]);
} else {
cmd.args(["-c:a", "copy"]);
}
cmd.arg(&out);
- let status = cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped()).output().await?;
+ let status = cmd
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::piped())
+ .output()
+ .await?;
if !status.status.success() {
- return Err(anyhow!("ffmpeg: {}", String::from_utf8_lossy(&status.stderr).trim()));
+ return Err(anyhow!(
+ "ffmpeg: {}",
+ String::from_utf8_lossy(&status.stderr).trim()
+ ));
}
Ok(out)
}
@@ -263,12 +343,32 @@ pub async fn download_items(
if super::cancelled(flag) {
break 'outer;
}
- let name = if multi { format!("{}_{:02}", base, idx + 1) } else { base.clone() };
+ let name = if multi {
+ format!("{}_{:02}", base, idx + 1)
+ } else {
+ base.clone()
+ };
let ext = ext_of(&file.url, &file.kind);
let target = folder.join(format!("{}.{}", name, ext));
let audio = !opts.audio_only.is_empty() && file.kind == "video";
- let final_target = if audio { target.with_extension(&opts.audio_only) } else { target.clone() };
- super::super::report(progress, &id, "download", done, Some(total), Some(final_target.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default()));
+ let final_target = if audio {
+ target.with_extension(&opts.audio_only)
+ } else {
+ target.clone()
+ };
+ super::super::report(
+ progress,
+ &id,
+ "download",
+ done,
+ Some(total),
+ Some(
+ final_target
+ .file_name()
+ .map(|n| n.to_string_lossy().to_string())
+ .unwrap_or_default(),
+ ),
+ );
if opts.skip_existing && final_target.exists() {
skipped += 1;
done += 1;
@@ -300,11 +400,19 @@ pub async fn download_items(
let _ = std::fs::write(folder.join(format!("{}.txt", base)), &item.caption);
}
if opts.metadata_json {
- let _ = std::fs::write(folder.join(format!("{}.json", base)), serde_json::to_string_pretty(item).unwrap_or_default());
+ let _ = std::fs::write(
+ folder.join(format!("{}.json", base)),
+ serde_json::to_string_pretty(item).unwrap_or_default(),
+ );
}
}
super::super::report(progress, &id, "done", done, Some(total), None);
- Ok(DownloadResult { files, skipped, failed, dest: dest.to_string() })
+ Ok(DownloadResult {
+ files,
+ skipped,
+ failed,
+ dest: dest.to_string(),
+ })
}
#[cfg(test)]
diff --git a/src-tauri/omniget-core/src/core/tools/instagram/mod.rs b/src-tauri/omniget-core/src/core/tools/instagram/mod.rs
index 053e4353..fdc6b6be 100644
--- a/src-tauri/omniget-core/src/core/tools/instagram/mod.rs
+++ b/src-tauri/omniget-core/src/core/tools/instagram/mod.rs
@@ -116,7 +116,12 @@ impl Session {
.into_iter()
.filter(|c| c.domain.ends_with("instagram.com"))
.collect();
- let get = |n: &str| cookies.iter().find(|c| c.name == n).map(|c| c.value.clone());
+ let get = |n: &str| {
+ cookies
+ .iter()
+ .find(|c| c.name == n)
+ .map(|c| c.value.clone())
+ };
let session_id = get("sessionid").filter(|v| !v.is_empty());
let user_id = get("ds_user_id").filter(|v| !v.is_empty());
match (session_id, user_id) {
@@ -130,7 +135,11 @@ impl Session {
}
pub fn info(&self) -> SessionInfo {
- SessionInfo { user_id: self.user_id.clone(), has_session: true, cookie_count: self.cookies.len() }
+ SessionInfo {
+ user_id: self.user_id.clone(),
+ has_session: true,
+ cookie_count: self.cookies.len(),
+ }
}
}
@@ -150,12 +159,30 @@ impl IgClient {
let jar = reqwest::cookie::Jar::default();
for c in &session.cookies {
let scheme = if c.secure { "https" } else { "http" };
- let url: reqwest::Url = format!("{}://{}{}", scheme, c.domain, if c.path.is_empty() { "/" } else { &c.path }).parse()?;
- jar.add_cookie_str(&format!("{}={}; Domain={}; Path={}", c.name, c.value, c.domain, if c.path.is_empty() { "/" } else { &c.path }), &url);
+ let url: reqwest::Url = format!(
+ "{}://{}{}",
+ scheme,
+ c.domain,
+ if c.path.is_empty() { "/" } else { &c.path }
+ )
+ .parse()?;
+ jar.add_cookie_str(
+ &format!(
+ "{}={}; Domain={}; Path={}",
+ c.name,
+ c.value,
+ c.domain,
+ if c.path.is_empty() { "/" } else { &c.path }
+ ),
+ &url,
+ );
}
let mut headers = HeaderMap::new();
headers.insert(reqwest::header::USER_AGENT, HeaderValue::from_static(UA));
- headers.insert(reqwest::header::ACCEPT_LANGUAGE, HeaderValue::from_static("en-US,en;q=0.9,pt-BR;q=0.8"));
+ headers.insert(
+ reqwest::header::ACCEPT_LANGUAGE,
+ HeaderValue::from_static("en-US,en;q=0.9,pt-BR;q=0.8"),
+ );
let http = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
.default_headers(headers)
.cookie_provider(Arc::new(jar))
@@ -163,17 +190,33 @@ impl IgClient {
.timeout(Duration::from_secs(120))
.build()?;
let csrf = session.csrf.clone();
- Ok(Arc::new(Self { http, session, www_claim: Mutex::new("0".into()), csrf: Mutex::new(csrf), page_delay_ms: (1200, 2600) }))
+ Ok(Arc::new(Self {
+ http,
+ session,
+ www_claim: Mutex::new("0".into()),
+ csrf: Mutex::new(csrf),
+ page_delay_ms: (1200, 2600),
+ }))
}
fn api_headers(&self) -> HeaderMap {
let mut h = HeaderMap::new();
h.insert("X-IG-App-ID", HeaderValue::from_static(APP_ID));
h.insert("X-ASBD-ID", HeaderValue::from_static(ASBD_ID));
- h.insert("X-IG-WWW-Claim", HeaderValue::from_str(&self.www_claim.lock().unwrap()).unwrap_or(HeaderValue::from_static("0")));
- h.insert("X-Requested-With", HeaderValue::from_static("XMLHttpRequest"));
+ h.insert(
+ "X-IG-WWW-Claim",
+ HeaderValue::from_str(&self.www_claim.lock().unwrap())
+ .unwrap_or(HeaderValue::from_static("0")),
+ );
+ h.insert(
+ "X-Requested-With",
+ HeaderValue::from_static("XMLHttpRequest"),
+ );
h.insert("Accept", HeaderValue::from_static("*/*"));
- h.insert("Referer", HeaderValue::from_static("https://www.instagram.com/"));
+ h.insert(
+ "Referer",
+ HeaderValue::from_static("https://www.instagram.com/"),
+ );
h.insert("Sec-Fetch-Dest", HeaderValue::from_static("empty"));
h.insert("Sec-Fetch-Mode", HeaderValue::from_static("cors"));
h.insert("Sec-Fetch-Site", HeaderValue::from_static("same-origin"));
@@ -187,8 +230,14 @@ impl IgClient {
let mut h = HeaderMap::new();
h.insert("X-IG-App-ID", HeaderValue::from_static(APP_ID));
h.insert("Accept", HeaderValue::from_static("*/*"));
- h.insert("Origin", HeaderValue::from_static("https://www.instagram.com"));
- h.insert("Referer", HeaderValue::from_static("https://www.instagram.com/"));
+ h.insert(
+ "Origin",
+ HeaderValue::from_static("https://www.instagram.com"),
+ );
+ h.insert(
+ "Referer",
+ HeaderValue::from_static("https://www.instagram.com/"),
+ );
if let Ok(v) = HeaderValue::from_str(&self.csrf.lock().unwrap()) {
h.insert("X-CSRFToken", v);
}
@@ -196,7 +245,11 @@ impl IgClient {
}
fn absorb(&self, resp: &reqwest::Response) {
- if let Some(c) = resp.headers().get("x-ig-set-www-claim").and_then(|v| v.to_str().ok()) {
+ if let Some(c) = resp
+ .headers()
+ .get("x-ig-set-www-claim")
+ .and_then(|v| v.to_str().ok())
+ {
*self.www_claim.lock().unwrap() = c.to_string();
}
for sc in resp.headers().get_all(reqwest::header::SET_COOKIE) {
@@ -215,13 +268,27 @@ impl IgClient {
self.absorb(&resp);
let status = resp.status();
if status.is_redirection() {
- let loc = resp.headers().get(reqwest::header::LOCATION).and_then(|v| v.to_str().ok()).unwrap_or("");
+ let loc = resp
+ .headers()
+ .get(reqwest::header::LOCATION)
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("");
if loc.contains("/accounts/login") || loc.contains("/challenge") {
- return Err(if loc.contains("/challenge") { IgError::Checkpoint } else { IgError::LoginRequired });
+ return Err(if loc.contains("/challenge") {
+ IgError::Checkpoint
+ } else {
+ IgError::LoginRequired
+ });
}
- return Err(IgError::Other(format!("{}: redirecionado para {}", what, loc)));
+ return Err(IgError::Other(format!(
+ "{}: redirecionado para {}",
+ what, loc
+ )));
}
- let text = resp.text().await.map_err(|e| IgError::Other(e.to_string()))?;
+ let text = resp
+ .text()
+ .await
+ .map_err(|e| IgError::Other(e.to_string()))?;
if status.as_u16() == 429 {
return Err(IgError::RateLimited);
}
@@ -234,25 +301,46 @@ impl IgClient {
}
return Err(IgError::Other(format!("{}: o Instagram respondeu HTML em vez de JSON (endpoint mudou ou sessao invalida, HTTP {})", what, status.as_u16())));
}
- return Err(IgError::Other(format!("{}: resposta invalida (HTTP {})", what, status.as_u16())));
+ return Err(IgError::Other(format!(
+ "{}: resposta invalida (HTTP {})",
+ what,
+ status.as_u16()
+ )));
}
};
- let message = json.get("message").and_then(|m| m.as_str()).unwrap_or("").to_string();
- let error_type = json.get("error_type").and_then(|m| m.as_str()).unwrap_or("");
+ let message = json
+ .get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("")
+ .to_string();
+ let error_type = json
+ .get("error_type")
+ .and_then(|m| m.as_str())
+ .unwrap_or("");
if message == "login_required" || error_type == "login_required" {
return Err(IgError::LoginRequired);
}
- if message == "checkpoint_required" || message == "challenge_required" || json.get("checkpoint_url").is_some() {
+ if message == "checkpoint_required"
+ || message == "challenge_required"
+ || json.get("checkpoint_url").is_some()
+ {
return Err(IgError::Checkpoint);
}
if message == "feedback_required" || json.get("feedback_title").is_some() {
return Err(IgError::ActionBlocked);
}
- if status.as_u16() == 404 || message.contains("not found") || message == "Media not found or unavailable" {
+ if status.as_u16() == 404
+ || message.contains("not found")
+ || message == "Media not found or unavailable"
+ {
return Err(IgError::NotFound(what.to_string()));
}
if !status.is_success() {
- let m = if message.is_empty() { format!("HTTP {}", status.as_u16()) } else { message };
+ let m = if message.is_empty() {
+ format!("HTTP {}", status.as_u16())
+ } else {
+ message
+ };
return Err(IgError::Other(format!("{}: {}", what, m)));
}
Ok(json)
@@ -260,7 +348,11 @@ impl IgClient {
/// GET `/api/v1/...` (ou URL absoluta) com os cabeçalhos da web.
pub async fn get_json(&self, path: &str, query: &[(&str, String)]) -> Result<Value, IgError> {
- let url = if path.starts_with("http") { path.to_string() } else { format!("{}{}", BASE, path) };
+ let url = if path.starts_with("http") {
+ path.to_string()
+ } else {
+ format!("{}{}", BASE, path)
+ };
let resp = self
.http
.get(&url)
@@ -274,7 +366,11 @@ impl IgClient {
/// POST de formulário para `/api/v1/...`.
pub async fn post_form(&self, path: &str, form: &[(&str, String)]) -> Result<Value, IgError> {
- let url = if path.starts_with("http") { path.to_string() } else { format!("{}{}", BASE, path) };
+ let url = if path.starts_with("http") {
+ path.to_string()
+ } else {
+ format!("{}{}", BASE, path)
+ };
let resp = self
.http
.post(&url)
@@ -287,7 +383,12 @@ impl IgClient {
}
/// POST cru (upload) com cabeçalhos extras.
- pub async fn post_raw(&self, url: &str, extra: HeaderMap, body: Vec<u8>) -> Result<Value, IgError> {
+ pub async fn post_raw(
+ &self,
+ url: &str,
+ extra: HeaderMap,
+ body: Vec<u8>,
+ ) -> Result<Value, IgError> {
let mut h = self.post_headers();
h.extend(extra);
let resp = self
@@ -323,7 +424,12 @@ impl IgClient {
pub async fn download(&self, url: &str, dest: &std::path::Path) -> anyhow::Result<u64> {
use futures::StreamExt;
use tokio::io::AsyncWriteExt;
- let resp = self.http.get(url).header("Referer", "https://www.instagram.com/").send().await?;
+ let resp = self
+ .http
+ .get(url)
+ .header("Referer", "https://www.instagram.com/")
+ .send()
+ .await?;
if !resp.status().is_success() {
bail!("download falhou: HTTP {}", resp.status());
}
@@ -348,16 +454,27 @@ impl IgClient {
/// GraphQL por `doc_id` (POST `/graphql/query`), com as variáveis
/// "provider" que a query exige; sem elas o servidor devolve
/// "execution error".
- pub async fn graphql(&self, friendly_name: &str, mut variables: Value) -> Result<Value, IgError> {
+ pub async fn graphql(
+ &self,
+ friendly_name: &str,
+ mut variables: Value,
+ ) -> Result<Value, IgError> {
let ids = doc_ids(self).await;
- let doc_id = ids
- .ids
- .get(friendly_name)
- .cloned()
- .ok_or_else(|| IgError::Other(format!("nao achei o doc_id de {} nos bundles do Instagram", friendly_name)))?;
+ let doc_id = ids.ids.get(friendly_name).cloned().ok_or_else(|| {
+ IgError::Other(format!(
+ "nao achei o doc_id de {} nos bundles do Instagram",
+ friendly_name
+ ))
+ })?;
if let Some(obj) = variables.as_object_mut() {
- for p in ids.providers.get(friendly_name).cloned().unwrap_or_default() {
- obj.entry(format!("__relay_internal__pv__{}", p.replace('.', ""))).or_insert(Value::Bool(false));
+ for p in ids
+ .providers
+ .get(friendly_name)
+ .cloned()
+ .unwrap_or_default()
+ {
+ obj.entry(format!("__relay_internal__pv__{}", p.replace('.', "")))
+ .or_insert(Value::Bool(false));
}
}
let form = vec![
@@ -368,12 +485,22 @@ impl IgClient {
("doc_id", doc_id),
];
let json = self.post_form("/graphql/query", &form).await?;
- if let Some(err) = json.get("errors").and_then(|e| e.as_array()).and_then(|a| a.first()) {
- let msg = err.get("message").and_then(|m| m.as_str()).unwrap_or("erro");
+ if let Some(err) = json
+ .get("errors")
+ .and_then(|e| e.as_array())
+ .and_then(|a| a.first())
+ {
+ let msg = err
+ .get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("erro");
if msg.contains("execution error") {
invalidate_doc_ids();
}
- return Err(IgError::Other(format!("GraphQL {}: {}", friendly_name, msg)));
+ return Err(IgError::Other(format!(
+ "GraphQL {}: {}",
+ friendly_name, msg
+ )));
}
Ok(json)
}
@@ -407,9 +534,18 @@ fn doc_ids_path() -> Option<std::path::PathBuf> {
/// bundles não acha o módulo (ele pode estar num chunk carregado depois).
fn default_doc_ids() -> DocIds {
let mut ids = HashMap::new();
- ids.insert("PolarisProfilePostsQuery".into(), "38154989454116081".into());
- ids.insert("PolarisProfilePostsTabContentQuery_connection".into(), "39535953862670189".into());
- ids.insert("PolarisPostActionLoadPostQueryQuery".into(), "8845758582119845".into());
+ ids.insert(
+ "PolarisProfilePostsQuery".into(),
+ "38154989454116081".into(),
+ );
+ ids.insert(
+ "PolarisProfilePostsTabContentQuery_connection".into(),
+ "39535953862670189".into(),
+ );
+ ids.insert(
+ "PolarisPostActionLoadPostQueryQuery".into(),
+ "8845758582119845".into(),
+ );
let provs = vec![
"PolarisMultiCaptionCarouselEnabled.relayprovider".to_string(),
"PolarisShortDramaEnabled.relayprovider".to_string(),
@@ -417,8 +553,15 @@ fn default_doc_ids() -> DocIds {
];
let mut providers = HashMap::new();
providers.insert("PolarisProfilePostsQuery".into(), provs.clone());
- providers.insert("PolarisProfilePostsTabContentQuery_connection".into(), provs);
- DocIds { fetched_at: 0, ids, providers }
+ providers.insert(
+ "PolarisProfilePostsTabContentQuery_connection".into(),
+ provs,
+ );
+ DocIds {
+ fetched_at: 0,
+ ids,
+ providers,
+ }
}
static DOC_IDS: OnceLock<Mutex<Option<DocIds>>> = OnceLock::new();
@@ -452,14 +595,25 @@ pub async fn doc_ids(client: &IgClient) -> DocIds {
let mut found = default_doc_ids();
found.fetched_at = now;
if let Ok(html) = client.get_text(&format!("{}/instagram/", BASE)).await {
- let script_re = regex::Regex::new(r#"https://static\.cdninstagram\.com/rsrc\.php/[A-Za-z0-9_/.\-]+\.js"#).unwrap();
- let mut urls: Vec<String> = script_re.find_iter(&html).map(|m| m.as_str().to_string()).collect();
+ let script_re = regex::Regex::new(
+ r#"https://static\.cdninstagram\.com/rsrc\.php/[A-Za-z0-9_/.\-]+\.js"#,
+ )
+ .unwrap();
+ let mut urls: Vec<String> = script_re
+ .find_iter(&html)
+ .map(|m| m.as_str().to_string())
+ .collect();
urls.dedup();
let id_re = regex::Regex::new(r#"__d\("([A-Za-z0-9_]*Query[A-Za-z0-9_]*)_instagramRelayOperation"\s*,\s*\[\]\s*,\s*\(function\([^)]*\)\{[^}]{0,80}?exports\s*=\s*"?(\d{10,20})"?"#).unwrap();
- let dep_re = regex::Regex::new(r#"__d\("([A-Za-z0-9_]*Query[A-Za-z0-9_]*)\.graphql"\s*,\s*\[([^\]]*)\]"#).unwrap();
+ let dep_re = regex::Regex::new(
+ r#"__d\("([A-Za-z0-9_]*Query[A-Za-z0-9_]*)\.graphql"\s*,\s*\[([^\]]*)\]"#,
+ )
+ .unwrap();
let mut hits = 0;
for u in urls.into_iter().take(40) {
- let Ok(text) = client.get_text(&u).await else { continue };
+ let Ok(text) = client.get_text(&u).await else {
+ continue;
+ };
for c in id_re.captures_iter(&text) {
if c[1].starts_with("Polaris") {
found.ids.insert(c[1].to_string(), c[2].to_string());
@@ -483,7 +637,10 @@ pub async fn doc_ids(client: &IgClient) -> DocIds {
}
}
}
- tracing::debug!("[instagram] doc_ids: {} operacoes encontradas nos bundles", hits);
+ tracing::debug!(
+ "[instagram] doc_ids: {} operacoes encontradas nos bundles",
+ hits
+ );
}
if let Some(p) = doc_ids_path() {
if let Some(parent) = p.parent() {
@@ -498,7 +655,11 @@ pub async fn doc_ids(client: &IgClient) -> DocIds {
// ── Shortcode ↔ id ───────────────────────────────────────────────────────
pub fn shortcode_to_pk(code: &str) -> Option<u64> {
- let code = if code.len() > 28 { &code[..code.len() - 28] } else { code };
+ let code = if code.len() > 28 {
+ &code[..code.len() - 28]
+ } else {
+ code
+ };
let mut n: u128 = 0;
for b in code.bytes() {
let i = ALPHABET.iter().position(|&a| a == b)? as u128;
@@ -526,15 +687,27 @@ pub fn pk_to_shortcode(mut pk: u64) -> String {
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum IgTarget {
/// `/p/<code>`, `/reel/<code>`, `/tv/<code>`, `/<user>/p/<code>`
- Post { shortcode: String },
+ Post {
+ shortcode: String,
+ },
/// `/stories/<user>/<id?>`
- Story { username: String, media_id: Option<String> },
+ Story {
+ username: String,
+ media_id: Option<String>,
+ },
/// `/stories/highlights/<id>` ou `/s/<base64>`
- Highlight { id: String },
+ Highlight {
+ id: String,
+ },
/// `/<user>/`, `/<user>/reels/`, `/<user>/tagged/`
- Profile { username: String, tab: String },
+ Profile {
+ username: String,
+ tab: String,
+ },
/// `/explore/tags/<tag>`
- Tag { name: String },
+ Tag {
+ name: String,
+ },
Unknown,
}
@@ -542,36 +715,78 @@ pub fn parse_target(input: &str) -> IgTarget {
let s = input.trim();
let s = s.strip_prefix('@').unwrap_or(s);
if let Some(tag) = s.strip_prefix('#') {
- return IgTarget::Tag { name: tag.to_string() };
+ return IgTarget::Tag {
+ name: tag.to_string(),
+ };
}
- let candidate: String = if s.contains("://") { s.to_string() } else if s.contains("instagram.com") { format!("https://{}", s) } else { s.to_string() };
+ let candidate: String = if s.contains("://") {
+ s.to_string()
+ } else if s.contains("instagram.com") {
+ format!("https://{}", s)
+ } else {
+ s.to_string()
+ };
let Ok(url) = url::Url::parse(&candidate) else {
// Só um nome de usuário ou um shortcode?
- if s.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_') && !s.is_empty() {
- return IgTarget::Profile { username: s.to_lowercase(), tab: "posts".into() };
+ if s.chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_')
+ && !s.is_empty()
+ {
+ return IgTarget::Profile {
+ username: s.to_lowercase(),
+ tab: "posts".into(),
+ };
}
return IgTarget::Unknown;
};
- if !url.host_str().map(|h| h.ends_with("instagram.com")).unwrap_or(false) {
+ if !url
+ .host_str()
+ .map(|h| h.ends_with("instagram.com"))
+ .unwrap_or(false)
+ {
return IgTarget::Unknown;
}
- let segs: Vec<&str> = url.path_segments().map(|p| p.filter(|s| !s.is_empty()).collect()).unwrap_or_default();
+ let segs: Vec<&str> = url
+ .path_segments()
+ .map(|p| p.filter(|s| !s.is_empty()).collect())
+ .unwrap_or_default();
match segs.as_slice() {
- ["p" | "reel" | "reels" | "tv", code, ..] => IgTarget::Post { shortcode: code.to_string() },
- [_, "p" | "reel" | "reels" | "tv", code, ..] => IgTarget::Post { shortcode: code.to_string() },
+ ["p" | "reel" | "reels" | "tv", code, ..] => IgTarget::Post {
+ shortcode: code.to_string(),
+ },
+ [_, "p" | "reel" | "reels" | "tv", code, ..] => IgTarget::Post {
+ shortcode: code.to_string(),
+ },
["stories", "highlights", id, ..] => IgTarget::Highlight { id: id.to_string() },
["s", b64, ..] => {
use base64::Engine;
- let decoded = base64::engine::general_purpose::STANDARD.decode(b64).ok().and_then(|b| String::from_utf8(b).ok()).unwrap_or_default();
+ let decoded = base64::engine::general_purpose::STANDARD
+ .decode(b64)
+ .ok()
+ .and_then(|b| String::from_utf8(b).ok())
+ .unwrap_or_default();
match decoded.strip_prefix("highlight:") {
Some(id) => IgTarget::Highlight { id: id.to_string() },
None => IgTarget::Unknown,
}
}
- ["stories", user, rest @ ..] => IgTarget::Story { username: user.to_lowercase(), media_id: rest.first().map(|s| s.to_string()) },
- ["explore", "tags", tag, ..] => IgTarget::Tag { name: tag.to_string() },
- [user] => IgTarget::Profile { username: user.to_lowercase(), tab: "posts".into() },
- [user, tab @ ("reels" | "tagged" | "saved" | "highlights" | "followers" | "following"), ..] => IgTarget::Profile { username: user.to_lowercase(), tab: tab.to_string() },
+ ["stories", user, rest @ ..] => IgTarget::Story {
+ username: user.to_lowercase(),
+ media_id: rest.first().map(|s| s.to_string()),
+ },
+ ["explore", "tags", tag, ..] => IgTarget::Tag {
+ name: tag.to_string(),
+ },
+ [user] => IgTarget::Profile {
+ username: user.to_lowercase(),
+ tab: "posts".into(),
+ },
+ [user, tab @ ("reels" | "tagged" | "saved" | "highlights" | "followers" | "following"), ..] => {
+ IgTarget::Profile {
+ username: user.to_lowercase(),
+ tab: tab.to_string(),
+ }
+ }
_ => IgTarget::Unknown,
}
}
@@ -582,7 +797,10 @@ static JOBS: OnceLock<Mutex<HashMap<String, Arc<AtomicBool>>>> = OnceLock::new()
pub fn job_start(id: &str) -> Arc<AtomicBool> {
let flag = Arc::new(AtomicBool::new(false));
- JOBS.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap().insert(id.to_string(), flag.clone());
+ JOBS.get_or_init(|| Mutex::new(HashMap::new()))
+ .lock()
+ .unwrap()
+ .insert(id.to_string(), flag.clone());
flag
}
@@ -609,13 +827,18 @@ pub fn cancelled(flag: &AtomicBool) -> bool {
// ── Pasta de dados ───────────────────────────────────────────────────────
pub fn data_dir() -> std::path::PathBuf {
- let d = super::tools_dir().unwrap_or_else(std::env::temp_dir).join("instagram");
+ let d = super::tools_dir()
+ .unwrap_or_else(std::env::temp_dir)
+ .join("instagram");
let _ = std::fs::create_dir_all(&d);
d
}
pub fn read_json<T: serde::de::DeserializeOwned + Default>(path: &std::path::Path) -> T {
- std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
+ std::fs::read_to_string(path)
+ .ok()
+ .and_then(|t| serde_json::from_str(&t).ok())
+ .unwrap_or_default()
}
pub fn write_json<T: Serialize>(path: &std::path::Path, value: &T) -> anyhow::Result<()> {
@@ -667,14 +890,57 @@ mod tests {
#[test]
fn parses_targets() {
- assert_eq!(parse_target("https://www.instagram.com/p/B89prebFBcw/?igsh=abc"), IgTarget::Post { shortcode: "B89prebFBcw".into() });
- assert_eq!(parse_target("https://www.instagram.com/reel/Dc30nJeRKKz/"), IgTarget::Post { shortcode: "Dc30nJeRKKz".into() });
- assert_eq!(parse_target("https://www.instagram.com/instagram/reel/Dc30nJeRKKz/"), IgTarget::Post { shortcode: "Dc30nJeRKKz".into() });
- assert_eq!(parse_target("https://www.instagram.com/stories/highlights/18142207969557132/"), IgTarget::Highlight { id: "18142207969557132".into() });
- assert_eq!(parse_target("https://www.instagram.com/stories/instagram/3811480328699137079/"), IgTarget::Story { username: "instagram".into(), media_id: Some("3811480328699137079".into()) });
- assert_eq!(parse_target("instagram.com/instagram/reels/"), IgTarget::Profile { username: "instagram".into(), tab: "reels".into() });
- assert_eq!(parse_target("@Instagram"), IgTarget::Profile { username: "instagram".into(), tab: "posts".into() });
- assert_eq!(parse_target("#sunset"), IgTarget::Tag { name: "sunset".into() });
+ assert_eq!(
+ parse_target("https://www.instagram.com/p/B89prebFBcw/?igsh=abc"),
+ IgTarget::Post {
+ shortcode: "B89prebFBcw".into()
+ }
+ );
+ assert_eq!(
+ parse_target("https://www.instagram.com/reel/Dc30nJeRKKz/"),
+ IgTarget::Post {
+ shortcode: "Dc30nJeRKKz".into()
+ }
+ );
+ assert_eq!(
+ parse_target("https://www.instagram.com/instagram/reel/Dc30nJeRKKz/"),
+ IgTarget::Post {
+ shortcode: "Dc30nJeRKKz".into()
+ }
+ );
+ assert_eq!(
+ parse_target("https://www.instagram.com/stories/highlights/18142207969557132/"),
+ IgTarget::Highlight {
+ id: "18142207969557132".into()
+ }
+ );
+ assert_eq!(
+ parse_target("https://www.instagram.com/stories/instagram/3811480328699137079/"),
+ IgTarget::Story {
+ username: "instagram".into(),
+ media_id: Some("3811480328699137079".into())
+ }
+ );
+ assert_eq!(
+ parse_target("instagram.com/instagram/reels/"),
+ IgTarget::Profile {
+ username: "instagram".into(),
+ tab: "reels".into()
+ }
+ );
+ assert_eq!(
+ parse_target("@Instagram"),
+ IgTarget::Profile {
+ username: "instagram".into(),
+ tab: "posts".into()
+ }
+ );
+ assert_eq!(
+ parse_target("#sunset"),
+ IgTarget::Tag {
+ name: "sunset".into()
+ }
+ );
assert_eq!(parse_target("https://youtube.com/x"), IgTarget::Unknown);
}
diff --git a/src-tauri/omniget-core/src/core/tools/instagram/profile.rs b/src-tauri/omniget-core/src/core/tools/instagram/profile.rs
index 6fb86222..2a7c56ff 100644
--- a/src-tauri/omniget-core/src/core/tools/instagram/profile.rs
+++ b/src-tauri/omniget-core/src/core/tools/instagram/profile.rs
@@ -40,16 +40,38 @@ fn parse_user_info(v: &Value) -> UserInfo {
.and_then(|h| h.get("url"))
.and_then(|x| x.as_str())
.map(|x| x.to_string())
- .or_else(|| v.get("hd_profile_pic_versions").and_then(|a| a.as_array()).and_then(|a| a.last()).and_then(|x| x.get("url")).and_then(|x| x.as_str()).map(|x| x.to_string()))
- .or_else(|| v.get("profile_pic_url_hd").and_then(|x| x.as_str()).map(|x| x.to_string()))
+ .or_else(|| {
+ v.get("hd_profile_pic_versions")
+ .and_then(|a| a.as_array())
+ .and_then(|a| a.last())
+ .and_then(|x| x.get("url"))
+ .and_then(|x| x.as_str())
+ .map(|x| x.to_string())
+ })
+ .or_else(|| {
+ v.get("profile_pic_url_hd")
+ .and_then(|x| x.as_str())
+ .map(|x| x.to_string())
+ })
.unwrap_or_else(|| s(v, "profile_pic_url"));
let count = |k: &str, edge: &str| {
let n = u(v, k);
- if n > 0 { n } else { v.get(edge).and_then(|e| e.get("count")).and_then(|c| c.as_u64()).unwrap_or(0) }
+ if n > 0 {
+ n
+ } else {
+ v.get(edge)
+ .and_then(|e| e.get("count"))
+ .and_then(|c| c.as_u64())
+ .unwrap_or(0)
+ }
};
let pk = {
let p = s(v, "pk");
- if p.is_empty() { s(v, "id") } else { p }
+ if p.is_empty() {
+ s(v, "id")
+ } else {
+ p
+ }
};
UserInfo {
username: s(v, "username"),
@@ -65,12 +87,22 @@ fn parse_user_info(v: &Value) -> UserInfo {
is_business: b(v, "is_business") || b(v, "is_business_account"),
category: {
let c = s(v, "category");
- if c.is_empty() { s(v, "category_name") } else { c }
+ if c.is_empty() {
+ s(v, "category_name")
+ } else {
+ c
+ }
},
profile_pic_url: s(v, "profile_pic_url"),
profile_pic_hd: hd,
- followed_by_viewer: b(v, "followed_by_viewer") || v.get("friendship_status").map(|f| b(f, "following")).unwrap_or(false),
- follows_viewer: b(v, "follows_viewer") || v.get("friendship_status").map(|f| b(f, "followed_by")).unwrap_or(false),
+ followed_by_viewer: b(v, "followed_by_viewer")
+ || v.get("friendship_status")
+ .map(|f| b(f, "following"))
+ .unwrap_or(false),
+ follows_viewer: b(v, "follows_viewer")
+ || v.get("friendship_status")
+ .map(|f| b(f, "followed_by"))
+ .unwrap_or(false),
has_highlights: b(v, "has_highlight_reels") || b(v, "highlight_reel_count"),
is_self: false,
pk,
@@ -79,8 +111,12 @@ fn parse_user_info(v: &Value) -> UserInfo {
/// `GET /api/v1/users/{id}/info/`
pub async fn user_by_id(client: &IgClient, id: &str) -> Result<UserInfo, IgError> {
- let json = client.get_json(&format!("/api/v1/users/{}/info/", id), &[]).await?;
- let user = json.get("user").ok_or_else(|| IgError::NotFound(format!("usuario {}", id)))?;
+ let json = client
+ .get_json(&format!("/api/v1/users/{}/info/", id), &[])
+ .await?;
+ let user = json
+ .get("user")
+ .ok_or_else(|| IgError::NotFound(format!("usuario {}", id)))?;
let mut info = parse_user_info(user);
info.is_self = info.pk == client.session.user_id;
Ok(info)
@@ -96,8 +132,18 @@ pub async fn resolve_user(client: &IgClient, name_or_id: &str) -> Result<UserInf
if name.chars().all(|c| c.is_ascii_digit()) {
return user_by_id(client, &name).await;
}
- if let Ok(json) = client.get_json("/api/v1/users/web_profile_info/", &[("username", name.clone())]).await {
- if let Some(user) = json.get("data").and_then(|d| d.get("user")).filter(|u| !u.is_null()) {
+ if let Ok(json) = client
+ .get_json(
+ "/api/v1/users/web_profile_info/",
+ &[("username", name.clone())],
+ )
+ .await
+ {
+ if let Some(user) = json
+ .get("data")
+ .and_then(|d| d.get("user"))
+ .filter(|u| !u.is_null())
+ {
let mut info = parse_user_info(user);
if info.profile_pic_hd.is_empty() || info.total_clips == 0 {
if let Ok(full) = user_by_id(client, &info.pk).await {
@@ -110,8 +156,17 @@ pub async fn resolve_user(client: &IgClient, name_or_id: &str) -> Result<UserInf
return Ok(info);
}
}
- let json = client.get_json("/api/v1/web/search/topsearch/", &[("query", name.clone()), ("context", "blended".into())]).await?;
- let users = json.get("users").and_then(|u| u.as_array()).cloned().unwrap_or_default();
+ let json = client
+ .get_json(
+ "/api/v1/web/search/topsearch/",
+ &[("query", name.clone()), ("context", "blended".into())],
+ )
+ .await?;
+ let users = json
+ .get("users")
+ .and_then(|u| u.as_array())
+ .cloned()
+ .unwrap_or_default();
let hit = users
.iter()
.filter_map(|r| r.get("user"))
@@ -139,7 +194,14 @@ fn page_pause_check(flag: &AtomicBool) -> bool {
}
/// Posts do perfil (fotos, vídeos e carrosséis) via GraphQL, mais novos primeiro.
-pub async fn user_posts(client: &IgClient, username: &str, limit: usize, flag: &AtomicBool, progress: &super::super::ProgressFn, job: &str) -> Result<Vec<MediaItem>, IgError> {
+pub async fn user_posts(
+ client: &IgClient,
+ username: &str,
+ limit: usize,
+ flag: &AtomicBool,
+ progress: &super::super::ProgressFn,
+ job: &str,
+) -> Result<Vec<MediaItem>, IgError> {
let data = json!({"count": 12, "include_reel_media_seen_timestamp": true, "include_relationship_info": true, "latest_besties_reel_media": true, "latest_reel_media": true});
let mut out = Vec::new();
let mut after: Option<String> = None;
@@ -147,12 +209,22 @@ pub async fn user_posts(client: &IgClient, username: &str, limit: usize, flag: &
let id = format!("ig:{}", job);
loop {
let (name, vars) = if first {
- ("PolarisProfilePostsQuery", json!({"data": data, "username": username}))
+ (
+ "PolarisProfilePostsQuery",
+ json!({"data": data, "username": username}),
+ )
} else {
- ("PolarisProfilePostsTabContentQuery_connection", json!({"after": after, "before": null, "data": data, "first": 12, "last": null, "username": username}))
+ (
+ "PolarisProfilePostsTabContentQuery_connection",
+ json!({"after": after, "before": null, "data": data, "first": 12, "last": null, "username": username}),
+ )
};
let json = client.graphql(name, vars).await?;
- let conn = json.get("data").and_then(|d| d.get("xdt_api__v1__feed__user_timeline_graphql_connection")).cloned().unwrap_or(Value::Null);
+ let conn = json
+ .get("data")
+ .and_then(|d| d.get("xdt_api__v1__feed__user_timeline_graphql_connection"))
+ .cloned()
+ .unwrap_or(Value::Null);
if conn.is_null() {
if first {
if let Some(user) = json.get("data").and_then(|d| d.get("xdt_viewer")) {
@@ -162,17 +234,40 @@ pub async fn user_posts(client: &IgClient, username: &str, limit: usize, flag: &
}
break;
}
- let edges = conn.get("edges").and_then(|e| e.as_array()).cloned().unwrap_or_default();
+ let edges = conn
+ .get("edges")
+ .and_then(|e| e.as_array())
+ .cloned()
+ .unwrap_or_default();
for e in &edges {
if let Some(item) = e.get("node").and_then(parse_item) {
out.push(item);
}
}
- super::super::report(progress, &id, "list", out.len() as u64, if limit > 0 { Some(limit as u64) } else { None }, None);
- let has_next = conn.get("page_info").map(|p| b(p, "has_next_page")).unwrap_or(false);
- after = conn.get("page_info").and_then(|p| p.get("end_cursor")).and_then(|c| c.as_str()).map(|c| c.to_string());
+ super::super::report(
+ progress,
+ &id,
+ "list",
+ out.len() as u64,
+ if limit > 0 { Some(limit as u64) } else { None },
+ None,
+ );
+ let has_next = conn
+ .get("page_info")
+ .map(|p| b(p, "has_next_page"))
+ .unwrap_or(false);
+ after = conn
+ .get("page_info")
+ .and_then(|p| p.get("end_cursor"))
+ .and_then(|c| c.as_str())
+ .map(|c| c.to_string());
first = false;
- if edges.is_empty() || !has_next || after.is_none() || (limit > 0 && out.len() >= limit) || !page_pause_check(flag) {
+ if edges.is_empty()
+ || !has_next
+ || after.is_none()
+ || (limit > 0 && out.len() >= limit)
+ || !page_pause_check(flag)
+ {
break;
}
client.pause().await;
@@ -184,26 +279,56 @@ pub async fn user_posts(client: &IgClient, username: &str, limit: usize, flag: &
}
/// Reels do perfil (`POST /api/v1/clips/user/`).
-pub async fn user_reels(client: &IgClient, user_id: &str, limit: usize, flag: &AtomicBool, progress: &super::super::ProgressFn, job: &str) -> Result<Vec<MediaItem>, IgError> {
+pub async fn user_reels(
+ client: &IgClient,
+ user_id: &str,
+ limit: usize,
+ flag: &AtomicBool,
+ progress: &super::super::ProgressFn,
+ job: &str,
+) -> Result<Vec<MediaItem>, IgError> {
let mut out = Vec::new();
let mut max_id: Option<String> = None;
let id = format!("ig:{}", job);
loop {
- let mut form = vec![("target_user_id", user_id.to_string()), ("page_size", "12".to_string()), ("include_feed_video", "true".to_string())];
+ let mut form = vec![
+ ("target_user_id", user_id.to_string()),
+ ("page_size", "12".to_string()),
+ ("include_feed_video", "true".to_string()),
+ ];
if let Some(m) = &max_id {
form.push(("max_id", m.clone()));
}
let json = client.post_form("/api/v1/clips/user/", &form).await?;
- let items = json.get("items").and_then(|i| i.as_array()).cloned().unwrap_or_default();
+ let items = json
+ .get("items")
+ .and_then(|i| i.as_array())
+ .cloned()
+ .unwrap_or_default();
for it in &items {
if let Some(item) = it.get("media").and_then(parse_item) {
out.push(item);
}
}
- super::super::report(progress, &id, "list", out.len() as u64, if limit > 0 { Some(limit as u64) } else { None }, None);
+ super::super::report(
+ progress,
+ &id,
+ "list",
+ out.len() as u64,
+ if limit > 0 { Some(limit as u64) } else { None },
+ None,
+ );
let paging = json.get("paging_info").cloned().unwrap_or(Value::Null);
- max_id = paging.get("max_id").and_then(|m| m.as_str()).map(|m| m.to_string());
- if items.is_empty() || !b(&paging, "more_available") || max_id.is_none() || (limit > 0 && out.len() >= limit) || !page_pause_check(flag) {
+ max_id = paging
+ .get("max_id")
+ .and_then(|m| m.as_str())
+ .map(|m| m.to_string());
+ if items.is_empty()
+ || !b(&paging, "more_available")
+ || max_id.is_none()
+ || (limit > 0 && out.len() >= limit)
+ || !page_pause_check(flag)
+ {
break;
}
client.pause().await;
@@ -215,7 +340,16 @@ pub async fn user_reels(client: &IgClient, user_id: &str, limit: usize, flag: &A
}
#[allow(clippy::too_many_arguments)]
-async fn rest_feed(client: &IgClient, path: &str, count: u32, limit: usize, flag: &AtomicBool, progress: &super::super::ProgressFn, job: &str, wrapped: bool) -> Result<Vec<MediaItem>, IgError> {
+async fn rest_feed(
+ client: &IgClient,
+ path: &str,
+ count: u32,
+ limit: usize,
+ flag: &AtomicBool,
+ progress: &super::super::ProgressFn,
+ job: &str,
+ wrapped: bool,
+) -> Result<Vec<MediaItem>, IgError> {
let mut out = Vec::new();
let mut max_id: Option<String> = None;
let id = format!("ig:{}", job);
@@ -225,16 +359,40 @@ async fn rest_feed(client: &IgClient, path: &str, count: u32, limit: usize, flag
q.push(("max_id", m.clone()));
}
let json = client.get_json(path, &q).await?;
- let items = json.get("items").and_then(|i| i.as_array()).cloned().unwrap_or_default();
+ let items = json
+ .get("items")
+ .and_then(|i| i.as_array())
+ .cloned()
+ .unwrap_or_default();
for it in &items {
- let node = if wrapped { it.get("media").unwrap_or(it) } else { it };
+ let node = if wrapped {
+ it.get("media").unwrap_or(it)
+ } else {
+ it
+ };
if let Some(item) = parse_item(node) {
out.push(item);
}
}
- super::super::report(progress, &id, "list", out.len() as u64, if limit > 0 { Some(limit as u64) } else { None }, None);
- max_id = json.get("next_max_id").and_then(|m| match m { Value::String(x) => Some(x.clone()), Value::Number(n) => Some(n.to_string()), _ => None });
- if items.is_empty() || !b(&json, "more_available") || max_id.is_none() || (limit > 0 && out.len() >= limit) || !page_pause_check(flag) {
+ super::super::report(
+ progress,
+ &id,
+ "list",
+ out.len() as u64,
+ if limit > 0 { Some(limit as u64) } else { None },
+ None,
+ );
+ max_id = json.get("next_max_id").and_then(|m| match m {
+ Value::String(x) => Some(x.clone()),
+ Value::Number(n) => Some(n.to_string()),
+ _ => None,
+ });
+ if items.is_empty()
+ || !b(&json, "more_available")
+ || max_id.is_none()
+ || (limit > 0 && out.len() >= limit)
+ || !page_pause_check(flag)
+ {
break;
}
client.pause().await;
@@ -246,13 +404,46 @@ async fn rest_feed(client: &IgClient, path: &str, count: u32, limit: usize, flag
}
/// Posts em que o perfil foi marcado.
-pub async fn user_tagged(client: &IgClient, user_id: &str, limit: usize, flag: &AtomicBool, progress: &super::super::ProgressFn, job: &str) -> Result<Vec<MediaItem>, IgError> {
- rest_feed(client, &format!("/api/v1/usertags/{}/feed/", user_id), 20, limit, flag, progress, job, false).await
+pub async fn user_tagged(
+ client: &IgClient,
+ user_id: &str,
+ limit: usize,
+ flag: &AtomicBool,
+ progress: &super::super::ProgressFn,
+ job: &str,
+) -> Result<Vec<MediaItem>, IgError> {
+ rest_feed(
+ client,
+ &format!("/api/v1/usertags/{}/feed/", user_id),
+ 20,
+ limit,
+ flag,
+ progress,
+ job,
+ false,
+ )
+ .await
}
/// Posts salvos da própria conta (todos, sem separar por coleção).
-pub async fn saved(client: &IgClient, limit: usize, flag: &AtomicBool, progress: &super::super::ProgressFn, job: &str) -> Result<Vec<MediaItem>, IgError> {
- rest_feed(client, "/api/v1/feed/saved/posts/", 30, limit, flag, progress, job, true).await
+pub async fn saved(
+ client: &IgClient,
+ limit: usize,
+ flag: &AtomicBool,
+ progress: &super::super::ProgressFn,
+ job: &str,
+) -> Result<Vec<MediaItem>, IgError> {
+ rest_feed(
+ client,
+ "/api/v1/feed/saved/posts/",
+ 30,
+ limit,
+ flag,
+ progress,
+ job,
+ true,
+ )
+ .await
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -266,8 +457,17 @@ pub struct Highlight {
/// `GET /api/v1/highlights/{id}/highlights_tray/`
pub async fn highlights(client: &IgClient, user_id: &str) -> Result<Vec<Highlight>, IgError> {
- let json = client.get_json(&format!("/api/v1/highlights/{}/highlights_tray/", user_id), &[]).await?;
- let tray = json.get("tray").and_then(|t| t.as_array()).cloned().unwrap_or_default();
+ let json = client
+ .get_json(
+ &format!("/api/v1/highlights/{}/highlights_tray/", user_id),
+ &[],
+ )
+ .await?;
+ let tray = json
+ .get("tray")
+ .and_then(|t| t.as_array())
+ .cloned()
+ .unwrap_or_default();
Ok(tray
.iter()
.map(|h| Highlight {
@@ -275,7 +475,10 @@ pub async fn highlights(client: &IgClient, user_id: &str) -> Result<Vec<Highligh
title: s(h, "title"),
cover: h
.get("cover_media")
- .and_then(|c| c.get("cropped_image_version").or(c.get("full_image_version")))
+ .and_then(|c| {
+ c.get("cropped_image_version")
+ .or(c.get("full_image_version"))
+ })
.and_then(|i| i.get("url"))
.and_then(|x| x.as_str())
.map(|x| x.to_string())
@@ -303,14 +506,26 @@ pub struct Reel {
pub async fn reels_media(client: &IgClient, reel_ids: &[String]) -> Result<Vec<Reel>, IgError> {
let q: Vec<(&str, String)> = reel_ids.iter().map(|r| ("reel_ids", r.clone())).collect();
let json = client.get_json("/api/v1/feed/reels_media/", &q).await?;
- let reels = json.get("reels_media").and_then(|r| r.as_array()).cloned().unwrap_or_default();
+ let reels = json
+ .get("reels_media")
+ .and_then(|r| r.as_array())
+ .cloned()
+ .unwrap_or_default();
let mut out = Vec::new();
for reel in reels {
let user = reel.get("user").cloned().unwrap_or(Value::Null);
let username = s(&user, "username");
- let title = reel.get("title").and_then(|t| t.as_str()).map(|t| t.to_string());
+ let title = reel
+ .get("title")
+ .and_then(|t| t.as_str())
+ .map(|t| t.to_string());
let mut items = Vec::new();
- for it in reel.get("items").and_then(|i| i.as_array()).cloned().unwrap_or_default() {
+ for it in reel
+ .get("items")
+ .and_then(|i| i.as_array())
+ .cloned()
+ .unwrap_or_default()
+ {
let mut node = it.clone();
if node.get("user").is_none() {
node["user"] = user.clone();
@@ -323,7 +538,11 @@ pub async fn reels_media(client: &IgClient, reel_ids: &[String]) -> Result<Vec<R
items.push(item);
}
}
- let close_friends = reel.get("items").and_then(|i| i.as_array()).map(|a| a.iter().any(|x| s(x, "audience") == "besties")).unwrap_or(false);
+ let close_friends = reel
+ .get("items")
+ .and_then(|i| i.as_array())
+ .map(|a| a.iter().any(|x| s(x, "audience") == "besties"))
+ .unwrap_or(false);
out.push(Reel {
id: s(&reel, "id"),
title,
@@ -342,8 +561,15 @@ pub async fn stories_of(client: &IgClient, user_id: &str) -> Result<Vec<MediaIte
Ok(reels.into_iter().flat_map(|r| r.items).collect())
}
-pub async fn highlight_items(client: &IgClient, highlight_id: &str) -> Result<Vec<MediaItem>, IgError> {
- let id = if highlight_id.starts_with("highlight:") { highlight_id.to_string() } else { format!("highlight:{}", highlight_id) };
+pub async fn highlight_items(
+ client: &IgClient,
+ highlight_id: &str,
+) -> Result<Vec<MediaItem>, IgError> {
+ let id = if highlight_id.starts_with("highlight:") {
+ highlight_id.to_string()
+ } else {
+ format!("highlight:{}", highlight_id)
+ };
let reels = reels_media(client, &[id]).await?;
Ok(reels.into_iter().flat_map(|r| r.items).collect())
}
@@ -362,7 +588,11 @@ pub struct TrayEntry {
/// Bandeja de stories da própria conta (quem tem story agora).
pub async fn stories_tray(client: &IgClient) -> Result<Vec<TrayEntry>, IgError> {
let json = client.get_json("/api/v1/feed/reels_tray/", &[]).await?;
- let tray = json.get("tray").and_then(|t| t.as_array()).cloned().unwrap_or_default();
+ let tray = json
+ .get("tray")
+ .and_then(|t| t.as_array())
+ .cloned()
+ .unwrap_or_default();
Ok(tray
.iter()
.map(|t| {
@@ -372,7 +602,10 @@ pub async fn stories_tray(client: &IgClient) -> Result<Vec<TrayEntry>, IgError>
username: s(&user, "username"),
full_name: s(&user, "full_name"),
profile_pic_url: s(&user, "profile_pic_url"),
- latest_reel_media: t.get("latest_reel_media").and_then(|x| x.as_i64()).unwrap_or(0),
+ latest_reel_media: t
+ .get("latest_reel_media")
+ .and_then(|x| x.as_i64())
+ .unwrap_or(0),
seen: t.get("seen").and_then(|x| x.as_i64()).unwrap_or(0),
close_friends: b(t, "has_besties_media"),
}
@@ -381,7 +614,11 @@ pub async fn stories_tray(client: &IgClient) -> Result<Vec<TrayEntry>, IgError>
}
/// Quem viu um story seu (`/api/v1/media/{pk}/list_reel_media_viewer/`).
-pub async fn story_viewers(client: &IgClient, story_pk: &str, flag: &AtomicBool) -> Result<(u64, Vec<super::follow::MiniUser>), IgError> {
+pub async fn story_viewers(
+ client: &IgClient,
+ story_pk: &str,
+ flag: &AtomicBool,
+) -> Result<(u64, Vec<super::follow::MiniUser>), IgError> {
let mut out = Vec::new();
let mut max_id: Option<String> = None;
let mut total = 0u64;
@@ -390,13 +627,25 @@ pub async fn story_viewers(client: &IgClient, story_pk: &str, flag: &AtomicBool)
if let Some(m) = &max_id {
q.push(("max_id", m.clone()));
}
- let json = client.get_json(&format!("/api/v1/media/{}/list_reel_media_viewer/", story_pk), &q).await?;
+ let json = client
+ .get_json(
+ &format!("/api/v1/media/{}/list_reel_media_viewer/", story_pk),
+ &q,
+ )
+ .await?;
total = total.max(u(&json, "total_viewer_count"));
- let users = json.get("users").and_then(|u| u.as_array()).cloned().unwrap_or_default();
+ let users = json
+ .get("users")
+ .and_then(|u| u.as_array())
+ .cloned()
+ .unwrap_or_default();
for us in &users {
out.push(super::follow::MiniUser::from_value(us));
}
- max_id = json.get("next_max_id").and_then(|m| m.as_str()).map(|m| m.to_string());
+ max_id = json
+ .get("next_max_id")
+ .and_then(|m| m.as_str())
+ .map(|m| m.to_string());
if users.is_empty() || max_id.is_none() || super::cancelled(flag) {
break;
}
@@ -419,7 +668,9 @@ pub struct Friendship {
}
pub async fn friendship(client: &IgClient, user_id: &str) -> Result<Friendship, IgError> {
- let v = client.get_json(&format!("/api/v1/friendships/show/{}/", user_id), &[]).await?;
+ let v = client
+ .get_json(&format!("/api/v1/friendships/show/{}/", user_id), &[])
+ .await?;
Ok(Friendship {
following: b(&v, "following"),
followed_by: b(&v, "followed_by"),
diff --git a/src-tauri/omniget-core/src/core/tools/instagram/publish.rs b/src-tauri/omniget-core/src/core/tools/instagram/publish.rs
index 47823917..fc2ce9a4 100644
--- a/src-tauri/omniget-core/src/core/tools/instagram/publish.rs
+++ b/src-tauri/omniget-core/src/core/tools/instagram/publish.rs
@@ -75,7 +75,10 @@ fn png_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
if bytes.len() < 24 || &bytes[..8] != b"\x89PNG\r\n\x1a\n" {
return None;
}
- Some((u32::from_be_bytes(bytes[16..20].try_into().ok()?), u32::from_be_bytes(bytes[20..24].try_into().ok()?)))
+ Some((
+ u32::from_be_bytes(bytes[16..20].try_into().ok()?),
+ u32::from_be_bytes(bytes[20..24].try_into().ok()?),
+ ))
}
/// Garante JPEG (o upload web só aceita JPEG); converte PNG/WebP/HEIC pelo ffmpeg.
@@ -97,29 +100,53 @@ async fn as_jpeg(path: &Path) -> anyhow::Result<(Vec<u8>, u32, u32)> {
.output()
.await?;
if !status.status.success() {
- return Err(anyhow!("ffmpeg: {}", String::from_utf8_lossy(&status.stderr).trim()));
+ return Err(anyhow!(
+ "ffmpeg: {}",
+ String::from_utf8_lossy(&status.stderr).trim()
+ ));
}
let bytes = tokio::fs::read(&out).await?;
let _ = tokio::fs::remove_file(&out).await;
- let (w, h) = jpeg_dimensions(&bytes).or_else(|| png_dimensions(&bytes)).unwrap_or((1080, 1080));
+ let (w, h) = jpeg_dimensions(&bytes)
+ .or_else(|| png_dimensions(&bytes))
+ .unwrap_or((1080, 1080));
Ok((bytes, w, h))
}
-async fn rupload_photo(client: &IgClient, bytes: Vec<u8>, w: u32, h: u32, uid: &str, params_extra: &[(&str, Value)]) -> Result<(), IgError> {
+async fn rupload_photo(
+ client: &IgClient,
+ bytes: Vec<u8>,
+ w: u32,
+ h: u32,
+ uid: &str,
+ params_extra: &[(&str, Value)],
+) -> Result<(), IgError> {
let name = format!("fb_uploader_{}", uid);
let mut params = serde_json::json!({"media_type": 1, "upload_id": uid, "upload_media_height": h, "upload_media_width": w});
for (k, v) in params_extra {
params[k] = v.clone();
}
let mut h = HeaderMap::new();
- h.insert("X-Instagram-Rupload-Params", HeaderValue::from_str(&params.to_string()).map_err(|e| IgError::Other(e.to_string()))?);
+ h.insert(
+ "X-Instagram-Rupload-Params",
+ HeaderValue::from_str(&params.to_string()).map_err(|e| IgError::Other(e.to_string()))?,
+ );
h.insert("X-Entity-Name", HeaderValue::from_str(&name).unwrap());
- h.insert("X-Entity-Length", HeaderValue::from_str(&bytes.len().to_string()).unwrap());
+ h.insert(
+ "X-Entity-Length",
+ HeaderValue::from_str(&bytes.len().to_string()).unwrap(),
+ );
h.insert("X-Entity-Type", HeaderValue::from_static("image/jpeg"));
h.insert("Offset", HeaderValue::from_static("0"));
h.insert("Content-Type", HeaderValue::from_static("image/jpeg"));
h.insert("X-Instagram-AJAX", HeaderValue::from_static("1"));
- let json = client.post_raw(&format!("{}/rupload_igphoto/{}", super::BASE, name), h, bytes).await?;
+ let json = client
+ .post_raw(
+ &format!("{}/rupload_igphoto/{}", super::BASE, name),
+ h,
+ bytes,
+ )
+ .await?;
if s(&json, "status") != "ok" {
return Err(IgError::Other(format!("upload da foto: {}", json)));
}
@@ -127,7 +154,16 @@ async fn rupload_photo(client: &IgClient, bytes: Vec<u8>, w: u32, h: u32, uid: &
}
#[allow(clippy::too_many_arguments)]
-async fn rupload_video(client: &IgClient, bytes: Vec<u8>, w: u32, h: u32, duration_ms: u64, uid: &str, reel: bool, story: bool) -> Result<(), IgError> {
+async fn rupload_video(
+ client: &IgClient,
+ bytes: Vec<u8>,
+ w: u32,
+ h: u32,
+ duration_ms: u64,
+ uid: &str,
+ reel: bool,
+ story: bool,
+) -> Result<(), IgError> {
let name = format!("fb_uploader_{}", uid);
let mut params = serde_json::json!({
"media_type": 2, "upload_id": uid, "upload_media_height": h, "upload_media_width": w,
@@ -142,14 +178,26 @@ async fn rupload_video(client: &IgClient, bytes: Vec<u8>, w: u32, h: u32, durati
params["for_album"] = Value::String("0".into());
}
let mut hd = HeaderMap::new();
- hd.insert("X-Instagram-Rupload-Params", HeaderValue::from_str(&params.to_string()).map_err(|e| IgError::Other(e.to_string()))?);
+ hd.insert(
+ "X-Instagram-Rupload-Params",
+ HeaderValue::from_str(&params.to_string()).map_err(|e| IgError::Other(e.to_string()))?,
+ );
hd.insert("X-Entity-Name", HeaderValue::from_str(&name).unwrap());
- hd.insert("X-Entity-Length", HeaderValue::from_str(&bytes.len().to_string()).unwrap());
+ hd.insert(
+ "X-Entity-Length",
+ HeaderValue::from_str(&bytes.len().to_string()).unwrap(),
+ );
hd.insert("X-Entity-Type", HeaderValue::from_static("video/mp4"));
hd.insert("Offset", HeaderValue::from_static("0"));
hd.insert("Content-Type", HeaderValue::from_static("video/mp4"));
hd.insert("X-Instagram-AJAX", HeaderValue::from_static("1"));
- let json = client.post_raw(&format!("{}/rupload_igvideo/{}", super::BASE, name), hd, bytes).await?;
+ let json = client
+ .post_raw(
+ &format!("{}/rupload_igvideo/{}", super::BASE, name),
+ hd,
+ bytes,
+ )
+ .await?;
if s(&json, "status") != "ok" {
return Err(IgError::Other(format!("upload do video: {}", json)));
}
@@ -158,9 +206,21 @@ async fn rupload_video(client: &IgClient, bytes: Vec<u8>, w: u32, h: u32, durati
async fn probe_video(path: &Path) -> anyhow::Result<(u32, u32, u64)> {
let info = crate::core::ffmpeg::probe(path).await?;
- let stream = info.streams.iter().find(|s| s.codec_type == "video").ok_or_else(|| anyhow!("o arquivo nao tem faixa de video"))?;
- let duration = if info.duration_seconds > 0.0 { info.duration_seconds } else { stream.duration_seconds.unwrap_or(0.0) };
- Ok((stream.width.unwrap_or(1080), stream.height.unwrap_or(1920), (duration * 1000.0) as u64))
+ let stream = info
+ .streams
+ .iter()
+ .find(|s| s.codec_type == "video")
+ .ok_or_else(|| anyhow!("o arquivo nao tem faixa de video"))?;
+ let duration = if info.duration_seconds > 0.0 {
+ info.duration_seconds
+ } else {
+ stream.duration_seconds.unwrap_or(0.0)
+ };
+ Ok((
+ stream.width.unwrap_or(1080),
+ stream.height.unwrap_or(1920),
+ (duration * 1000.0) as u64,
+ ))
}
/// Extrai um frame como capa do vídeo.
@@ -168,7 +228,15 @@ async fn cover_frame(path: &Path) -> anyhow::Result<(Vec<u8>, u32, u32)> {
let ffmpeg = crate::core::dependencies::ensure_ffmpeg().await?;
let out = super::super::temp_dir().join(format!("ig-cover-{}.jpg", upload_id()));
let status = crate::core::process::command(&ffmpeg)
- .args(["-y", "-hide_banner", "-loglevel", "error", "-ss", "0.5", "-i"])
+ .args([
+ "-y",
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-ss",
+ "0.5",
+ "-i",
+ ])
.arg(path)
.args(["-frames:v", "1", "-q:v", "2", "-pix_fmt", "yuvj420p"])
.arg(&out)
@@ -178,7 +246,10 @@ async fn cover_frame(path: &Path) -> anyhow::Result<(Vec<u8>, u32, u32)> {
.output()
.await?;
if !status.status.success() {
- return Err(anyhow!("ffmpeg: {}", String::from_utf8_lossy(&status.stderr).trim()));
+ return Err(anyhow!(
+ "ffmpeg: {}",
+ String::from_utf8_lossy(&status.stderr).trim()
+ ));
}
let bytes = tokio::fs::read(&out).await?;
let _ = tokio::fs::remove_file(&out).await;
@@ -189,7 +260,15 @@ async fn cover_frame(path: &Path) -> anyhow::Result<(Vec<u8>, u32, u32)> {
fn result_of(json: &Value) -> PublishResult {
let media = json.get("media").cloned().unwrap_or(Value::Null);
let code = s(&media, "code");
- PublishResult { media_id: s(&media, "pk"), url: if code.is_empty() { String::new() } else { format!("{}/p/{}/", super::BASE, code) }, code }
+ PublishResult {
+ media_id: s(&media, "pk"),
+ url: if code.is_empty() {
+ String::new()
+ } else {
+ format!("{}/p/{}/", super::BASE, code)
+ },
+ code,
+ }
}
fn common_form(req: &PublishRequest, uid: &str) -> Vec<(&'static str, String)> {
@@ -197,8 +276,14 @@ fn common_form(req: &PublishRequest, uid: &str) -> Vec<(&'static str, String)> {
("upload_id", uid.to_string()),
("caption", req.caption.clone()),
("source_type", "library".into()),
- ("disable_comments", if req.disable_comments { "1" } else { "0" }.into()),
- ("like_and_view_counts_disabled", if req.hide_like_counts { "1" } else { "0" }.into()),
+ (
+ "disable_comments",
+ if req.disable_comments { "1" } else { "0" }.into(),
+ ),
+ (
+ "like_and_view_counts_disabled",
+ if req.hide_like_counts { "1" } else { "0" }.into(),
+ ),
("custom_accessibility_caption", req.alt_text.clone()),
("usertags", "".into()),
("archive_only", "false".into()),
@@ -207,44 +292,97 @@ fn common_form(req: &PublishRequest, uid: &str) -> Vec<(&'static str, String)> {
}
/// Publica pela sessão web.
-pub async fn publish_web(client: &IgClient, req: &PublishRequest, progress: &super::super::ProgressFn, job: &str) -> anyhow::Result<PublishResult> {
+pub async fn publish_web(
+ client: &IgClient,
+ req: &PublishRequest,
+ progress: &super::super::ProgressFn,
+ job: &str,
+) -> anyhow::Result<PublishResult> {
let id = format!("ig:{}", job);
if req.files.is_empty() {
return Err(anyhow!("escolha pelo menos um arquivo"));
}
- let report = |stage: &str, done: u64, total: u64| super::super::report(progress, &id, stage, done, Some(total), None);
+ let report = |stage: &str, done: u64, total: u64| {
+ super::super::report(progress, &id, stage, done, Some(total), None)
+ };
let m = |e: IgError| anyhow!(e.to_string());
match req.kind.as_str() {
"photo" => {
report("upload", 0, 2);
let uid = upload_id();
let (bytes, w, h) = as_jpeg(Path::new(&req.files[0])).await?;
- rupload_photo(client, bytes, w, h, &uid, &[]).await.map_err(m)?;
+ rupload_photo(client, bytes, w, h, &uid, &[])
+ .await
+ .map_err(m)?;
report("configure", 1, 2);
- let json = client.post_form("/api/v1/media/configure/", &common_form(req, &uid)).await.map_err(m)?;
+ let json = client
+ .post_form("/api/v1/media/configure/", &common_form(req, &uid))
+ .await
+ .map_err(m)?;
report("done", 2, 2);
Ok(result_of(&json))
}
"story" => {
let path = Path::new(&req.files[0]);
let uid = upload_id();
- let is_video = matches!(path.extension().and_then(|e| e.to_str()).map(|e| e.to_lowercase()).as_deref(), Some("mp4" | "mov" | "m4v" | "webm"));
+ let is_video = matches!(
+ path.extension()
+ .and_then(|e| e.to_str())
+ .map(|e| e.to_lowercase())
+ .as_deref(),
+ Some("mp4" | "mov" | "m4v" | "webm")
+ );
report("upload", 0, 2);
if is_video {
let (w, h, dur) = probe_video(path).await?;
let bytes = tokio::fs::read(path).await?;
- rupload_video(client, bytes, w, h, dur, &uid, false, true).await.map_err(m)?;
+ rupload_video(client, bytes, w, h, dur, &uid, false, true)
+ .await
+ .map_err(m)?;
let (cover, cw, ch) = cover_frame(path).await?;
- rupload_photo(client, cover, cw, ch, &uid, &[("media_type", Value::from(2))]).await.map_err(m)?;
+ rupload_photo(
+ client,
+ cover,
+ cw,
+ ch,
+ &uid,
+ &[("media_type", Value::from(2))],
+ )
+ .await
+ .map_err(m)?;
report("configure", 1, 2);
- let json = client.post_form("/api/v1/media/configure_to_story/?video=1", &[("upload_id", uid.clone()), ("source_type", "library".into()), ("configure_mode", "1".into()), ("video_result", "".into()), ("length", (dur as f64 / 1000.0).to_string())]).await.map_err(m)?;
+ let json = client
+ .post_form(
+ "/api/v1/media/configure_to_story/?video=1",
+ &[
+ ("upload_id", uid.clone()),
+ ("source_type", "library".into()),
+ ("configure_mode", "1".into()),
+ ("video_result", "".into()),
+ ("length", (dur as f64 / 1000.0).to_string()),
+ ],
+ )
+ .await
+ .map_err(m)?;
report("done", 2, 2);
Ok(result_of(&json))
} else {
let (bytes, w, h) = as_jpeg(path).await?;
- rupload_photo(client, bytes, w, h, &uid, &[]).await.map_err(m)?;
+ rupload_photo(client, bytes, w, h, &uid, &[])
+ .await
+ .map_err(m)?;
report("configure", 1, 2);
- let json = client.post_form("/api/v1/media/configure_to_story/", &[("upload_id", uid.clone()), ("source_type", "library".into()), ("configure_mode", "1".into())]).await.map_err(m)?;
+ let json = client
+ .post_form(
+ "/api/v1/media/configure_to_story/",
+ &[
+ ("upload_id", uid.clone()),
+ ("source_type", "library".into()),
+ ("configure_mode", "1".into()),
+ ],
+ )
+ .await
+ .map_err(m)?;
report("done", 2, 2);
Ok(result_of(&json))
}
@@ -255,26 +393,60 @@ pub async fn publish_web(client: &IgClient, req: &PublishRequest, progress: &sup
report("upload", 0, 3);
let (w, h, dur) = probe_video(path).await?;
let bytes = tokio::fs::read(path).await?;
- rupload_video(client, bytes, w, h, dur, &uid, true, false).await.map_err(m)?;
+ rupload_video(client, bytes, w, h, dur, &uid, true, false)
+ .await
+ .map_err(m)?;
report("cover", 1, 3);
let (cover, cw, ch) = cover_frame(path).await?;
- rupload_photo(client, cover, cw, ch, &uid, &[("media_type", Value::from(2))]).await.map_err(m)?;
+ rupload_photo(
+ client,
+ cover,
+ cw,
+ ch,
+ &uid,
+ &[("media_type", Value::from(2))],
+ )
+ .await
+ .map_err(m)?;
report("configure", 2, 3);
let mut form = common_form(req, &uid);
form.push(("video_format", "video/mp4".into()));
form.push(("length", (dur as f64 / 1000.0).to_string()));
- form.push(("clips_share_to_feed", if req.share_to_feed || req.kind == "video" { "1" } else { "0" }.into()));
- form.push(("share_to_feed", if req.share_to_feed || req.kind == "video" { "1" } else { "0" }.into()));
+ form.push((
+ "clips_share_to_feed",
+ if req.share_to_feed || req.kind == "video" {
+ "1"
+ } else {
+ "0"
+ }
+ .into(),
+ ));
+ form.push((
+ "share_to_feed",
+ if req.share_to_feed || req.kind == "video" {
+ "1"
+ } else {
+ "0"
+ }
+ .into(),
+ ));
// O Instagram pode ainda estar transcodificando: tenta algumas vezes.
let mut last = None;
for attempt in 0..6 {
- match client.post_form("/api/v1/media/configure_to_clips/?video=1", &form).await {
+ match client
+ .post_form("/api/v1/media/configure_to_clips/?video=1", &form)
+ .await
+ {
Ok(json) if s(&json, "status") == "ok" => {
report("done", 3, 3);
return Ok(result_of(&json));
}
Ok(json) => last = Some(anyhow!("configure: {}", json)),
- Err(IgError::Other(e)) if e.contains("Transcode") || e.contains("not ready") || e.contains("202") => {
+ Err(IgError::Other(e))
+ if e.contains("Transcode")
+ || e.contains("not ready")
+ || e.contains("202") =>
+ {
last = Some(anyhow!(e));
}
Err(e) => return Err(m(e)),
@@ -294,17 +466,46 @@ pub async fn publish_web(client: &IgClient, req: &PublishRequest, progress: &sup
report("upload", i as u64, total);
let path = Path::new(f);
let uid = format!("{}{}", upload_id(), i);
- let is_video = matches!(path.extension().and_then(|e| e.to_str()).map(|e| e.to_lowercase()).as_deref(), Some("mp4" | "mov" | "m4v" | "webm"));
+ let is_video = matches!(
+ path.extension()
+ .and_then(|e| e.to_str())
+ .map(|e| e.to_lowercase())
+ .as_deref(),
+ Some("mp4" | "mov" | "m4v" | "webm")
+ );
if is_video {
let (w, h, dur) = probe_video(path).await?;
let bytes = tokio::fs::read(path).await?;
- rupload_video(client, bytes, w, h, dur, &uid, false, false).await.map_err(m)?;
+ rupload_video(client, bytes, w, h, dur, &uid, false, false)
+ .await
+ .map_err(m)?;
let (cover, cw, ch) = cover_frame(path).await?;
- rupload_photo(client, cover, cw, ch, &uid, &[("media_type", Value::from(2)), ("is_sidecar", Value::from("1"))]).await.map_err(m)?;
+ rupload_photo(
+ client,
+ cover,
+ cw,
+ ch,
+ &uid,
+ &[
+ ("media_type", Value::from(2)),
+ ("is_sidecar", Value::from("1")),
+ ],
+ )
+ .await
+ .map_err(m)?;
children.push(serde_json::json!({"upload_id": uid, "source_type": "library", "video_result": "", "length": dur as f64 / 1000.0}));
} else {
let (bytes, w, h) = as_jpeg(path).await?;
- rupload_photo(client, bytes, w, h, &uid, &[("is_sidecar", Value::from("1"))]).await.map_err(m)?;
+ rupload_photo(
+ client,
+ bytes,
+ w,
+ h,
+ &uid,
+ &[("is_sidecar", Value::from("1"))],
+ )
+ .await
+ .map_err(m)?;
children.push(serde_json::json!({"upload_id": uid, "source_type": "library"}));
}
super::sleep_jitter(500, 1500).await;
@@ -312,8 +513,14 @@ pub async fn publish_web(client: &IgClient, req: &PublishRequest, progress: &sup
report("configure", total - 1, total);
let mut form = common_form(req, &sidecar_id);
form.push(("client_sidecar_id", sidecar_id.clone()));
- form.push(("children_metadata", serde_json::to_string(&children).unwrap_or_default()));
- let json = client.post_form("/api/v1/media/configure_sidecar/", &form).await.map_err(m)?;
+ form.push((
+ "children_metadata",
+ serde_json::to_string(&children).unwrap_or_default(),
+ ));
+ let json = client
+ .post_form("/api/v1/media/configure_sidecar/", &form)
+ .await
+ .map_err(m)?;
report("done", total, total);
Ok(result_of(&json))
}
@@ -331,11 +538,20 @@ pub struct GraphAuth {
const GRAPH: &str = "https://graph.facebook.com/v21.0";
-async fn graph_post(http: &reqwest::Client, url: &str, form: &[(&str, String)]) -> anyhow::Result<Value> {
+async fn graph_post(
+ http: &reqwest::Client,
+ url: &str,
+ form: &[(&str, String)],
+) -> anyhow::Result<Value> {
let resp = http.post(url).form(form).send().await?;
let json: Value = resp.json().await?;
if let Some(err) = json.get("error") {
- return Err(anyhow!("Graph API: {}", err.get("message").and_then(|m| m.as_str()).unwrap_or("erro")));
+ return Err(anyhow!(
+ "Graph API: {}",
+ err.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("erro")
+ ));
}
Ok(json)
}
@@ -343,14 +559,26 @@ async fn graph_post(http: &reqwest::Client, url: &str, form: &[(&str, String)])
async fn graph_get(http: &reqwest::Client, url: &str) -> anyhow::Result<Value> {
let json: Value = http.get(url).send().await?.json().await?;
if let Some(err) = json.get("error") {
- return Err(anyhow!("Graph API: {}", err.get("message").and_then(|m| m.as_str()).unwrap_or("erro")));
+ return Err(anyhow!(
+ "Graph API: {}",
+ err.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("erro")
+ ));
}
Ok(json)
}
async fn wait_container(http: &reqwest::Client, id: &str, token: &str) -> anyhow::Result<()> {
for _ in 0..40 {
- let st = graph_get(http, &format!("{}/{}?fields=status_code,status&access_token={}", GRAPH, id, token)).await?;
+ let st = graph_get(
+ http,
+ &format!(
+ "{}/{}?fields=status_code,status&access_token={}",
+ GRAPH, id, token
+ ),
+ )
+ .await?;
match s(&st, "status_code").as_str() {
"FINISHED" => return Ok(()),
"ERROR" | "EXPIRED" => return Err(anyhow!("o container falhou: {}", s(&st, "status"))),
@@ -361,7 +589,12 @@ async fn wait_container(http: &reqwest::Client, id: &str, token: &str) -> anyhow
}
/// Publica pela API oficial. `req.files` são URLs públicas.
-pub async fn publish_graph(auth: &GraphAuth, req: &PublishRequest, progress: &super::super::ProgressFn, job: &str) -> anyhow::Result<PublishResult> {
+pub async fn publish_graph(
+ auth: &GraphAuth,
+ req: &PublishRequest,
+ progress: &super::super::ProgressFn,
+ job: &str,
+) -> anyhow::Result<PublishResult> {
let id = format!("ig:{}", job);
let http = super::super::client()?;
let token = auth.access_token.trim().to_string();
@@ -370,17 +603,29 @@ pub async fn publish_graph(auth: &GraphAuth, req: &PublishRequest, progress: &su
return Err(anyhow!("informe o token e o ID da conta do Instagram"));
}
if req.files.is_empty() || !req.files.iter().all(|f| f.starts_with("http")) {
- return Err(anyhow!("a API oficial so aceita URLs publicas (https://…) para os arquivos"));
+ return Err(anyhow!(
+ "a API oficial so aceita URLs publicas (https://…) para os arquivos"
+ ));
}
let media_url = format!("{}/{}/media", GRAPH, user);
- let is_video = |f: &str| f.split('?').next().unwrap_or(f).to_lowercase().ends_with(".mp4") || f.to_lowercase().ends_with(".mov");
+ let is_video = |f: &str| {
+ f.split('?')
+ .next()
+ .unwrap_or(f)
+ .to_lowercase()
+ .ends_with(".mp4")
+ || f.to_lowercase().ends_with(".mov")
+ };
let creation_id = match req.kind.as_str() {
"carousel" => {
let total = req.files.len() as u64 + 2;
let mut children = Vec::new();
for (i, f) in req.files.iter().enumerate() {
super::super::report(progress, &id, "container", i as u64, Some(total), None);
- let mut form = vec![("is_carousel_item", "true".to_string()), ("access_token", token.clone())];
+ let mut form = vec![
+ ("is_carousel_item", "true".to_string()),
+ ("access_token", token.clone()),
+ ];
if is_video(f) {
form.push(("media_type", "VIDEO".into()));
form.push(("video_url", f.clone()));
@@ -392,22 +637,50 @@ pub async fn publish_graph(auth: &GraphAuth, req: &PublishRequest, progress: &su
wait_container(&http, &cid, &token).await?;
children.push(cid);
}
- let c = graph_post(&http, &media_url, &[("media_type", "CAROUSEL".into()), ("children", children.join(",")), ("caption", req.caption.clone()), ("access_token", token.clone())]).await?;
+ let c = graph_post(
+ &http,
+ &media_url,
+ &[
+ ("media_type", "CAROUSEL".into()),
+ ("children", children.join(",")),
+ ("caption", req.caption.clone()),
+ ("access_token", token.clone()),
+ ],
+ )
+ .await?;
s(&c, "id")
}
kind => {
super::super::report(progress, &id, "container", 0, Some(3), None);
let f = &req.files[0];
- let mut form = vec![("caption", req.caption.clone()), ("access_token", token.clone())];
+ let mut form = vec![
+ ("caption", req.caption.clone()),
+ ("access_token", token.clone()),
+ ];
match kind {
"story" => {
form.push(("media_type", "STORIES".into()));
- form.push((if is_video(f) { "video_url" } else { "image_url" }, f.clone()));
+ form.push((
+ if is_video(f) {
+ "video_url"
+ } else {
+ "image_url"
+ },
+ f.clone(),
+ ));
}
"reel" | "video" => {
form.push(("media_type", "REELS".into()));
form.push(("video_url", f.clone()));
- form.push(("share_to_feed", if req.share_to_feed || kind == "video" { "true" } else { "false" }.into()));
+ form.push((
+ "share_to_feed",
+ if req.share_to_feed || kind == "video" {
+ "true"
+ } else {
+ "false"
+ }
+ .into(),
+ ));
}
_ => form.push(("image_url", f.clone())),
}
@@ -418,11 +691,31 @@ pub async fn publish_graph(auth: &GraphAuth, req: &PublishRequest, progress: &su
super::super::report(progress, &id, "processing", 1, Some(3), None);
wait_container(&http, &creation_id, &token).await?;
super::super::report(progress, &id, "publish", 2, Some(3), None);
- let p = graph_post(&http, &format!("{}/{}/media_publish", GRAPH, user), &[("creation_id", creation_id), ("access_token", token.clone())]).await?;
+ let p = graph_post(
+ &http,
+ &format!("{}/{}/media_publish", GRAPH, user),
+ &[
+ ("creation_id", creation_id),
+ ("access_token", token.clone()),
+ ],
+ )
+ .await?;
let media_id = s(&p, "id");
- let link = graph_get(&http, &format!("{}/{}?fields=permalink,shortcode&access_token={}", GRAPH, media_id, token)).await.unwrap_or(Value::Null);
+ let link = graph_get(
+ &http,
+ &format!(
+ "{}/{}?fields=permalink,shortcode&access_token={}",
+ GRAPH, media_id, token
+ ),
+ )
+ .await
+ .unwrap_or(Value::Null);
super::super::report(progress, &id, "done", 3, Some(3), None);
- Ok(PublishResult { media_id, code: s(&link, "shortcode"), url: s(&link, "permalink") })
+ Ok(PublishResult {
+ media_id,
+ code: s(&link, "shortcode"),
+ url: s(&link, "permalink"),
+ })
}
// ── Agendamento ──────────────────────────────────────────────────────────
@@ -491,7 +784,10 @@ pub fn schedule_update(post: &ScheduledPost) -> anyhow::Result<()> {
/// Próximo agendamento vencido e ainda pendente.
pub fn schedule_due(now: i64) -> Option<ScheduledPost> {
- schedule_list().posts.into_iter().find(|p| p.status == "pending" && p.run_at <= now)
+ schedule_list()
+ .posts
+ .into_iter()
+ .find(|p| p.status == "pending" && p.run_at <= now)
}
#[cfg(test)]
@@ -501,7 +797,10 @@ mod tests {
#[test]
fn jpeg_dims() {
// JPEG mínimo: SOI + SOF0 (altura 2, largura 3).
- let bytes = [0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x0B, 0x08, 0x00, 0x02, 0x00, 0x03, 0x01, 0x01, 0x11, 0x00, 0xFF, 0xD9];
+ let bytes = [
+ 0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x0B, 0x08, 0x00, 0x02, 0x00, 0x03, 0x01, 0x01, 0x11,
+ 0x00, 0xFF, 0xD9,
+ ];
assert_eq!(jpeg_dimensions(&bytes), Some((3, 2)));
assert_eq!(jpeg_dimensions(b"nope"), None);
}
diff --git a/src-tauri/omniget-core/src/core/tools/instagram/social.rs b/src-tauri/omniget-core/src/core/tools/instagram/social.rs
index 00d3d2f9..41d0938e 100644
--- a/src-tauri/omniget-core/src/core/tools/instagram/social.rs
+++ b/src-tauri/omniget-core/src/core/tools/instagram/social.rs
@@ -26,12 +26,19 @@ fn parse_comment(v: &Value) -> Comment {
let mentions = text
.split_whitespace()
.filter_map(|w| w.strip_prefix('@'))
- .map(|w| w.trim_end_matches(|c: char| !c.is_alphanumeric() && c != '_' && c != '.').to_lowercase())
+ .map(|w| {
+ w.trim_end_matches(|c: char| !c.is_alphanumeric() && c != '_' && c != '.')
+ .to_lowercase()
+ })
.filter(|w| !w.is_empty())
.collect();
Comment {
pk: s(v, "pk"),
- created_at: v.get("created_at_utc").or(v.get("created_at")).and_then(|x| x.as_i64()).unwrap_or(0),
+ created_at: v
+ .get("created_at_utc")
+ .or(v.get("created_at"))
+ .and_then(|x| x.as_i64())
+ .unwrap_or(0),
user: v.get("user").map(MiniUser::from_value).unwrap_or_default(),
like_count: u(v, "comment_like_count"),
reply_count: u(v, "child_comment_count"),
@@ -41,18 +48,34 @@ fn parse_comment(v: &Value) -> Comment {
}
/// `GET /api/v1/media/{pk}/comments/` paginado por `min_id`.
-pub async fn comments(client: &IgClient, media_pk: &str, limit: usize, flag: &AtomicBool, progress: &super::super::ProgressFn, job: &str) -> Result<Vec<Comment>, IgError> {
+pub async fn comments(
+ client: &IgClient,
+ media_pk: &str,
+ limit: usize,
+ flag: &AtomicBool,
+ progress: &super::super::ProgressFn,
+ job: &str,
+) -> Result<Vec<Comment>, IgError> {
let mut out = Vec::new();
let mut min_id: Option<String> = None;
let id = format!("ig:{}", job);
let mut seen: HashSet<String> = HashSet::new();
loop {
- let mut q = vec![("can_support_threading", "true".to_string()), ("permalink_enabled", "false".to_string())];
+ let mut q = vec![
+ ("can_support_threading", "true".to_string()),
+ ("permalink_enabled", "false".to_string()),
+ ];
if let Some(m) = &min_id {
q.push(("min_id", m.clone()));
}
- let json = client.get_json(&format!("/api/v1/media/{}/comments/", media_pk), &q).await?;
- let list = json.get("comments").and_then(|c| c.as_array()).cloned().unwrap_or_default();
+ let json = client
+ .get_json(&format!("/api/v1/media/{}/comments/", media_pk), &q)
+ .await?;
+ let list = json
+ .get("comments")
+ .and_then(|c| c.as_array())
+ .cloned()
+ .unwrap_or_default();
let mut added = 0;
for c in &list {
let cm = parse_comment(c);
@@ -61,10 +84,30 @@ pub async fn comments(client: &IgClient, media_pk: &str, limit: usize, flag: &At
added += 1;
}
}
- super::super::report(progress, &id, "comments", out.len() as u64, if limit > 0 { Some(limit as u64) } else { u(&json, "comment_count").checked_sub(0) }, None);
- min_id = json.get("next_min_id").and_then(|m| match m { Value::String(x) => Some(x.clone()), Value::Number(n) => Some(n.to_string()), _ => None });
+ super::super::report(
+ progress,
+ &id,
+ "comments",
+ out.len() as u64,
+ if limit > 0 {
+ Some(limit as u64)
+ } else {
+ u(&json, "comment_count").checked_sub(0)
+ },
+ None,
+ );
+ min_id = json.get("next_min_id").and_then(|m| match m {
+ Value::String(x) => Some(x.clone()),
+ Value::Number(n) => Some(n.to_string()),
+ _ => None,
+ });
let more = b(&json, "has_more_comments") || b(&json, "has_more_headload_comments");
- if added == 0 || !more || min_id.is_none() || (limit > 0 && out.len() >= limit) || super::cancelled(flag) {
+ if added == 0
+ || !more
+ || min_id.is_none()
+ || (limit > 0 && out.len() >= limit)
+ || super::cancelled(flag)
+ {
break;
}
client.pause().await;
@@ -77,8 +120,14 @@ pub async fn comments(client: &IgClient, media_pk: &str, limit: usize, flag: &At
/// `GET /api/v1/media/{pk}/likers/` (uma resposta só, até ~1000 contas).
pub async fn likers(client: &IgClient, media_pk: &str) -> Result<(u64, Vec<MiniUser>), IgError> {
- let json = client.get_json(&format!("/api/v1/media/{}/likers/", media_pk), &[]).await?;
- let users = json.get("users").and_then(|u| u.as_array()).map(|a| a.iter().map(MiniUser::from_value).collect()).unwrap_or_default();
+ let json = client
+ .get_json(&format!("/api/v1/media/{}/likers/", media_pk), &[])
+ .await?;
+ let users = json
+ .get("users")
+ .and_then(|u| u.as_array())
+ .map(|a| a.iter().map(MiniUser::from_value).collect())
+ .unwrap_or_default();
Ok((u(&json, "user_count"), users))
}
@@ -105,7 +154,13 @@ pub struct GiveawayResult {
pub fn giveaway(comments: &[Comment], rules: &GiveawayRules) -> GiveawayResult {
let keyword = rules.keyword.trim().to_lowercase();
- let excluded: HashSet<String> = rules.exclude.iter().map(|e| e.trim_start_matches('@').to_lowercase()).chain(std::iter::once(rules.owner_username.to_lowercase())).filter(|e| !e.is_empty()).collect();
+ let excluded: HashSet<String> = rules
+ .exclude
+ .iter()
+ .map(|e| e.trim_start_matches('@').to_lowercase())
+ .chain(std::iter::once(rules.owner_username.to_lowercase()))
+ .filter(|e| !e.is_empty())
+ .collect();
let mut seen_users: HashSet<String> = HashSet::new();
let mut pool: Vec<Comment> = Vec::new();
for c in comments {
@@ -130,7 +185,9 @@ pub fn giveaway(comments: &[Comment], rules: &GiveawayRules) -> GiveawayResult {
// resultado poder ser reproduzido pela semente exibida.
let mut state = seed | 1;
let mut next = move || {
- state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ state = state
+ .wrapping_mul(6364136223846793005)
+ .wrapping_add(1442695040888963407);
state >> 33
};
for i in (1..pool.len()).rev() {
@@ -138,7 +195,11 @@ pub fn giveaway(comments: &[Comment], rules: &GiveawayRules) -> GiveawayResult {
pool.swap(i, j);
}
pool.truncate(rules.winners.max(1));
- GiveawayResult { eligible, winners: pool, seed }
+ GiveawayResult {
+ eligible,
+ winners: pool,
+ seed,
+ }
}
#[derive(Debug, Clone, Serialize)]
@@ -153,12 +214,18 @@ pub struct TagInfo {
/// `GET /api/v1/tags/web_info/?tag_name=`
pub async fn tag_info(client: &IgClient, tag: &str) -> Result<TagInfo, IgError> {
let tag = tag.trim().trim_start_matches('#').to_lowercase();
- let json = client.get_json("/api/v1/tags/web_info/", &[("tag_name", tag.clone())]).await?;
+ let json = client
+ .get_json("/api/v1/tags/web_info/", &[("tag_name", tag.clone())])
+ .await?;
let d = json.get("data").cloned().unwrap_or(json.clone());
Ok(TagInfo {
name: {
let n = s(&d, "name");
- if n.is_empty() { tag } else { n }
+ if n.is_empty() {
+ tag
+ } else {
+ n
+ }
},
media_count: u(&d, "media_count"),
formatted_media_count: s(&d, "formatted_media_count"),
@@ -168,35 +235,77 @@ pub async fn tag_info(client: &IgClient, tag: &str) -> Result<TagInfo, IgError>
}
/// `POST /api/v1/tags/{tag}/sections/` — `tab` = "recent" | "top".
-pub async fn tag_media(client: &IgClient, tag: &str, tab: &str, limit: usize, flag: &AtomicBool, progress: &super::super::ProgressFn, job: &str) -> Result<Vec<MediaItem>, IgError> {
+pub async fn tag_media(
+ client: &IgClient,
+ tag: &str,
+ tab: &str,
+ limit: usize,
+ flag: &AtomicBool,
+ progress: &super::super::ProgressFn,
+ job: &str,
+) -> Result<Vec<MediaItem>, IgError> {
let tag = tag.trim().trim_start_matches('#').to_lowercase();
let mut out = Vec::new();
let mut max_id: Option<String> = None;
let mut page: Option<String> = None;
let id = format!("ig:{}", job);
loop {
- let mut form = vec![("include_persistent", "0".to_string()), ("surface", "grid".to_string()), ("tab", tab.to_string())];
+ let mut form = vec![
+ ("include_persistent", "0".to_string()),
+ ("surface", "grid".to_string()),
+ ("tab", tab.to_string()),
+ ];
if let Some(m) = &max_id {
form.push(("max_id", m.clone()));
}
if let Some(p) = &page {
form.push(("page", p.clone()));
}
- let json = client.post_form(&format!("/api/v1/tags/{}/sections/", tag), &form).await?;
- let sections = json.get("sections").and_then(|s| s.as_array()).cloned().unwrap_or_default();
+ let json = client
+ .post_form(&format!("/api/v1/tags/{}/sections/", tag), &form)
+ .await?;
+ let sections = json
+ .get("sections")
+ .and_then(|s| s.as_array())
+ .cloned()
+ .unwrap_or_default();
let mut added = 0;
for sec in &sections {
- for m in sec.get("layout_content").and_then(|l| l.get("medias")).and_then(|m| m.as_array()).cloned().unwrap_or_default() {
+ for m in sec
+ .get("layout_content")
+ .and_then(|l| l.get("medias"))
+ .and_then(|m| m.as_array())
+ .cloned()
+ .unwrap_or_default()
+ {
if let Some(item) = m.get("media").and_then(parse_item) {
out.push(item);
added += 1;
}
}
}
- super::super::report(progress, &id, "list", out.len() as u64, if limit > 0 { Some(limit as u64) } else { None }, None);
- max_id = json.get("next_max_id").and_then(|m| m.as_str()).map(|m| m.to_string());
- page = json.get("next_page").map(|p| match p { Value::String(x) => x.clone(), other => other.to_string() });
- if added == 0 || !b(&json, "more_available") || max_id.is_none() || (limit > 0 && out.len() >= limit) || super::cancelled(flag) {
+ super::super::report(
+ progress,
+ &id,
+ "list",
+ out.len() as u64,
+ if limit > 0 { Some(limit as u64) } else { None },
+ None,
+ );
+ max_id = json
+ .get("next_max_id")
+ .and_then(|m| m.as_str())
+ .map(|m| m.to_string());
+ page = json.get("next_page").map(|p| match p {
+ Value::String(x) => x.clone(),
+ other => other.to_string(),
+ });
+ if added == 0
+ || !b(&json, "more_available")
+ || max_id.is_none()
+ || (limit > 0 && out.len() >= limit)
+ || super::cancelled(flag)
+ {
break;
}
client.pause().await;
@@ -212,16 +321,35 @@ mod tests {
use super::*;
fn c(user: &str, text: &str) -> Comment {
- parse_comment(&serde_json::json!({"pk": text, "text": text, "created_at": 1, "user": {"pk": user, "username": user}}))
+ parse_comment(
+ &serde_json::json!({"pk": text, "text": text, "created_at": 1, "user": {"pk": user, "username": user}}),
+ )
}
#[test]
fn giveaway_filters() {
- let comments = vec![c("a", "eu quero @x @y"), c("a", "de novo @x @y"), c("owner", "obrigado @z @w"), c("b", "sem mencao"), c("c", "@um @dois"), c("d", "@um @dois #promo")];
- let rules = GiveawayRules { winners: 5, unique_users: true, min_mentions: 2, keyword: "".into(), exclude: vec![], owner_username: "owner".into() };
+ let comments = vec![
+ c("a", "eu quero @x @y"),
+ c("a", "de novo @x @y"),
+ c("owner", "obrigado @z @w"),
+ c("b", "sem mencao"),
+ c("c", "@um @dois"),
+ c("d", "@um @dois #promo"),
+ ];
+ let rules = GiveawayRules {
+ winners: 5,
+ unique_users: true,
+ min_mentions: 2,
+ keyword: "".into(),
+ exclude: vec![],
+ owner_username: "owner".into(),
+ };
let r = giveaway(&comments, &rules);
assert_eq!(r.eligible, 3);
- let rules2 = GiveawayRules { keyword: "#promo".into(), ..rules };
+ let rules2 = GiveawayRules {
+ keyword: "#promo".into(),
+ ..rules
+ };
assert_eq!(giveaway(&comments, &rules2).eligible, 1);
}
}
diff --git a/src-tauri/omniget-core/src/core/tools/jpeg_pdf.rs b/src-tauri/omniget-core/src/core/tools/jpeg_pdf.rs
index 4187e864..7d100baf 100644
--- a/src-tauri/omniget-core/src/core/tools/jpeg_pdf.rs
+++ b/src-tauri/omniget-core/src/core/tools/jpeg_pdf.rs
@@ -37,7 +37,11 @@ pub fn jpeg_info(data: &[u8]) -> anyhow::Result<JpegInfo> {
let height = u16::from_be_bytes([data[i + 5], data[i + 6]]) as u32;
let width = u16::from_be_bytes([data[i + 7], data[i + 8]]) as u32;
let components = data[i + 9];
- return Ok(JpegInfo { width, height, components });
+ return Ok(JpegInfo {
+ width,
+ height,
+ components,
+ });
}
i += 2 + len;
}
@@ -69,12 +73,23 @@ pub fn build_pdf(images: &[Vec<u8>]) -> anyhow::Result<Vec<u8>> {
out.extend_from_slice(body);
};
- push_obj(&mut out, &mut offsets, b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
- let kids: Vec<String> = (0..n_pages).map(|i| format!("{} 0 R", obj_page(i))).collect();
push_obj(
&mut out,
&mut offsets,
- format!("2 0 obj\n<< /Type /Pages /Kids [{}] /Count {} >>\nendobj\n", kids.join(" "), n_pages).as_bytes(),
+ b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n",
+ );
+ let kids: Vec<String> = (0..n_pages)
+ .map(|i| format!("{} 0 R", obj_page(i)))
+ .collect();
+ push_obj(
+ &mut out,
+ &mut offsets,
+ format!(
+ "2 0 obj\n<< /Type /Pages /Kids [{}] /Count {} >>\nendobj\n",
+ kids.join(" "),
+ n_pages
+ )
+ .as_bytes(),
);
for (i, img) in images.iter().enumerate() {
let info = jpeg_info(img)?;
@@ -128,7 +143,12 @@ pub fn build_pdf(images: &[Vec<u8>]) -> anyhow::Result<Vec<u8>> {
out.extend_from_slice(format!("{:010} 00000 n \n", off).as_bytes());
}
out.extend_from_slice(
- format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n", total_objs + 1, xref_at).as_bytes(),
+ format!(
+ "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
+ total_objs + 1,
+ xref_at
+ )
+ .as_bytes(),
);
Ok(out)
}
@@ -140,7 +160,9 @@ mod tests {
/// JPEG 1x1 mínimo (cinza) só com os marcadores que o parser precisa.
fn tiny_jpeg() -> Vec<u8> {
let mut v = vec![0xFF, 0xD8];
- v.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x0B, 0x08, 0x00, 0x02, 0x00, 0x03, 0x01, 0x01, 0x11, 0x00]);
+ v.extend_from_slice(&[
+ 0xFF, 0xC0, 0x00, 0x0B, 0x08, 0x00, 0x02, 0x00, 0x03, 0x01, 0x01, 0x11, 0x00,
+ ]);
v.extend_from_slice(&[0xFF, 0xD9]);
v
}
diff --git a/src-tauri/omniget-core/src/core/tools/kdeconnect.rs b/src-tauri/omniget-core/src/core/tools/kdeconnect.rs
index 4ae36454..81c897e6 100644
--- a/src-tauri/omniget-core/src/core/tools/kdeconnect.rs
+++ b/src-tauri/omniget-core/src/core/tools/kdeconnect.rs
@@ -33,9 +33,16 @@ async fn locate() -> Option<PathBuf> {
"/opt/homebrew/bin/kdeconnect-cli",
]
} else if cfg!(target_os = "windows") {
- &[r"C:\Program Files\KDE Connect\bin\kdeconnect-cli.exe", r"C:\Program Files\KDE\bin\kdeconnect-cli.exe"]
+ &[
+ r"C:\Program Files\KDE Connect\bin\kdeconnect-cli.exe",
+ r"C:\Program Files\KDE\bin\kdeconnect-cli.exe",
+ ]
} else {
- &["/usr/bin/kdeconnect-cli", "/usr/lib/kdeconnectd/kdeconnect-cli", "/app/bin/kdeconnect-cli"]
+ &[
+ "/usr/bin/kdeconnect-cli",
+ "/usr/lib/kdeconnectd/kdeconnect-cli",
+ "/app/bin/kdeconnect-cli",
+ ]
};
candidates.iter().map(PathBuf::from).find(|p| p.exists())
}
@@ -63,7 +70,12 @@ pub async fn status() -> KdeStatus {
"sudo apt install kdeconnect · flatpak install org.kde.kdeconnect".to_string()
};
let Some(bin) = locate().await else {
- return KdeStatus { installed: false, path: None, devices: vec![], install_hint: hint };
+ return KdeStatus {
+ installed: false,
+ path: None,
+ devices: vec![],
+ install_hint: hint,
+ };
};
let devices = crate::core::process::command(&bin)
.args(["-l"])
@@ -71,14 +83,27 @@ pub async fn status() -> KdeStatus {
.await
.map(|o| parse_devices(&String::from_utf8_lossy(&o.stdout)))
.unwrap_or_default();
- KdeStatus { installed: true, path: Some(bin.to_string_lossy().to_string()), devices, install_hint: hint }
+ KdeStatus {
+ installed: true,
+ path: Some(bin.to_string_lossy().to_string()),
+ devices,
+ install_hint: hint,
+ }
}
async fn run(args: &[&str]) -> anyhow::Result<String> {
- let bin = locate().await.ok_or_else(|| anyhow!("kdeconnect-cli nao encontrado"))?;
- let out = crate::core::process::command(&bin).args(args).output().await?;
+ let bin = locate()
+ .await
+ .ok_or_else(|| anyhow!("kdeconnect-cli nao encontrado"))?;
+ let out = crate::core::process::command(&bin)
+ .args(args)
+ .output()
+ .await?;
if !out.status.success() {
- return Err(anyhow!("kdeconnect-cli falhou: {}", String::from_utf8_lossy(&out.stderr).trim()));
+ return Err(anyhow!(
+ "kdeconnect-cli falhou: {}",
+ String::from_utf8_lossy(&out.stderr).trim()
+ ));
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
diff --git a/src-tauri/omniget-core/src/core/tools/manifest_dl.rs b/src-tauri/omniget-core/src/core/tools/manifest_dl.rs
index 2702b279..a7d3183f 100644
--- a/src-tauri/omniget-core/src/core/tools/manifest_dl.rs
+++ b/src-tauri/omniget-core/src/core/tools/manifest_dl.rs
@@ -31,7 +31,10 @@ pub fn headers_arg(opts: &ManifestOptions) -> Option<String> {
let mut h = Vec::new();
if !opts.referer.trim().is_empty() {
h.push(format!("Referer: {}", opts.referer.trim()));
- h.push(format!("Origin: {}", opts.referer.trim().trim_end_matches('/')));
+ h.push(format!(
+ "Origin: {}",
+ opts.referer.trim().trim_end_matches('/')
+ ));
}
if !opts.cookie.trim().is_empty() {
h.push(format!("Cookie: {}", opts.cookie.trim()));
@@ -48,7 +51,10 @@ pub fn headers_arg(opts: &ManifestOptions) -> Option<String> {
}
}
-pub async fn download(opts: ManifestOptions, progress: super::ProgressFn) -> anyhow::Result<ManifestResult> {
+pub async fn download(
+ opts: ManifestOptions,
+ progress: super::ProgressFn,
+) -> anyhow::Result<ManifestResult> {
use tokio::io::{AsyncBufReadExt, BufReader};
let ffmpeg = crate::core::dependencies::ensure_ffmpeg().await?;
let url = opts.url.trim().to_string();
@@ -62,16 +68,41 @@ pub async fn download(opts: ManifestOptions, progress: super::ProgressFn) -> any
}
let out = PathBuf::from(&opts.dest_dir).join(name);
let mut cmd = crate::core::process::command(&ffmpeg);
- cmd.args(["-y", "-hide_banner", "-loglevel", "error", "-nostats", "-progress", "pipe:1"]);
+ cmd.args([
+ "-y",
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-nostats",
+ "-progress",
+ "pipe:1",
+ ]);
if !opts.user_agent.trim().is_empty() {
cmd.args(["-user_agent", opts.user_agent.trim()]);
}
if let Some(h) = headers_arg(&opts) {
cmd.args(["-headers", &h]);
}
- cmd.args(["-protocol_whitelist", "file,http,https,tcp,tls,crypto,data", "-allowed_extensions", "ALL", "-i", &url]);
- cmd.args(["-c", "copy", "-bsf:a", "aac_adtstoasc", "-movflags", "+faststart"]).arg(&out);
- cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());
+ cmd.args([
+ "-protocol_whitelist",
+ "file,http,https,tcp,tls,crypto,data",
+ "-allowed_extensions",
+ "ALL",
+ "-i",
+ &url,
+ ]);
+ cmd.args([
+ "-c",
+ "copy",
+ "-bsf:a",
+ "aac_adtstoasc",
+ "-movflags",
+ "+faststart",
+ ])
+ .arg(&out);
+ cmd.stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped());
let mut child = cmd.spawn()?;
let stdout = child.stdout.take();
let stderr = child.stderr.take();
@@ -83,9 +114,19 @@ pub async fn download(opts: ManifestOptions, progress: super::ProgressFn) -> any
if let Some(o) = stdout {
let mut lines = BufReader::new(o).lines();
while let Ok(Some(line)) = lines.next_line().await {
- if let Some(us) = line.strip_prefix("out_time_us=").and_then(|v| v.trim().parse::<u64>().ok()) {
+ if let Some(us) = line
+ .strip_prefix("out_time_us=")
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ {
secs = us as f64 / 1_000_000.0;
- super::report(&p2, &id2, "progress", us / 1_000_000, None, Some(format!("{:.0}s", secs)));
+ super::report(
+ &p2,
+ &id2,
+ "progress",
+ us / 1_000_000,
+ None,
+ Some(format!("{:.0}s", secs)),
+ );
}
}
}
@@ -117,7 +158,10 @@ pub async fn download(opts: ManifestOptions, progress: super::ProgressFn) -> any
return Err(anyhow!("ffmpeg falhou: {}{}", tail, hint));
}
super::report(&progress, &id, "done", secs as u64, Some(secs as u64), None);
- Ok(ManifestResult { path: out.to_string_lossy().to_string(), seconds: secs })
+ Ok(ManifestResult {
+ path: out.to_string_lossy().to_string(),
+ seconds: secs,
+ })
}
#[cfg(test)]
@@ -126,7 +170,18 @@ mod tests {
#[test]
fn builds_headers() {
- let o = ManifestOptions { url: "".into(), dest_dir: "".into(), file_name: "".into(), referer: "https://x.com/".into(), user_agent: "".into(), cookie: "a=1".into(), extra_headers: vec!["X-Y: z".into()] };
- assert_eq!(headers_arg(&o).unwrap(), "Referer: https://x.com/\r\nOrigin: https://x.com\r\nCookie: a=1\r\nX-Y: z\r\n");
+ let o = ManifestOptions {
+ url: "".into(),
+ dest_dir: "".into(),
+ file_name: "".into(),
+ referer: "https://x.com/".into(),
+ user_agent: "".into(),
+ cookie: "a=1".into(),
+ extra_headers: vec!["X-Y: z".into()],
+ };
+ assert_eq!(
+ headers_arg(&o).unwrap(),
+ "Referer: https://x.com/\r\nOrigin: https://x.com\r\nCookie: a=1\r\nX-Y: z\r\n"
+ );
}
}
diff --git a/src-tauri/omniget-core/src/core/tools/mod.rs b/src-tauri/omniget-core/src/core/tools/mod.rs
index 3583ce87..d89dd7d0 100644
--- a/src-tauri/omniget-core/src/core/tools/mod.rs
+++ b/src-tauri/omniget-core/src/core/tools/mod.rs
@@ -14,8 +14,8 @@ pub mod edge_tts;
pub mod file_search;
pub mod gallery;
pub mod gdocs;
-pub mod humanize;
pub mod github;
+pub mod humanize;
pub mod image_resize;
pub mod instagram;
pub mod jpeg_pdf;
@@ -67,7 +67,14 @@ pub fn noop_progress() -> ProgressFn {
Arc::new(|_| {})
}
-pub fn report(p: &ProgressFn, id: &str, stage: &str, done: u64, total: Option<u64>, message: Option<String>) {
+pub fn report(
+ p: &ProgressFn,
+ id: &str,
+ stage: &str,
+ done: u64,
+ total: Option<u64>,
+ message: Option<String>,
+) {
p(ToolProgress {
id: id.to_string(),
stage: stage.to_string(),
@@ -98,10 +105,12 @@ pub fn client() -> anyhow::Result<reqwest::Client> {
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
),
);
- Ok(crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .default_headers(headers)
- .timeout(std::time::Duration::from_secs(600))
- .build()?)
+ Ok(
+ crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .default_headers(headers)
+ .timeout(std::time::Duration::from_secs(600))
+ .build()?,
+ )
}
/// Baixa uma URL para um arquivo, em streaming, reportando bytes.
diff --git a/src-tauri/omniget-core/src/core/tools/ocr.rs b/src-tauri/omniget-core/src/core/tools/ocr.rs
index e148ab4a..7e3e7260 100644
--- a/src-tauri/omniget-core/src/core/tools/ocr.rs
+++ b/src-tauri/omniget-core/src/core/tools/ocr.rs
@@ -21,9 +21,16 @@ pub async fn locate() -> Option<PathBuf> {
return Some(p);
}
let candidates: &[&str] = if cfg!(target_os = "windows") {
- &[r"C:\Program Files\Tesseract-OCR\tesseract.exe", r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe"]
+ &[
+ r"C:\Program Files\Tesseract-OCR\tesseract.exe",
+ r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe",
+ ]
} else {
- &["/opt/homebrew/bin/tesseract", "/usr/local/bin/tesseract", "/usr/bin/tesseract"]
+ &[
+ "/opt/homebrew/bin/tesseract",
+ "/usr/local/bin/tesseract",
+ "/usr/bin/tesseract",
+ ]
};
candidates.iter().map(PathBuf::from).find(|p| p.exists())
}
@@ -38,14 +45,25 @@ pub async fn status() -> OcrStatus {
}
.to_string();
let Some(bin) = locate().await else {
- return OcrStatus { installed: false, path: None, version: None, languages: vec![], install_hint: hint };
+ return OcrStatus {
+ installed: false,
+ path: None,
+ version: None,
+ languages: vec![],
+ install_hint: hint,
+ };
};
let version = crate::core::process::command(&bin)
.arg("--version")
.output()
.await
.ok()
- .and_then(|o| String::from_utf8_lossy(&o.stdout).lines().next().map(|l| l.trim().to_string()));
+ .and_then(|o| {
+ String::from_utf8_lossy(&o.stdout)
+ .lines()
+ .next()
+ .map(|l| l.trim().to_string())
+ });
let languages = crate::core::process::command(&bin)
.arg("--list-langs")
.output()
@@ -58,7 +76,13 @@ pub async fn status() -> OcrStatus {
.collect()
})
.unwrap_or_default();
- OcrStatus { installed: true, path: Some(bin.to_string_lossy().to_string()), version, languages, install_hint: hint }
+ OcrStatus {
+ installed: true,
+ path: Some(bin.to_string_lossy().to_string()),
+ version,
+ languages,
+ install_hint: hint,
+ }
}
#[derive(Debug, Clone, Serialize)]
@@ -67,22 +91,46 @@ pub struct OcrResult {
pub text: String,
}
-pub async fn run(inputs: &[String], langs: &str, progress: super::ProgressFn) -> anyhow::Result<Vec<OcrResult>> {
- let bin = locate().await.ok_or_else(|| anyhow!("tesseract nao esta instalado"))?;
- let langs = if langs.trim().is_empty() { "eng" } else { langs.trim() };
+pub async fn run(
+ inputs: &[String],
+ langs: &str,
+ progress: super::ProgressFn,
+) -> anyhow::Result<Vec<OcrResult>> {
+ let bin = locate()
+ .await
+ .ok_or_else(|| anyhow!("tesseract nao esta instalado"))?;
+ let langs = if langs.trim().is_empty() {
+ "eng"
+ } else {
+ langs.trim()
+ };
let mut out = Vec::new();
let total = inputs.len() as u64;
for (i, input) in inputs.iter().enumerate() {
- super::report(&progress, "ocr", "progress", i as u64, Some(total), Some(input.clone()));
+ super::report(
+ &progress,
+ "ocr",
+ "progress",
+ i as u64,
+ Some(total),
+ Some(input.clone()),
+ );
let o = crate::core::process::command(&bin)
.arg(input)
.args(["stdout", "-l", langs, "--psm", "3"])
.output()
.await?;
if !o.status.success() {
- return Err(anyhow!("tesseract falhou em {}: {}", input, String::from_utf8_lossy(&o.stderr).trim()));
+ return Err(anyhow!(
+ "tesseract falhou em {}: {}",
+ input,
+ String::from_utf8_lossy(&o.stderr).trim()
+ ));
}
- out.push(OcrResult { path: input.clone(), text: String::from_utf8_lossy(&o.stdout).trim().to_string() });
+ out.push(OcrResult {
+ path: input.clone(),
+ text: String::from_utf8_lossy(&o.stdout).trim().to_string(),
+ });
}
super::report(&progress, "ocr", "done", total, Some(total), None);
Ok(out)
diff --git a/src-tauri/omniget-core/src/core/tools/ollama.rs b/src-tauri/omniget-core/src/core/tools/ollama.rs
index ccf7b5e7..8434a19a 100644
--- a/src-tauri/omniget-core/src/core/tools/ollama.rs
+++ b/src-tauri/omniget-core/src/core/tools/ollama.rs
@@ -7,7 +7,11 @@ use serde::{Deserialize, Serialize};
pub const DEFAULT_HOST: &str = "http://127.0.0.1:11434";
fn base(host: &str) -> String {
- let h = if host.trim().is_empty() { DEFAULT_HOST } else { host.trim() };
+ let h = if host.trim().is_empty() {
+ DEFAULT_HOST
+ } else {
+ host.trim()
+ };
h.trim_end_matches('/').to_string()
}
@@ -53,12 +57,36 @@ pub struct Recommended {
pub fn recommended() -> Vec<Recommended> {
vec![
- Recommended { name: "qwen3:8b".into(), size_gb: 5.2, use_case: "tradução e resumo, boa em português".into() },
- Recommended { name: "gemma3:12b".into(), size_gb: 8.1, use_case: "qualidade alta, precisa de 12 GB+ de RAM".into() },
- Recommended { name: "llama3.2:3b".into(), size_gb: 2.0, use_case: "máquinas fracas, rápido".into() },
- Recommended { name: "gemma3:4b".into(), size_gb: 3.3, use_case: "equilíbrio, aceita imagens".into() },
- Recommended { name: "qwen2.5-coder:7b".into(), size_gb: 4.7, use_case: "código".into() },
- Recommended { name: "nomic-embed-text".into(), size_gb: 0.3, use_case: "busca semântica (embeddings)".into() },
+ Recommended {
+ name: "qwen3:8b".into(),
+ size_gb: 5.2,
+ use_case: "tradução e resumo, boa em português".into(),
+ },
+ Recommended {
+ name: "gemma3:12b".into(),
+ size_gb: 8.1,
+ use_case: "qualidade alta, precisa de 12 GB+ de RAM".into(),
+ },
+ Recommended {
+ name: "llama3.2:3b".into(),
+ size_gb: 2.0,
+ use_case: "máquinas fracas, rápido".into(),
+ },
+ Recommended {
+ name: "gemma3:4b".into(),
+ size_gb: 3.3,
+ use_case: "equilíbrio, aceita imagens".into(),
+ },
+ Recommended {
+ name: "qwen2.5-coder:7b".into(),
+ size_gb: 4.7,
+ use_case: "código".into(),
+ },
+ Recommended {
+ name: "nomic-embed-text".into(),
+ size_gb: 0.3,
+ use_case: "busca semântica (embeddings)".into(),
+ },
]
}
@@ -74,11 +102,19 @@ pub async fn status(host: &str) -> OllamaStatus {
download_url: "https://ollama.com/download".into(),
};
let Some(client) = client else { return st };
- let short = client.get(format!("{}/api/version", b)).timeout(std::time::Duration::from_secs(3)).send().await;
+ let short = client
+ .get(format!("{}/api/version", b))
+ .timeout(std::time::Duration::from_secs(3))
+ .send()
+ .await;
if let Ok(r) = short {
if r.status().is_success() {
st.running = true;
- st.version = r.json::<serde_json::Value>().await.ok().and_then(|v| v["version"].as_str().map(|s| s.to_string()));
+ st.version = r
+ .json::<serde_json::Value>()
+ .await
+ .ok()
+ .and_then(|v| v["version"].as_str().map(|s| s.to_string()));
}
}
if !st.running {
@@ -87,14 +123,20 @@ pub async fn status(host: &str) -> OllamaStatus {
if let Ok(r) = client.get(format!("{}/api/tags", b)).send().await {
if let Ok(v) = r.json::<serde_json::Value>().await {
if let Some(arr) = v["models"].as_array() {
- st.models = arr.iter().filter_map(|m| serde_json::from_value(m.clone()).ok()).collect();
+ st.models = arr
+ .iter()
+ .filter_map(|m| serde_json::from_value(m.clone()).ok())
+ .collect();
}
}
}
if let Ok(r) = client.get(format!("{}/api/ps", b)).send().await {
if let Ok(v) = r.json::<serde_json::Value>().await {
if let Some(arr) = v["models"].as_array() {
- st.loaded = arr.iter().filter_map(|m| m["name"].as_str().map(|s| s.to_string())).collect();
+ st.loaded = arr
+ .iter()
+ .filter_map(|m| m["name"].as_str().map(|s| s.to_string()))
+ .collect();
}
}
}
@@ -135,7 +177,11 @@ pub async fn pull(host: &str, name: &str, progress: super::ProgressFn) -> anyhow
let status = v["status"].as_str().unwrap_or("").to_string();
let done = v["completed"].as_u64().unwrap_or(0);
let total = v["total"].as_u64();
- let stage = if status == "success" { "done" } else { "progress" };
+ let stage = if status == "success" {
+ "done"
+ } else {
+ "progress"
+ };
super::report(&progress, &id, stage, done, total, Some(status));
}
}
diff --git a/src-tauri/omniget-core/src/core/tools/pdf.rs b/src-tauri/omniget-core/src/core/tools/pdf.rs
index d7a0c777..363f6fac 100644
--- a/src-tauri/omniget-core/src/core/tools/pdf.rs
+++ b/src-tauri/omniget-core/src/core/tools/pdf.rs
@@ -34,7 +34,11 @@ struct Writer {
buf: Vec<u8>,
}
-unsafe extern "C" fn write_block(this: *mut FileWrite, data: *const c_void, size: c_ulong) -> c_int {
+unsafe extern "C" fn write_block(
+ this: *mut FileWrite,
+ data: *const c_void,
+ size: c_ulong,
+) -> c_int {
let w = &mut *(this as *mut Writer);
let slice = std::slice::from_raw_parts(data as *const u8, size as usize);
w.buf.extend_from_slice(slice);
@@ -77,7 +81,9 @@ static API: Mutex<Option<&'static Api>> = Mutex::new(None);
static OPS: Mutex<()> = Mutex::new(());
unsafe fn sym<T: Copy>(lib: &libloading::Library, name: &[u8]) -> anyhow::Result<T> {
- Ok(*lib.get::<T>(name).map_err(|e| anyhow!("PDFium sem {}: {}", String::from_utf8_lossy(name), e))?)
+ Ok(*lib
+ .get::<T>(name)
+ .map_err(|e| anyhow!("PDFium sem {}: {}", String::from_utf8_lossy(name), e))?)
}
fn api() -> anyhow::Result<&'static Api> {
@@ -85,8 +91,10 @@ fn api() -> anyhow::Result<&'static Api> {
if let Some(a) = *guard {
return Ok(a);
}
- let path = crate::core::pdfium::resolve_path().ok_or_else(|| anyhow!("PDFium nao esta instalado (Ajustes → Dependencias → PDFium)"))?;
- let lib = unsafe { libloading::Library::new(&path) }.map_err(|e| anyhow!("nao carregou o PDFium em {}: {}", path.display(), e))?;
+ let path = crate::core::pdfium::resolve_path()
+ .ok_or_else(|| anyhow!("PDFium nao esta instalado (Ajustes → Dependencias → PDFium)"))?;
+ let lib = unsafe { libloading::Library::new(&path) }
+ .map_err(|e| anyhow!("nao carregou o PDFium em {}: {}", path.display(), e))?;
let api = unsafe {
let init: unsafe extern "C" fn() = sym(&lib, b"FPDF_InitLibrary\0")?;
init();
@@ -136,7 +144,8 @@ impl Document {
fn open(api: &'static Api, path: &Path, password: Option<&str>) -> anyhow::Result<Self> {
let data = std::fs::read(path).map_err(|e| anyhow!("nao leu {}: {}", path.display(), e))?;
let pw = CString::new(password.unwrap_or("")).unwrap_or_default();
- let doc = unsafe { (api.load_mem)(data.as_ptr() as *const c_void, data.len(), pw.as_ptr()) };
+ let doc =
+ unsafe { (api.load_mem)(data.as_ptr() as *const c_void, data.len(), pw.as_ptr()) };
if doc.is_null() {
let code = unsafe { (api.last_error)() };
let why = match code {
@@ -149,7 +158,11 @@ impl Document {
};
return Err(anyhow!("{}: {}", path.display(), why));
}
- Ok(Document { api, doc, _data: data })
+ Ok(Document {
+ api,
+ doc,
+ _data: data,
+ })
}
fn new(api: &'static Api) -> anyhow::Result<Self> {
@@ -157,7 +170,11 @@ impl Document {
if doc.is_null() {
return Err(anyhow!("nao criou o documento"));
}
- Ok(Document { api, doc, _data: Vec::new() })
+ Ok(Document {
+ api,
+ doc,
+ _data: Vec::new(),
+ })
}
fn pages(&self) -> usize {
@@ -169,12 +186,20 @@ impl Document {
if page.is_null() {
return Err(anyhow!("pagina {} nao abriu", index + 1));
}
- Ok(PageRef { api: self.api, page, _doc: self })
+ Ok(PageRef {
+ api: self.api,
+ page,
+ _doc: self,
+ })
}
/// Copia páginas de `src` (números 1-based, na ordem dada) para o fim.
fn import(&self, src: &Document, pages: &[usize]) -> anyhow::Result<()> {
- let spec = pages.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(",");
+ let spec = pages
+ .iter()
+ .map(|p| p.to_string())
+ .collect::<Vec<_>>()
+ .join(",");
let spec = CString::new(spec)?;
let at = self.pages() as c_int;
let ok = unsafe { (self.api.import_pages)(self.doc, src.doc, spec.as_ptr(), at) };
@@ -185,7 +210,13 @@ impl Document {
}
fn to_bytes(&self) -> anyhow::Result<Vec<u8>> {
- let mut w = Writer { fw: FileWrite { version: 1, write_block }, buf: Vec::new() };
+ let mut w = Writer {
+ fw: FileWrite {
+ version: 1,
+ write_block,
+ },
+ buf: Vec::new(),
+ };
let ok = unsafe { (self.api.save_copy)(self.doc, &mut w.fw as *mut FileWrite, 0) };
if ok == 0 {
return Err(anyhow!("nao gravou o PDF"));
@@ -204,13 +235,25 @@ impl Document {
fn meta(&self, tag: &str) -> Option<String> {
let tag = CString::new(tag).ok()?;
- let len = unsafe { (self.api.meta_text)(self.doc, tag.as_ptr(), std::ptr::null_mut(), 0) } as usize;
+ let len = unsafe { (self.api.meta_text)(self.doc, tag.as_ptr(), std::ptr::null_mut(), 0) }
+ as usize;
if len < 4 {
return None;
}
let mut buf = vec![0u8; len];
- unsafe { (self.api.meta_text)(self.doc, tag.as_ptr(), buf.as_mut_ptr() as *mut c_void, len as c_ulong) };
- let units: Vec<u16> = buf.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|u| *u != 0).collect();
+ unsafe {
+ (self.api.meta_text)(
+ self.doc,
+ tag.as_ptr(),
+ buf.as_mut_ptr() as *mut c_void,
+ len as c_ulong,
+ )
+ };
+ let units: Vec<u16> = buf
+ .chunks_exact(2)
+ .map(|c| u16::from_le_bytes([c[0], c[1]]))
+ .take_while(|u| *u != 0)
+ .collect();
let s = String::from_utf16_lossy(&units).trim().to_string();
if s.is_empty() {
None
@@ -276,7 +319,9 @@ impl PageRef<'_> {
let n = (self.api.text_get)(tp, 0, count, buf.as_mut_ptr());
(self.api.text_close)(tp);
let n = (n.max(1) - 1) as usize;
- String::from_utf16_lossy(&buf[..n.min(buf.len())]).replace("\r\n", "\n").replace('\r', "\n")
+ String::from_utf16_lossy(&buf[..n.min(buf.len())])
+ .replace("\r\n", "\n")
+ .replace('\r', "\n")
}
}
}
@@ -294,12 +339,32 @@ pub fn parse_ranges(spec: &str, total: usize) -> anyhow::Result<Vec<usize>> {
return Ok((1..=total).collect());
}
let mut out = Vec::new();
- for part in spec.split([',', ' ']).map(str::trim).filter(|p| !p.is_empty()) {
+ for part in spec
+ .split([',', ' '])
+ .map(str::trim)
+ .filter(|p| !p.is_empty())
+ {
if let Some((a, b)) = part.split_once('-') {
- let a: usize = if a.trim().is_empty() { 1 } else { a.trim().parse().map_err(|_| anyhow!("intervalo invalido: {}", part))? };
- let b: usize = if b.trim().is_empty() { total } else { b.trim().parse().map_err(|_| anyhow!("intervalo invalido: {}", part))? };
+ let a: usize = if a.trim().is_empty() {
+ 1
+ } else {
+ a.trim()
+ .parse()
+ .map_err(|_| anyhow!("intervalo invalido: {}", part))?
+ };
+ let b: usize = if b.trim().is_empty() {
+ total
+ } else {
+ b.trim()
+ .parse()
+ .map_err(|_| anyhow!("intervalo invalido: {}", part))?
+ };
if a == 0 || b == 0 || a > total || b > total {
- return Err(anyhow!("pagina fora do documento ({} paginas): {}", total, part));
+ return Err(anyhow!(
+ "pagina fora do documento ({} paginas): {}",
+ total,
+ part
+ ));
}
if a <= b {
out.extend(a..=b);
@@ -307,9 +372,15 @@ pub fn parse_ranges(spec: &str, total: usize) -> anyhow::Result<Vec<usize>> {
out.extend((b..=a).rev());
}
} else {
- let n: usize = part.parse().map_err(|_| anyhow!("pagina invalida: {}", part))?;
+ let n: usize = part
+ .parse()
+ .map_err(|_| anyhow!("pagina invalida: {}", part))?;
if n == 0 || n > total {
- return Err(anyhow!("pagina fora do documento ({} paginas): {}", total, n));
+ return Err(anyhow!(
+ "pagina fora do documento ({} paginas): {}",
+ total,
+ n
+ ));
}
out.push(n);
}
@@ -321,12 +392,17 @@ pub fn parse_ranges(spec: &str, total: usize) -> anyhow::Result<Vec<usize>> {
}
fn stem(path: &Path) -> String {
- path.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "documento".into())
+ path.file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| "documento".into())
}
fn out_dir_for(input: &Path, output_dir: &str) -> PathBuf {
if output_dir.trim().is_empty() {
- input.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."))
+ input
+ .parent()
+ .map(Path::to_path_buf)
+ .unwrap_or_else(|| PathBuf::from("."))
} else {
PathBuf::from(output_dir.trim())
}
@@ -338,10 +414,17 @@ fn unique(path: PathBuf) -> PathBuf {
return path;
}
let stem = stem(&path);
- let ext = path.extension().map(|e| e.to_string_lossy().to_string()).unwrap_or_default();
+ let ext = path
+ .extension()
+ .map(|e| e.to_string_lossy().to_string())
+ .unwrap_or_default();
let dir = path.parent().map(Path::to_path_buf).unwrap_or_default();
for i in 2..1000 {
- let cand = dir.join(if ext.is_empty() { format!("{} ({})", stem, i) } else { format!("{} ({}).{}", stem, i, ext) });
+ let cand = dir.join(if ext.is_empty() {
+ format!("{} ({})", stem, i)
+ } else {
+ format!("{} ({}).{}", stem, i, ext)
+ });
if !cand.exists() {
return cand;
}
@@ -354,7 +437,8 @@ fn encode(img: &image::RgbImage, format: &str, quality: u8) -> anyhow::Result<Ve
if format == "png" {
img.write_to(&mut Cursor::new(&mut buf), image::ImageFormat::Png)?;
} else {
- let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buf, quality.clamp(10, 100));
+ let mut enc =
+ image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buf, quality.clamp(10, 100));
enc.encode_image(img)?;
}
Ok(buf)
@@ -404,11 +488,19 @@ async fn find_soffice() -> Option<PathBuf> {
return Some(p);
}
let candidates: &[&str] = if cfg!(target_os = "windows") {
- &[r"C:\Program Files\LibreOffice\program\soffice.exe", r"C:\Program Files (x86)\LibreOffice\program\soffice.exe"]
+ &[
+ r"C:\Program Files\LibreOffice\program\soffice.exe",
+ r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
+ ]
} else if cfg!(target_os = "macos") {
&["/Applications/LibreOffice.app/Contents/MacOS/soffice"]
} else {
- &["/usr/bin/soffice", "/usr/bin/libreoffice", "/snap/bin/libreoffice", "/var/lib/flatpak/exports/bin/org.libreoffice.LibreOffice"]
+ &[
+ "/usr/bin/soffice",
+ "/usr/bin/libreoffice",
+ "/snap/bin/libreoffice",
+ "/var/lib/flatpak/exports/bin/org.libreoffice.LibreOffice",
+ ]
};
candidates.iter().map(PathBuf::from).find(|p| p.exists())
}
@@ -419,7 +511,9 @@ pub async fn status() -> PdfStatus {
pdfium: available(),
pdfium_version: crate::core::pdfium::read_version_marker(),
ghostscript: find_gs().await.map(|p| p.to_string_lossy().to_string()),
- libreoffice: find_soffice().await.map(|p| p.to_string_lossy().to_string()),
+ libreoffice: find_soffice()
+ .await
+ .map(|p| p.to_string_lossy().to_string()),
tesseract: ocr.installed,
tesseract_langs: ocr.languages,
}
@@ -488,7 +582,13 @@ pub fn merge(opts: &MergeOptions, progress: &super::ProgressFn) -> anyhow::Resul
let dest = Document::new(api)?;
let total = opts.inputs.len() as u64;
for (i, input) in opts.inputs.iter().enumerate() {
- report(progress, "progress", i as u64, Some(total), Some(input.clone()));
+ report(
+ progress,
+ "progress",
+ i as u64,
+ Some(total),
+ Some(input.clone()),
+ );
let src = Document::open(api, Path::new(input), None)?;
let all: Vec<usize> = (1..=src.pages()).collect();
if !all.is_empty() {
@@ -498,7 +598,11 @@ pub fn merge(opts: &MergeOptions, progress: &super::ProgressFn) -> anyhow::Resul
let out = unique(PathBuf::from(opts.output.trim()));
let bytes = dest.save(&out)?;
report(progress, "done", total, Some(total), None);
- Ok(PdfOut { output: out.to_string_lossy().to_string(), pages: dest.pages(), bytes })
+ Ok(PdfOut {
+ output: out.to_string_lossy().to_string(),
+ pages: dest.pages(),
+ bytes,
+ })
}
// ── Dividir ────────────────────────────────────────────────────────────
@@ -533,7 +637,9 @@ pub fn split(opts: &SplitOptions, progress: &super::ProgressFn) -> anyhow::Resul
return Err(anyhow!("o PDF nao tem paginas"));
}
let groups: Vec<(String, Vec<usize>)> = match opts.mode.as_str() {
- "each" => (1..=total).map(|p| (format!("p{:03}", p), vec![p])).collect(),
+ "each" => (1..=total)
+ .map(|p| (format!("p{:03}", p), vec![p]))
+ .collect(),
"every" => {
let n = opts.every.max(1);
(1..=total)
@@ -547,9 +653,14 @@ pub fn split(opts: &SplitOptions, progress: &super::ProgressFn) -> anyhow::Resul
.split(';')
.map(str::trim)
.filter(|s| !s.is_empty())
- .map(|s| parse_ranges(s, total).map(|pages| (s.replace(' ', "").replace(',', "_"), pages)))
+ .map(|s| {
+ parse_ranges(s, total).map(|pages| (s.replace(' ', "").replace(',', "_"), pages))
+ })
.collect::<anyhow::Result<Vec<_>>>()?,
- _ => vec![(opts.ranges.replace(' ', "").replace(',', "_"), parse_ranges(&opts.ranges, total)?)],
+ _ => vec![(
+ opts.ranges.replace(' ', "").replace(',', "_"),
+ parse_ranges(&opts.ranges, total)?,
+ )],
};
if groups.is_empty() {
return Err(anyhow!("nenhum trecho para extrair"));
@@ -568,7 +679,10 @@ pub fn split(opts: &SplitOptions, progress: &super::ProgressFn) -> anyhow::Resul
outputs.push(path.to_string_lossy().to_string());
}
report(progress, "done", n, Some(n), None);
- Ok(PdfOuts { outputs, pages: total })
+ Ok(PdfOuts {
+ outputs,
+ pages: total,
+ })
}
// ── Renderizar (PDF → imagens) ─────────────────────────────────────────
@@ -603,7 +717,13 @@ pub fn render(opts: &RenderOptions, progress: &super::ProgressFn) -> anyhow::Res
let mut outputs = Vec::new();
let n = pages.len() as u64;
for (i, p) in pages.iter().enumerate() {
- report(progress, "progress", i as u64, Some(n), Some(format!("pagina {}", p)));
+ report(
+ progress,
+ "progress",
+ i as u64,
+ Some(n),
+ Some(format!("pagina {}", p)),
+ );
let img = doc.page(p - 1)?.render(dpi)?;
let bytes = encode(&img, format, quality)?;
let path = dir.join(format!("{} - {:03}.{}", stem(input), p, format));
@@ -623,7 +743,12 @@ pub struct TextResult {
pub pages: usize,
}
-pub fn to_text(input: &str, pages: &str, save: bool, output_dir: &str) -> anyhow::Result<TextResult> {
+pub fn to_text(
+ input: &str,
+ pages: &str,
+ save: bool,
+ output_dir: &str,
+) -> anyhow::Result<TextResult> {
let api = api()?;
let _g = OPS.lock().unwrap_or_else(|p| p.into_inner());
let path = Path::new(input.trim());
@@ -644,12 +769,21 @@ pub fn to_text(input: &str, pages: &str, save: bool, output_dir: &str) -> anyhow
} else {
None
};
- Ok(TextResult { text, output, pages: pages.len() })
+ Ok(TextResult {
+ text,
+ output,
+ pages: pages.len(),
+ })
}
// ── Imagens → PDF ──────────────────────────────────────────────────────
-pub fn images_to_pdf(inputs: &[String], output: &str, quality: u8, progress: &super::ProgressFn) -> anyhow::Result<PdfOut> {
+pub fn images_to_pdf(
+ inputs: &[String],
+ output: &str,
+ quality: u8,
+ progress: &super::ProgressFn,
+) -> anyhow::Result<PdfOut> {
if inputs.is_empty() {
return Err(anyhow!("escolha pelo menos uma imagem"));
}
@@ -662,7 +796,9 @@ pub fn images_to_pdf(inputs: &[String], output: &str, quality: u8, progress: &su
if jpeg_pdf::is_jpeg(&data) {
jpegs.push(data);
} else {
- let img = image::load_from_memory(&data).map_err(|e| anyhow!("{}: {}", input, e))?.to_rgb8();
+ let img = image::load_from_memory(&data)
+ .map_err(|e| anyhow!("{}: {}", input, e))?
+ .to_rgb8();
jpegs.push(encode(&img, "jpg", quality)?);
}
}
@@ -673,19 +809,35 @@ pub fn images_to_pdf(inputs: &[String], output: &str, quality: u8, progress: &su
}
std::fs::write(&out, &pdf)?;
report(progress, "done", n, Some(n), None);
- Ok(PdfOut { output: out.to_string_lossy().to_string(), pages: jpegs.len(), bytes: pdf.len() as u64 })
+ Ok(PdfOut {
+ output: out.to_string_lossy().to_string(),
+ pages: jpegs.len(),
+ bytes: pdf.len() as u64,
+ })
}
// ── Rasterizar de volta para PDF (comprimir e sanitizar) ───────────────
-fn rasterize(input: &Path, output: &Path, dpi: u32, quality: u8, progress: &super::ProgressFn) -> anyhow::Result<PdfOut> {
+fn rasterize(
+ input: &Path,
+ output: &Path,
+ dpi: u32,
+ quality: u8,
+ progress: &super::ProgressFn,
+) -> anyhow::Result<PdfOut> {
let api = api()?;
let _g = OPS.lock().unwrap_or_else(|p| p.into_inner());
let doc = Document::open(api, input, None)?;
let total = doc.pages();
let mut jpegs = Vec::with_capacity(total);
for i in 0..total {
- report(progress, "progress", i as u64, Some(total as u64), Some(format!("pagina {}", i + 1)));
+ report(
+ progress,
+ "progress",
+ i as u64,
+ Some(total as u64),
+ Some(format!("pagina {}", i + 1)),
+ );
let img = doc.page(i)?.render(dpi)?;
jpegs.push(encode(&img, "jpg", quality)?);
}
@@ -696,7 +848,11 @@ fn rasterize(input: &Path, output: &Path, dpi: u32, quality: u8, progress: &supe
}
std::fs::write(output, &pdf)?;
report(progress, "done", total as u64, Some(total as u64), None);
- Ok(PdfOut { output: output.to_string_lossy().to_string(), pages: total, bytes: pdf.len() as u64 })
+ Ok(PdfOut {
+ output: output.to_string_lossy().to_string(),
+ pages: total,
+ bytes: pdf.len() as u64,
+ })
}
#[derive(Debug, Clone, Deserialize)]
@@ -725,11 +881,20 @@ pub struct CompressResult {
pub pages: usize,
}
-pub async fn compress(opts: CompressOptions, progress: super::ProgressFn) -> anyhow::Result<CompressResult> {
+pub async fn compress(
+ opts: CompressOptions,
+ progress: super::ProgressFn,
+) -> anyhow::Result<CompressResult> {
let input = PathBuf::from(opts.input.trim());
let before = std::fs::metadata(&input)?.len();
- let output = unique(out_dir_for(&input, &opts.output_dir).join(format!("{} (comprimido).pdf", stem(&input))));
- let gs = if opts.mode == "raster" { None } else { find_gs().await };
+ let output = unique(
+ out_dir_for(&input, &opts.output_dir).join(format!("{} (comprimido).pdf", stem(&input))),
+ );
+ let gs = if opts.mode == "raster" {
+ None
+ } else {
+ find_gs().await
+ };
if let Some(gs) = gs {
let preset = match opts.preset.as_str() {
"screen" | "printer" | "prepress" => opts.preset.clone(),
@@ -737,7 +902,14 @@ pub async fn compress(opts: CompressOptions, progress: super::ProgressFn) -> any
};
report(&progress, "progress", 0, None, Some("ghostscript".into()));
let o = crate::core::process::command(&gs)
- .args(["-sDEVICE=pdfwrite", "-dCompatibilityLevel=1.5", "-dNOPAUSE", "-dQUIET", "-dBATCH", "-dDetectDuplicateImages=true"])
+ .args([
+ "-sDEVICE=pdfwrite",
+ "-dCompatibilityLevel=1.5",
+ "-dNOPAUSE",
+ "-dQUIET",
+ "-dBATCH",
+ "-dDetectDuplicateImages=true",
+ ])
.arg(format!("-dPDFSETTINGS=/{}", preset))
.arg(format!("-sOutputFile={}", output.display()))
.arg(&input)
@@ -747,15 +919,28 @@ pub async fn compress(opts: CompressOptions, progress: super::ProgressFn) -> any
let after = std::fs::metadata(&output)?.len();
let pages = tokio::task::spawn_blocking({
let out = output.clone();
- move || info(&out.to_string_lossy(), None).map(|i| i.pages).unwrap_or(0)
+ move || {
+ info(&out.to_string_lossy(), None)
+ .map(|i| i.pages)
+ .unwrap_or(0)
+ }
})
.await
.unwrap_or(0);
report(&progress, "done", 1, Some(1), None);
- return Ok(CompressResult { output: output.to_string_lossy().to_string(), before, after, method: "ghostscript".into(), pages });
+ return Ok(CompressResult {
+ output: output.to_string_lossy().to_string(),
+ before,
+ after,
+ method: "ghostscript".into(),
+ pages,
+ });
}
if opts.mode == "gs" {
- return Err(anyhow!("ghostscript falhou: {}", String::from_utf8_lossy(&o.stderr).trim()));
+ return Err(anyhow!(
+ "ghostscript falhou: {}",
+ String::from_utf8_lossy(&o.stderr).trim()
+ ));
}
let _ = std::fs::remove_file(&output);
} else if opts.mode == "gs" {
@@ -763,15 +948,30 @@ pub async fn compress(opts: CompressOptions, progress: super::ProgressFn) -> any
}
let dpi = if opts.dpi == 0 { 110 } else { opts.dpi };
let quality = if opts.quality == 0 { 60 } else { opts.quality };
- let out = tokio::task::spawn_blocking(move || rasterize(&input, &output, dpi, quality, &progress)).await??;
- Ok(CompressResult { output: out.output, before, after: out.bytes, method: "raster".into(), pages: out.pages })
+ let out =
+ tokio::task::spawn_blocking(move || rasterize(&input, &output, dpi, quality, &progress))
+ .await??;
+ Ok(CompressResult {
+ output: out.output,
+ before,
+ after: out.bytes,
+ method: "raster".into(),
+ pages: out.pages,
+ })
}
/// Dangerzone sem contêiner: cada página vira pixels e o PDF é remontado
/// só com imagens. Scripts, formulários, links e anexos não sobrevivem.
-pub fn sanitize(input: &str, output_dir: &str, dpi: u32, quality: u8, progress: &super::ProgressFn) -> anyhow::Result<PdfOut> {
+pub fn sanitize(
+ input: &str,
+ output_dir: &str,
+ dpi: u32,
+ quality: u8,
+ progress: &super::ProgressFn,
+) -> anyhow::Result<PdfOut> {
let input = PathBuf::from(input.trim());
- let output = unique(out_dir_for(&input, output_dir).join(format!("{} (seguro).pdf", stem(&input))));
+ let output =
+ unique(out_dir_for(&input, output_dir).join(format!("{} (seguro).pdf", stem(&input))));
let dpi = if dpi == 0 { 150 } else { dpi };
let quality = if quality == 0 { 85 } else { quality };
rasterize(&input, &output, dpi, quality, progress)
@@ -779,10 +979,22 @@ pub fn sanitize(input: &str, output_dir: &str, dpi: u32, quality: u8, progress:
// ── OCR (PDF pesquisável) ──────────────────────────────────────────────
-pub async fn ocr(input: String, langs: String, output_dir: String, dpi: u32, progress: super::ProgressFn) -> anyhow::Result<PdfOut> {
- let tesseract = super::ocr::locate().await.ok_or_else(|| anyhow!("tesseract nao esta instalado"))?;
+pub async fn ocr(
+ input: String,
+ langs: String,
+ output_dir: String,
+ dpi: u32,
+ progress: super::ProgressFn,
+) -> anyhow::Result<PdfOut> {
+ let tesseract = super::ocr::locate()
+ .await
+ .ok_or_else(|| anyhow!("tesseract nao esta instalado"))?;
let input_path = PathBuf::from(input.trim());
- let langs = if langs.trim().is_empty() { "eng".to_string() } else { langs.trim().to_string() };
+ let langs = if langs.trim().is_empty() {
+ "eng".to_string()
+ } else {
+ langs.trim().to_string()
+ };
let dpi = if dpi == 0 { 300 } else { dpi };
let work = super::temp_dir().join(format!("pdf-ocr-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&work)?;
@@ -799,7 +1011,13 @@ pub async fn ocr(input: String, langs: String, output_dir: String, dpi: u32, pro
let total = doc.pages();
let mut out = Vec::with_capacity(total);
for i in 0..total {
- report(&progress, "render", i as u64, Some(total as u64), Some(format!("pagina {}", i + 1)));
+ report(
+ &progress,
+ "render",
+ i as u64,
+ Some(total as u64),
+ Some(format!("pagina {}", i + 1)),
+ );
let img = doc.page(i)?.render(dpi)?;
let p = work.join(format!("{:04}.png", i + 1));
std::fs::write(&p, encode(&img, "png", 100)?)?;
@@ -812,7 +1030,13 @@ pub async fn ocr(input: String, langs: String, output_dir: String, dpi: u32, pro
// 2) tesseract com lista de imagens → um PDF só, com camada de texto
let list = work.join("pages.txt");
- std::fs::write(&list, pngs.iter().map(|p| p.to_string_lossy().to_string()).collect::<Vec<_>>().join("\n"))?;
+ std::fs::write(
+ &list,
+ pngs.iter()
+ .map(|p| p.to_string_lossy().to_string())
+ .collect::<Vec<_>>()
+ .join("\n"),
+ )?;
let base = work.join("ocr");
report(&progress, "ocr", 0, Some(pages as u64), Some(langs.clone()));
let o = crate::core::process::command(&tesseract)
@@ -823,10 +1047,15 @@ pub async fn ocr(input: String, langs: String, output_dir: String, dpi: u32, pro
.await?;
if !o.status.success() {
let _ = std::fs::remove_dir_all(&work);
- return Err(anyhow!("tesseract falhou: {}", String::from_utf8_lossy(&o.stderr).trim()));
+ return Err(anyhow!(
+ "tesseract falhou: {}",
+ String::from_utf8_lossy(&o.stderr).trim()
+ ));
}
let produced = base.with_extension("pdf");
- let output = unique(out_dir_for(&input_path, &output_dir).join(format!("{} (OCR).pdf", stem(&input_path))));
+ let output = unique(
+ out_dir_for(&input_path, &output_dir).join(format!("{} (OCR).pdf", stem(&input_path))),
+ );
if let Some(parent) = output.parent() {
std::fs::create_dir_all(parent)?;
}
@@ -836,38 +1065,70 @@ pub async fn ocr(input: String, langs: String, output_dir: String, dpi: u32, pro
let bytes = std::fs::metadata(&output).map(|m| m.len()).unwrap_or(0);
let _ = std::fs::remove_dir_all(&work);
report(&progress, "done", pages as u64, Some(pages as u64), None);
- Ok(PdfOut { output: output.to_string_lossy().to_string(), pages, bytes })
+ Ok(PdfOut {
+ output: output.to_string_lossy().to_string(),
+ pages,
+ bytes,
+ })
}
// ── LibreOffice (PDF ↔ Office) ─────────────────────────────────────────
-pub async fn office_convert(inputs: Vec<String>, target: String, output_dir: String, progress: super::ProgressFn) -> anyhow::Result<Vec<String>> {
- let soffice = find_soffice().await.ok_or_else(|| anyhow!("LibreOffice nao encontrado"))?;
+pub async fn office_convert(
+ inputs: Vec<String>,
+ target: String,
+ output_dir: String,
+ progress: super::ProgressFn,
+) -> anyhow::Result<Vec<String>> {
+ let soffice = find_soffice()
+ .await
+ .ok_or_else(|| anyhow!("LibreOffice nao encontrado"))?;
let target = target.trim().trim_start_matches('.').to_ascii_lowercase();
- if !matches!(target.as_str(), "docx" | "odt" | "pptx" | "xlsx" | "pdf" | "html" | "txt" | "epub") {
+ if !matches!(
+ target.as_str(),
+ "docx" | "odt" | "pptx" | "xlsx" | "pdf" | "html" | "txt" | "epub"
+ ) {
return Err(anyhow!("formato nao suportado: {}", target));
}
let mut outputs = Vec::new();
let n = inputs.len() as u64;
for (i, input) in inputs.iter().enumerate() {
- report(&progress, "progress", i as u64, Some(n), Some(input.clone()));
+ report(
+ &progress,
+ "progress",
+ i as u64,
+ Some(n),
+ Some(input.clone()),
+ );
let input_path = PathBuf::from(input.trim());
let dir = out_dir_for(&input_path, &output_dir);
std::fs::create_dir_all(&dir)?;
- let is_pdf = input_path.extension().map(|e| e.eq_ignore_ascii_case("pdf")).unwrap_or(false);
+ let is_pdf = input_path
+ .extension()
+ .map(|e| e.eq_ignore_ascii_case("pdf"))
+ .unwrap_or(false);
let mut cmd = crate::core::process::command(&soffice);
cmd.args(["--headless", "--norestore"]);
if is_pdf && target != "pdf" {
cmd.arg("--infilter=writer_pdf_import");
}
- cmd.arg("--convert-to").arg(&target).arg("--outdir").arg(&dir).arg(&input_path);
+ cmd.arg("--convert-to")
+ .arg(&target)
+ .arg("--outdir")
+ .arg(&dir)
+ .arg(&input_path);
let o = cmd.output().await?;
let produced = dir.join(format!("{}.{}", stem(&input_path), target));
if !o.status.success() || !produced.exists() {
return Err(anyhow!(
"LibreOffice nao converteu {}: {}",
input,
- String::from_utf8_lossy(if o.stderr.is_empty() { &o.stdout } else { &o.stderr }).trim()
+ String::from_utf8_lossy(if o.stderr.is_empty() {
+ &o.stdout
+ } else {
+ &o.stderr
+ })
+ .trim()
));
}
outputs.push(produced.to_string_lossy().to_string());
@@ -914,7 +1175,8 @@ mod tests {
std::fs::create_dir_all(&dir).unwrap();
let mut jpegs = Vec::new();
for i in 0..3u8 {
- let img = image::RgbImage::from_fn(200, 300, |x, _| image::Rgb([x as u8, 80 + i * 40, 200]));
+ let img =
+ image::RgbImage::from_fn(200, 300, |x, _| image::Rgb([x as u8, 80 + i * 40, 200]));
jpegs.push(encode(&img, "jpg", 80).unwrap());
}
let a = dir.join("a.pdf");
@@ -923,22 +1185,71 @@ mod tests {
let i = info(&a.to_string_lossy(), None).unwrap();
assert_eq!(i.pages, 3);
assert!(!i.has_text);
- let merged = merge(&MergeOptions { inputs: vec![a.to_string_lossy().to_string(), a.to_string_lossy().to_string()], output: dir.join("m.pdf").to_string_lossy().to_string() }, &p).unwrap();
+ let merged = merge(
+ &MergeOptions {
+ inputs: vec![
+ a.to_string_lossy().to_string(),
+ a.to_string_lossy().to_string(),
+ ],
+ output: dir.join("m.pdf").to_string_lossy().to_string(),
+ },
+ &p,
+ )
+ .unwrap();
assert_eq!(merged.pages, 6);
- let sp = split(&SplitOptions { input: merged.output.clone(), mode: "every".into(), every: 4, ranges: String::new(), output_dir: String::new() }, &p).unwrap();
+ let sp = split(
+ &SplitOptions {
+ input: merged.output.clone(),
+ mode: "every".into(),
+ every: 4,
+ ranges: String::new(),
+ output_dir: String::new(),
+ },
+ &p,
+ )
+ .unwrap();
assert_eq!(sp.outputs.len(), 2);
assert_eq!(info(&sp.outputs[1], None).unwrap().pages, 2);
- let imgs = render(&RenderOptions { input: merged.output.clone(), pages: "1,6".into(), dpi: 50, format: "png".into(), quality: 0, output_dir: String::new() }, &p).unwrap();
+ let imgs = render(
+ &RenderOptions {
+ input: merged.output.clone(),
+ pages: "1,6".into(),
+ dpi: 50,
+ format: "png".into(),
+ quality: 0,
+ output_dir: String::new(),
+ },
+ &p,
+ )
+ .unwrap();
assert_eq!(imgs.len(), 2);
let png = image::open(&imgs[0]).unwrap().to_rgb8();
- assert!(png.width() > 100 && png.get_pixel(png.width() - 1, 10)[2] > 150, "render azul");
+ assert!(
+ png.width() > 100 && png.get_pixel(png.width() - 1, 10)[2] > 150,
+ "render azul"
+ );
let t = to_text(&merged.output, "", false, "").unwrap();
assert_eq!(t.pages, 6);
let s = sanitize(&merged.output, "", 40, 50, &p).unwrap();
assert_eq!(s.pages, 6);
- let c = compress(CompressOptions { input: merged.output.clone(), output_dir: String::new(), mode: "raster".into(), preset: String::new(), dpi: 30, quality: 30 }, p.clone()).await.unwrap();
+ let c = compress(
+ CompressOptions {
+ input: merged.output.clone(),
+ output_dir: String::new(),
+ mode: "raster".into(),
+ preset: String::new(),
+ dpi: 30,
+ quality: 30,
+ },
+ p.clone(),
+ )
+ .await
+ .unwrap();
assert!(c.after < c.before, "{} < {}", c.after, c.before);
- println!("ok: {} {} {:?} {}", merged.output, sp.outputs[0], imgs, c.output);
+ println!(
+ "ok: {} {} {:?} {}",
+ merged.output, sp.outputs[0], imgs, c.output
+ );
let _ = std::fs::remove_dir_all(&dir);
}
}
diff --git a/src-tauri/omniget-core/src/core/tools/pinterest/analysis.rs b/src-tauri/omniget-core/src/core/tools/pinterest/analysis.rs
index 12c0017f..b52e2745 100644
--- a/src-tauri/omniget-core/src/core/tools/pinterest/analysis.rs
+++ b/src-tauri/omniget-core/src/core/tools/pinterest/analysis.rs
@@ -9,17 +9,73 @@ use serde::Serialize;
/// Frases explícitas (nível 3).
const AI_EXPLICIT: &[&str] = &[
- "#aigenerated", "ai generated", "ai-generated", "aigenerated", "generative ai", "genai", "made with ai", "created with ai",
- "created using ai", "ai created", "generated with ai", "generated by ai", "ai modified", "ai-modified", "gerado por ia",
- "gerada por ia", "feito com ia", "criado com ia", "arte ia", "imagem ia", "inteligencia artificial", "inteligência artificial",
+ "#aigenerated",
+ "ai generated",
+ "ai-generated",
+ "aigenerated",
+ "generative ai",
+ "genai",
+ "made with ai",
+ "created with ai",
+ "created using ai",
+ "ai created",
+ "generated with ai",
+ "generated by ai",
+ "ai modified",
+ "ai-modified",
+ "gerado por ia",
+ "gerada por ia",
+ "feito com ia",
+ "criado com ia",
+ "arte ia",
+ "imagem ia",
+ "inteligencia artificial",
+ "inteligência artificial",
];
/// Ferramentas e termos comuns (nível 2).
const AI_TOOLS: &[&str] = &[
- "midjourney", "dall-e", "dall·e", "dalle", "stable diffusion", "ai art", "ai-art", "aiart", "ai image", "ai images",
- "ai artwork", "ai generated art", "ai illustration", "adobe firefly", "nightcafe", "leonardo ai", "leonardo.ai", "ai model",
- "text to image", "text-to-image", "sora ai", "flux ai", "comfyui", "automatic1111", "gpt image", "ideogram", "niji",
- "civitai", "lora", "sdxl", "imagen 3", "nano banana", "gemini image", "chatgpt image", "grok imagine", "ai photo",
- "ai portrait", "ai wallpaper", "ai aesthetic", "ai girl", "ai boy", "ai fashion",
+ "midjourney",
+ "dall-e",
+ "dall·e",
+ "dalle",
+ "stable diffusion",
+ "ai art",
+ "ai-art",
+ "aiart",
+ "ai image",
+ "ai images",
+ "ai artwork",
+ "ai generated art",
+ "ai illustration",
+ "adobe firefly",
+ "nightcafe",
+ "leonardo ai",
+ "leonardo.ai",
+ "ai model",
+ "text to image",
+ "text-to-image",
+ "sora ai",
+ "flux ai",
+ "comfyui",
+ "automatic1111",
+ "gpt image",
+ "ideogram",
+ "niji",
+ "civitai",
+ "lora",
+ "sdxl",
+ "imagen 3",
+ "nano banana",
+ "gemini image",
+ "chatgpt image",
+ "grok imagine",
+ "ai photo",
+ "ai portrait",
+ "ai wallpaper",
+ "ai aesthetic",
+ "ai girl",
+ "ai boy",
+ "ai fashion",
];
/// Devolve (nível, termo que bateu). 1 = só a palavra "ai"/"ia" isolada.
@@ -35,7 +91,10 @@ pub fn ai_keyword_level(text_lower: &str) -> (u8, Option<String>) {
}
}
let weak = regex::Regex::new(r"(?:^|[^a-z0-9])(?:ai|a\.i\.|#ai|ia)(?:$|[^a-z0-9])").unwrap();
- if weak.is_match(text_lower) || text_lower.contains("prompt:") || text_lower.contains("ai prompt") {
+ if weak.is_match(text_lower)
+ || text_lower.contains("prompt:")
+ || text_lower.contains("ai prompt")
+ {
return (1, Some("ai".into()));
}
(0, None)
@@ -72,7 +131,10 @@ pub struct DupeGroup {
}
/// Agrupa por assinatura igual e depois por dHash (união-busca).
-pub fn group_dupes(items: &[(String, Option<String>, Option<u64>)], threshold: u32) -> Vec<DupeGroup> {
+pub fn group_dupes(
+ items: &[(String, Option<String>, Option<u64>)],
+ threshold: u32,
+) -> Vec<DupeGroup> {
let n = items.len();
let mut parent: Vec<usize> = (0..n).collect();
fn find(p: &mut [usize], i: usize) -> usize {
@@ -139,12 +201,20 @@ pub fn group_dupes(items: &[(String, Option<String>, Option<u64>)], threshold: u
}
}
out.push(DupeGroup {
- kind: if all_same_sig { "exact".into() } else { "near".into() },
+ kind: if all_same_sig {
+ "exact".into()
+ } else {
+ "near".into()
+ },
ids: members.iter().map(|&i| items[i].0.clone()).collect(),
distance: if all_same_sig { 0 } else { maxd },
});
}
- out.sort_by(|a, b| a.distance.cmp(&b.distance).then(b.ids.len().cmp(&a.ids.len())));
+ out.sort_by(|a, b| {
+ a.distance
+ .cmp(&b.distance)
+ .then(b.ids.len().cmp(&a.ids.len()))
+ });
out
}
@@ -173,8 +243,15 @@ pub fn to_hex(c: [u8; 3]) -> String {
/// Amostra pixels de uma imagem (pula os quase brancos/pretos quando pedido).
pub fn sample_pixels(bytes: &[u8], max_samples: usize, skip_extremes: bool) -> Vec<[u8; 3]> {
- let Ok(img) = image::load_from_memory(bytes) else { return Vec::new() };
- let small = image::imageops::resize(&img.to_rgb8(), 48, 48, image::imageops::FilterType::Triangle);
+ let Ok(img) = image::load_from_memory(bytes) else {
+ return Vec::new();
+ };
+ let small = image::imageops::resize(
+ &img.to_rgb8(),
+ 48,
+ 48,
+ image::imageops::FilterType::Triangle,
+ );
let mut out = Vec::with_capacity(max_samples.min(48 * 48));
for p in small.pixels() {
let [r, g, b] = p.0;
@@ -205,13 +282,19 @@ pub fn kmeans_palette(samples: &[[u8; 3]], k: usize) -> Vec<Swatch> {
if samples.is_empty() || k == 0 {
return Vec::new();
}
- let pts: Vec<[f32; 3]> = samples.iter().map(|c| [c[0] as f32, c[1] as f32, c[2] as f32]).collect();
+ let pts: Vec<[f32; 3]> = samples
+ .iter()
+ .map(|c| [c[0] as f32, c[1] as f32, c[2] as f32])
+ .collect();
let k = k.min(pts.len());
let mut centers: Vec<[f32; 3]> = vec![pts[0]];
while centers.len() < k {
let mut best = (0usize, -1.0f32);
for (i, p) in pts.iter().enumerate() {
- let d = centers.iter().map(|c| dist2(*p, *c)).fold(f32::MAX, f32::min);
+ let d = centers
+ .iter()
+ .map(|c| dist2(*p, *c))
+ .fold(f32::MAX, f32::min);
if d > best.1 {
best = (i, d);
}
@@ -245,7 +328,11 @@ pub fn kmeans_palette(samples: &[[u8; 3]], k: usize) -> Vec<Swatch> {
}
for (j, c) in centers.iter_mut().enumerate() {
if sums[j][3] > 0.0 {
- *c = [sums[j][0] / sums[j][3], sums[j][1] / sums[j][3], sums[j][2] / sums[j][3]];
+ *c = [
+ sums[j][0] / sums[j][3],
+ sums[j][1] / sums[j][3],
+ sums[j][2] / sums[j][3],
+ ];
}
}
}
@@ -260,10 +347,18 @@ pub fn kmeans_palette(samples: &[[u8; 3]], k: usize) -> Vec<Swatch> {
.filter(|(_, c)| **c > 0)
.map(|(c, cnt)| {
let rgb = [c[0].round() as u8, c[1].round() as u8, c[2].round() as u8];
- Swatch { hex: to_hex(rgb), rgb, share: *cnt as f32 / total }
+ Swatch {
+ hex: to_hex(rgb),
+ rgb,
+ share: *cnt as f32 / total,
+ }
})
.collect();
- out.sort_by(|a, b| b.share.partial_cmp(&a.share).unwrap_or(std::cmp::Ordering::Equal));
+ out.sort_by(|a, b| {
+ b.share
+ .partial_cmp(&a.share)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ });
out
}
diff --git a/src-tauri/omniget-core/src/core/tools/pinterest/api.rs b/src-tauri/omniget-core/src/core/tools/pinterest/api.rs
index 92c5c5b6..fa2834cf 100644
--- a/src-tauri/omniget-core/src/core/tools/pinterest/api.rs
+++ b/src-tauri/omniget-core/src/core/tools/pinterest/api.rs
@@ -18,19 +18,64 @@ pub const PAGE: u32 = 100;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Target {
- Pin { id: String },
- Board { user: String, slug: String },
- Section { user: String, slug: String, section: String },
- User { username: String },
- UserCreated { username: String },
- Search { query: String, scope: String },
- Short { code: String },
+ Pin {
+ id: String,
+ },
+ Board {
+ user: String,
+ slug: String,
+ },
+ Section {
+ user: String,
+ slug: String,
+ section: String,
+ },
+ User {
+ username: String,
+ },
+ UserCreated {
+ username: String,
+ },
+ Search {
+ query: String,
+ scope: String,
+ },
+ Short {
+ code: String,
+ },
}
const RESERVED: &[&str] = &[
- "pin", "search", "ideas", "today", "settings", "login", "signup", "business", "explore", "categories", "topics",
- "news_hub", "videos", "shopping", "help", "about", "policy", "resource", "oauth", "password", "notifications",
- "messages", "homefeed", "create", "pin-builder", "pin-creation-tool", "board", "boards", "_created", "_saved",
+ "pin",
+ "search",
+ "ideas",
+ "today",
+ "settings",
+ "login",
+ "signup",
+ "business",
+ "explore",
+ "categories",
+ "topics",
+ "news_hub",
+ "videos",
+ "shopping",
+ "help",
+ "about",
+ "policy",
+ "resource",
+ "oauth",
+ "password",
+ "notifications",
+ "messages",
+ "homefeed",
+ "create",
+ "pin-builder",
+ "pin-creation-tool",
+ "board",
+ "boards",
+ "_created",
+ "_saved",
];
fn pinterest_host(host: &str) -> bool {
@@ -53,25 +98,43 @@ pub fn parse_target(input: &str) -> Option<Target> {
if s.chars().all(|c| c.is_ascii_digit()) && s.len() >= 8 {
return Some(Target::Pin { id: s.to_string() });
}
- let with_scheme = if s.contains("://") { s.to_string() } else { format!("https://{}", s) };
+ let with_scheme = if s.contains("://") {
+ s.to_string()
+ } else {
+ format!("https://{}", s)
+ };
let Ok(u) = url::Url::parse(&with_scheme) else {
- return Some(Target::Search { query: s.to_string(), scope: "pins".into() });
+ return Some(Target::Search {
+ query: s.to_string(),
+ scope: "pins".into(),
+ });
};
let host = u.host_str().unwrap_or("").to_ascii_lowercase();
if host == "pin.it" {
let code = u.path().trim_matches('/').to_string();
- return if code.is_empty() { None } else { Some(Target::Short { code }) };
+ return if code.is_empty() {
+ None
+ } else {
+ Some(Target::Short { code })
+ };
}
if !pinterest_host(&host) {
// não é URL do Pinterest: trata como texto de busca
if !s.contains('.') || s.contains(' ') {
- return Some(Target::Search { query: s.to_string(), scope: "pins".into() });
+ return Some(Target::Search {
+ query: s.to_string(),
+ scope: "pins".into(),
+ });
}
return None;
}
let segs: Vec<String> = u
.path_segments()
- .map(|it| it.filter(|p| !p.is_empty()).map(|p| p.to_string()).collect())
+ .map(|it| {
+ it.filter(|p| !p.is_empty())
+ .map(|p| p.to_string())
+ .collect()
+ })
.unwrap_or_default();
match segs.as_slice() {
[] => None,
@@ -79,20 +142,37 @@ pub fn parse_target(input: &str) -> Option<Target> {
let raw = rest.first()?;
let id = raw.rsplit("--").next().unwrap_or(raw);
let id: String = id.chars().filter(|c| c.is_ascii_digit()).collect();
- if id.is_empty() { None } else { Some(Target::Pin { id }) }
+ if id.is_empty() {
+ None
+ } else {
+ Some(Target::Pin { id })
+ }
}
[first, scope, ..] if first == "search" => {
- let query = u.query_pairs().find(|(k, _)| k == "q").map(|(_, v)| v.to_string()).unwrap_or_default();
+ let query = u
+ .query_pairs()
+ .find(|(k, _)| k == "q")
+ .map(|(_, v)| v.to_string())
+ .unwrap_or_default();
let scope = match scope.as_str() {
"videos" | "boards" => scope.to_string(),
_ => "pins".to_string(),
};
Some(Target::Search { query, scope })
}
- [user] if !RESERVED.contains(&user.as_str()) => Some(Target::User { username: user.clone() }),
- [user, tab] if tab == "_created" => Some(Target::UserCreated { username: user.clone() }),
- [user, tab] if tab == "_saved" || tab == "pins" => Some(Target::User { username: user.clone() }),
- [user, slug] if !RESERVED.contains(&user.as_str()) => Some(Target::Board { user: user.clone(), slug: slug.clone() }),
+ [user] if !RESERVED.contains(&user.as_str()) => Some(Target::User {
+ username: user.clone(),
+ }),
+ [user, tab] if tab == "_created" => Some(Target::UserCreated {
+ username: user.clone(),
+ }),
+ [user, tab] if tab == "_saved" || tab == "pins" => Some(Target::User {
+ username: user.clone(),
+ }),
+ [user, slug] if !RESERVED.contains(&user.as_str()) => Some(Target::Board {
+ user: user.clone(),
+ slug: slug.clone(),
+ }),
[user, slug, section, ..] if !RESERVED.contains(&user.as_str()) => Some(Target::Section {
user: user.clone(),
slug: slug.clone(),
@@ -260,13 +340,29 @@ pub struct User {
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Feed {
- Board { board_id: String, include_sections: bool },
- Section { section_id: String },
- UserPins { username: String },
- UserCreated { username: String },
- Search { query: String, scope: String },
- Related { pin_id: String },
- BoardIdeas { board_id: String },
+ Board {
+ board_id: String,
+ include_sections: bool,
+ },
+ Section {
+ section_id: String,
+ },
+ UserPins {
+ username: String,
+ },
+ UserCreated {
+ username: String,
+ },
+ Search {
+ query: String,
+ scope: String,
+ },
+ Related {
+ pin_id: String,
+ },
+ BoardIdeas {
+ board_id: String,
+ },
}
// ───────────────────────── helpers de JSON ─────────────────────────
@@ -275,7 +371,11 @@ fn s(v: &Value) -> Option<String> {
match v {
Value::String(x) => {
let t = x.trim();
- if t.is_empty() { None } else { Some(t.to_string()) }
+ if t.is_empty() {
+ None
+ } else {
+ Some(t.to_string())
+ }
}
Value::Number(n) => Some(n.to_string()),
_ => None,
@@ -283,12 +383,18 @@ fn s(v: &Value) -> Option<String> {
}
fn n(v: &Value) -> u64 {
- v.as_u64().or_else(|| v.as_f64().map(|f| f.max(0.0) as u64)).unwrap_or(0)
+ v.as_u64()
+ .or_else(|| v.as_f64().map(|f| f.max(0.0) as u64))
+ .unwrap_or(0)
}
fn media(v: &Value) -> Option<Media> {
let url = s(&v["url"])?;
- Some(Media { url, width: n(&v["width"]) as u32, height: n(&v["height"]) as u32 })
+ Some(Media {
+ url,
+ width: n(&v["width"]) as u32,
+ height: n(&v["height"]) as u32,
+ })
}
fn person(v: &Value) -> Option<Person> {
@@ -299,13 +405,19 @@ fn person(v: &Value) -> Option<Person> {
let f = s(&v["first_name"]).unwrap_or_default();
let l = s(&v["last_name"]).unwrap_or_default();
let t = format!("{} {}", f, l).trim().to_string();
- if t.is_empty() { None } else { Some(t) }
+ if t.is_empty() {
+ None
+ } else {
+ Some(t)
+ }
});
Some(Person {
id: s(&v["id"]),
username: s(&v["username"]),
name,
- avatar: s(&v["image_medium_url"]).or_else(|| s(&v["image_large_url"])).or_else(|| s(&v["image_small_url"])),
+ avatar: s(&v["image_medium_url"])
+ .or_else(|| s(&v["image_large_url"]))
+ .or_else(|| s(&v["image_small_url"])),
})
}
@@ -364,14 +476,21 @@ fn largest_image(images: &Value) -> (Option<Media>, Option<Media>, Option<String
Some(o) => o,
None => return (None, None, None),
};
- let orig = obj.get("orig").or_else(|| obj.get("originals")).and_then(media);
+ let orig = obj
+ .get("orig")
+ .or_else(|| obj.get("originals"))
+ .and_then(media);
let large = obj.get("736x").and_then(media).or_else(|| {
obj.iter()
.filter(|(k, _)| k.ends_with('x'))
.filter_map(|(_, v)| media(v))
.max_by_key(|m| m.width)
});
- let thumb = obj.get("236x").and_then(media).map(|m| m.url).or_else(|| large.as_ref().map(|m| m.url.clone()));
+ let thumb = obj
+ .get("236x")
+ .and_then(media)
+ .map(|m| m.url)
+ .or_else(|| large.as_ref().map(|m| m.url.clone()));
(orig, large, thumb)
}
@@ -410,20 +529,32 @@ pub fn parse_pin(v: &Value) -> Option<Pin> {
if v["type"].as_str().map(|t| t != "pin").unwrap_or(false) {
return None;
}
- let title = s(&v["title"]).or_else(|| s(&v["grid_title"])).unwrap_or_default();
+ let title = s(&v["title"])
+ .or_else(|| s(&v["grid_title"]))
+ .unwrap_or_default();
let description = s(&v["description"])
.or_else(|| s(&v["closeup_unified_description"]))
.or_else(|| s(&v["closeup_description"]))
.or_else(|| s(&v["grid_description"]))
.unwrap_or_default();
- let alt_text = s(&v["alt_text"]).or_else(|| s(&v["auto_alt_text"])).or_else(|| s(&v["seo_alt_text"])).unwrap_or_default();
+ let alt_text = s(&v["alt_text"])
+ .or_else(|| s(&v["auto_alt_text"]))
+ .or_else(|| s(&v["seo_alt_text"]))
+ .unwrap_or_default();
let (mut image, image_large, thumb) = largest_image(&v["images"]);
let image_signature = s(&v["image_signature"]);
if image.is_none() {
if let (Some(sig), Some(l)) = (&image_signature, &image_large) {
let ext = l.url.rsplit('.').next().unwrap_or("jpg");
image = Some(Media {
- url: format!("https://i.pinimg.com/originals/{}/{}/{}/{}.{}", &sig[0..2], &sig[2..4], &sig[4..6], sig, ext),
+ url: format!(
+ "https://i.pinimg.com/originals/{}/{}/{}/{}.{}",
+ &sig[0..2],
+ &sig[2..4],
+ &sig[4..6],
+ sig,
+ ext
+ ),
width: 0,
height: 0,
});
@@ -445,21 +576,38 @@ pub fn parse_pin(v: &Value) -> Option<Pin> {
if video.is_none() {
video = Some(vv.clone());
}
- extras.push(Extra { index: idx, kind: "video".into(), image: None, video: Some(vv) });
+ extras.push(Extra {
+ index: idx,
+ kind: "video".into(),
+ image: None,
+ video: Some(vv),
+ });
idx += 1;
}
} else if bt == 2 || btype.contains("image") {
let (o, l, _) = largest_image(&block["image"]["images"]);
let m = o.or(l).or_else(|| {
- let sig = s(&block["image_signature"]).or_else(|| s(&page["image_signature"]))?;
+ let sig =
+ s(&block["image_signature"]).or_else(|| s(&page["image_signature"]))?;
Some(Media {
- url: format!("https://i.pinimg.com/originals/{}/{}/{}/{}.jpg", &sig[0..2], &sig[2..4], &sig[4..6], sig),
+ url: format!(
+ "https://i.pinimg.com/originals/{}/{}/{}/{}.jpg",
+ &sig[0..2],
+ &sig[2..4],
+ &sig[4..6],
+ sig
+ ),
width: 0,
height: 0,
})
});
if let Some(m) = m {
- extras.push(Extra { index: idx, kind: "image".into(), image: Some(m), video: None });
+ extras.push(Extra {
+ index: idx,
+ kind: "image".into(),
+ image: Some(m),
+ video: None,
+ });
idx += 1;
}
}
@@ -471,14 +619,27 @@ pub fn parse_pin(v: &Value) -> Option<Pin> {
extras.clear();
for (i, slot) in slots.iter().enumerate() {
let (o, l, _) = largest_image(&slot["images"]);
- let m = o.or_else(|| l.map(|m| Media { url: to_originals(&m.url), ..m }));
+ let m = o.or_else(|| {
+ l.map(|m| Media {
+ url: to_originals(&m.url),
+ ..m
+ })
+ });
if let Some(m) = m {
- extras.push(Extra { index: i, kind: "image".into(), image: Some(m), video: None });
+ extras.push(Extra {
+ index: i,
+ kind: "image".into(),
+ image: Some(m),
+ video: None,
+ });
}
}
}
- let is_gif = image.as_ref().map(|m| m.url.to_lowercase().ends_with(".gif")).unwrap_or(false);
+ let is_gif = image
+ .as_ref()
+ .map(|m| m.url.to_lowercase().ends_with(".gif"))
+ .unwrap_or(false);
let kind = if v["carousel_data"]["carousel_slots"].is_array() && extras.len() > 1 {
"carousel"
} else if extras.len() > 1 {
@@ -495,8 +656,15 @@ pub fn parse_pin(v: &Value) -> Option<Pin> {
}
let stats = &v["aggregated_pin_data"]["aggregated_stats"];
- let reactions = v["reaction_counts"].as_object().map(|o| o.values().map(n).sum()).unwrap_or(0);
- let rich_v = if v["rich_metadata"].is_object() { &v["rich_metadata"] } else { &v["rich_summary"] };
+ let reactions = v["reaction_counts"]
+ .as_object()
+ .map(|o| o.values().map(n).sum())
+ .unwrap_or(0);
+ let rich_v = if v["rich_metadata"].is_object() {
+ &v["rich_metadata"]
+ } else {
+ &v["rich_summary"]
+ };
let rich = rich_v.as_object().map(|_| Rich {
site_name: s(&rich_v["site_name"]),
title: s(&rich_v["title"]),
@@ -515,7 +683,13 @@ pub fn parse_pin(v: &Value) -> Option<Pin> {
let board = board_v.as_object().map(|_| BoardRef {
id: s(&board_v["id"]),
name: s(&board_v["name"]),
- url: s(&board_v["url"]).map(|u| if u.starts_with('/') { format!("{}{}", ROOT, u) } else { u }),
+ url: s(&board_v["url"]).map(|u| {
+ if u.starts_with('/') {
+ format!("{}{}", ROOT, u)
+ } else {
+ u
+ }
+ }),
});
let ai = detect_ai(v, &title, &description, &alt_text);
@@ -542,7 +716,8 @@ pub fn parse_pin(v: &Value) -> Option<Pin> {
repins: n(&v["repin_count"]),
comments: n(&v["comment_count"]),
reactions,
- is_promoted: v["is_promoted"].as_bool().unwrap_or(false) || v["is_downstream_promotion"].as_bool().unwrap_or(false),
+ is_promoted: v["is_promoted"].as_bool().unwrap_or(false)
+ || v["is_downstream_promotion"].as_bool().unwrap_or(false),
is_repin: v["is_repin"].as_bool().unwrap_or(false),
ai,
dominant_color: s(&v["dominant_color"]),
@@ -554,7 +729,15 @@ pub fn parse_pin(v: &Value) -> Option<Pin> {
fn parse_board(v: &Value) -> Option<Board> {
let id = s(&v["id"])?;
- let url = s(&v["url"]).map(|u| if u.starts_with('/') { format!("{}{}", ROOT, u) } else { u }).unwrap_or_default();
+ let url = s(&v["url"])
+ .map(|u| {
+ if u.starts_with('/') {
+ format!("{}{}", ROOT, u)
+ } else {
+ u
+ }
+ })
+ .unwrap_or_default();
Some(Board {
id,
name: s(&v["name"]).unwrap_or_default(),
@@ -564,9 +747,14 @@ fn parse_board(v: &Value) -> Option<Board> {
section_count: n(&v["section_count"]),
follower_count: n(&v["follower_count"]),
privacy: s(&v["privacy"]).unwrap_or_else(|| "public".into()),
- cover: s(&v["image_cover_hd_url"]).or_else(|| s(&v["image_cover_url"])).or_else(|| {
- v["images"]["474x"].as_array().and_then(|a| a.first()).and_then(|m| s(&m["url"]))
- }),
+ cover: s(&v["image_cover_hd_url"])
+ .or_else(|| s(&v["image_cover_url"]))
+ .or_else(|| {
+ v["images"]["474x"]
+ .as_array()
+ .and_then(|a| a.first())
+ .and_then(|m| s(&m["url"]))
+ }),
owner: person(&v["owner"]),
is_collaborative: v["is_collaborative"].as_bool().unwrap_or(false),
})
@@ -608,11 +796,17 @@ pub fn cookie_header(input: Option<&str>) -> Option<String> {
let p = std::path::Path::new(raw);
if p.exists() && p.is_file() {
let content = std::fs::read_to_string(p).ok()?;
- return crate::platforms::cookie_provider::cookie_header_from_netscape_for_domain(&content, "pinterest.com")
- .or_else(|| crate::platforms::cookie_provider::cookie_header_from_netscape(&content));
+ return crate::platforms::cookie_provider::cookie_header_from_netscape_for_domain(
+ &content,
+ "pinterest.com",
+ )
+ .or_else(|| crate::platforms::cookie_provider::cookie_header_from_netscape(&content));
}
if raw.contains('\t') {
- return crate::platforms::cookie_provider::cookie_header_from_netscape_for_domain(raw, "pinterest.com");
+ return crate::platforms::cookie_provider::cookie_header_from_netscape_for_domain(
+ raw,
+ "pinterest.com",
+ );
}
if raw.contains('=') {
return Some(raw.trim_start_matches("Cookie:").trim().to_string());
@@ -625,11 +819,23 @@ impl PinClient {
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, USER_AGENT};
let mut headers = HeaderMap::new();
headers.insert(USER_AGENT, HeaderValue::from_static(UA));
- headers.insert(ACCEPT, HeaderValue::from_static("application/json, text/javascript, */*, q=0.01"));
- headers.insert("X-Requested-With", HeaderValue::from_static("XMLHttpRequest"));
+ headers.insert(
+ ACCEPT,
+ HeaderValue::from_static("application/json, text/javascript, */*, q=0.01"),
+ );
+ headers.insert(
+ "X-Requested-With",
+ HeaderValue::from_static("XMLHttpRequest"),
+ );
headers.insert("X-Pinterest-AppState", HeaderValue::from_static("active"));
- headers.insert("X-Pinterest-PWS-Handler", HeaderValue::from_static("www/[username].js"));
- headers.insert("Accept-Language", HeaderValue::from_static("en-US,en;q=0.9"));
+ headers.insert(
+ "X-Pinterest-PWS-Handler",
+ HeaderValue::from_static("www/[username].js"),
+ );
+ headers.insert(
+ "Accept-Language",
+ HeaderValue::from_static("en-US,en;q=0.9"),
+ );
let http = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
.default_headers(headers)
.timeout(Duration::from_secs(120))
@@ -637,7 +843,9 @@ impl PinClient {
.build()?;
let cookie = cookie_header(cookies);
let csrf = cookie.as_ref().and_then(|c| {
- c.split(';').map(|p| p.trim()).find_map(|p| p.strip_prefix("csrftoken=").map(|v| v.to_string()))
+ c.split(';')
+ .map(|p| p.trim())
+ .find_map(|p| p.strip_prefix("csrftoken=").map(|v| v.to_string()))
});
Ok(Self { http, cookie, csrf })
}
@@ -658,7 +866,12 @@ impl PinClient {
}
/// GET em um resource; devolve `data` e o próximo bookmark (None no fim).
- async fn resource(&self, name: &str, options: Value, source_url: &str) -> anyhow::Result<(Value, Option<String>)> {
+ async fn resource(
+ &self,
+ name: &str,
+ options: Value,
+ source_url: &str,
+ ) -> anyhow::Result<(Value, Option<String>)> {
let url = format!("{}/resource/{}Resource/get/", ROOT, name);
let data = json!({ "options": options, "context": {} }).to_string();
let mut attempt = 0u32;
@@ -672,12 +885,19 @@ impl PinClient {
let resp = self.apply_cookie(req).send().await?;
let status = resp.status();
if (status.as_u16() == 429 || status.is_server_error()) && attempt < 4 {
- tokio::time::sleep(Duration::from_millis(800 * attempt as u64 * attempt as u64)).await;
+ tokio::time::sleep(Duration::from_millis(800 * attempt as u64 * attempt as u64))
+ .await;
continue;
}
let body: Value = match resp.json().await {
Ok(v) => v,
- Err(e) => return Err(anyhow!("Pinterest respondeu HTTP {} sem JSON ({})", status, e)),
+ Err(e) => {
+ return Err(anyhow!(
+ "Pinterest respondeu HTTP {} sem JSON ({})",
+ status,
+ e
+ ))
+ }
};
let rr = &body["resource_response"];
if rr["status"].as_str() != Some("success") {
@@ -685,12 +905,20 @@ impl PinClient {
.as_str()
.or_else(|| rr["error"]["message"].as_str())
.unwrap_or("resposta sem status de sucesso");
- let code = rr["error"]["http_status"].as_u64().unwrap_or(status.as_u16() as u64);
+ let code = rr["error"]["http_status"]
+ .as_u64()
+ .unwrap_or(status.as_u16() as u64);
if code == 404 {
- return Err(anyhow!("nao encontrado no Pinterest (privado, removido ou URL errada): {}", msg));
+ return Err(anyhow!(
+ "nao encontrado no Pinterest (privado, removido ou URL errada): {}",
+ msg
+ ));
}
if code == 401 || code == 403 {
- return Err(anyhow!("o Pinterest negou o acesso ({}); para boards secretos informe os cookies", msg));
+ return Err(anyhow!(
+ "o Pinterest negou o acesso ({}); para boards secretos informe os cookies",
+ msg
+ ));
}
return Err(anyhow!("Pinterest: {} (HTTP {})", msg, code));
}
@@ -706,14 +934,24 @@ impl PinClient {
}
pub async fn pin(&self, id: &str) -> anyhow::Result<Pin> {
- let (data, _) = self.resource("Pin", json!({ "id": id, "field_set_key": "detailed" }), &format!("/pin/{}/", id)).await?;
+ let (data, _) = self
+ .resource(
+ "Pin",
+ json!({ "id": id, "field_set_key": "detailed" }),
+ &format!("/pin/{}/", id),
+ )
+ .await?;
parse_pin(&data).ok_or_else(|| anyhow!("o Pinterest nao devolveu esse pin"))
}
pub async fn board(&self, user: &str, slug: &str) -> anyhow::Result<Board> {
let src = format!("/{}/{}/", user, slug);
let (data, _) = self
- .resource("Board", json!({ "username": user, "slug": slug, "field_set_key": "detailed" }), &src)
+ .resource(
+ "Board",
+ json!({ "username": user, "slug": slug, "field_set_key": "detailed" }),
+ &src,
+ )
.await?;
parse_board(&data).ok_or_else(|| anyhow!("board nao encontrado"))
}
@@ -747,7 +985,11 @@ impl PinClient {
pub async fn user(&self, username: &str) -> anyhow::Result<User> {
let (data, _) = self
- .resource("User", json!({ "username": username, "field_set_key": "profile" }), &format!("/{}/", username))
+ .resource(
+ "User",
+ json!({ "username": username, "field_set_key": "profile" }),
+ &format!("/{}/", username),
+ )
.await?;
parse_user(&data).ok_or_else(|| anyhow!("perfil nao encontrado"))
}
@@ -763,7 +1005,9 @@ impl PinClient {
if let Some(b) = &bookmark {
opts["bookmarks"] = json!([b]);
}
- let (data, next) = self.resource("Boards", opts, &format!("/{}/_saved/", username)).await?;
+ let (data, next) = self
+ .resource("Boards", opts, &format!("/{}/_saved/", username))
+ .await?;
let before = out.len();
for v in data.as_array().cloned().unwrap_or_default() {
if let Some(b) = parse_board(&v) {
@@ -781,10 +1025,18 @@ impl PinClient {
}
/// Uma página de um feed.
- pub async fn feed_page(&self, feed: &Feed, bookmark: Option<&str>, page_size: u32) -> anyhow::Result<(Vec<Pin>, Option<String>, Vec<String>)> {
+ pub async fn feed_page(
+ &self,
+ feed: &Feed,
+ bookmark: Option<&str>,
+ page_size: u32,
+ ) -> anyhow::Result<(Vec<Pin>, Option<String>, Vec<String>)> {
let bm = bookmark.map(|b| json!([b])).unwrap_or_else(|| json!([]));
let (name, opts, src) = match feed {
- Feed::Board { board_id, include_sections } => (
+ Feed::Board {
+ board_id,
+ include_sections,
+ } => (
"BoardFeed",
json!({ "board_id": board_id, "page_size": page_size, "bookmarks": bm, "field_set_key": "react_grid_pin", "filter_section_pins": !include_sections, "layout": "default", "redux_normalize_feed": true }),
"/".to_string(),
@@ -807,7 +1059,11 @@ impl PinClient {
Feed::Search { query, scope } => (
"BaseSearch",
json!({ "query": query, "scope": scope, "page_size": page_size, "bookmarks": bm, "rs": "typed", "auto_correction_disabled": false, "redux_normalize_feed": true }),
- format!("/search/{}/?q={}&rs=typed", scope, urlencoding::encode(query)),
+ format!(
+ "/search/{}/?q={}&rs=typed",
+ scope,
+ urlencoding::encode(query)
+ ),
),
Feed::Related { pin_id } => (
"RelatedPinFeed",
@@ -827,7 +1083,10 @@ impl PinClient {
} else {
if let Some(g) = data["rankedGuides"].as_array() {
for x in g {
- if let Some(t) = s(&x["term"]).or_else(|| s(&x["display"])).or_else(|| s(&x["name"])) {
+ if let Some(t) = s(&x["term"])
+ .or_else(|| s(&x["display"]))
+ .or_else(|| s(&x["name"]))
+ {
guides.push(t);
}
}
@@ -854,7 +1113,11 @@ impl PinClient {
let mut bookmark: Option<String> = None;
let mut empty_pages = 0u32;
loop {
- let want = if limit == 0 { PAGE } else { ((limit - out.len()).min(PAGE as usize)).max(1) as u32 };
+ let want = if limit == 0 {
+ PAGE
+ } else {
+ ((limit - out.len()).min(PAGE as usize)).max(1) as u32
+ };
let (pins, next, _) = self.feed_page(feed, bookmark.as_deref(), want).await?;
let before = out.len();
for p in pins {
@@ -888,7 +1151,10 @@ impl PinClient {
let mut out = Vec::new();
let mut bookmark: Option<String> = None;
loop {
- let bm = bookmark.as_ref().map(|b| json!([b])).unwrap_or_else(|| json!([]));
+ let bm = bookmark
+ .as_ref()
+ .map(|b| json!([b]))
+ .unwrap_or_else(|| json!([]));
let (data, next) = self
.resource(
"BaseSearch",
@@ -918,11 +1184,19 @@ impl PinClient {
pub async fn typeahead(&self, term: &str) -> anyhow::Result<Vec<String>> {
let (data, _) = self
- .resource("AdvancedTypeahead", json!({ "pin_scope": "pins", "count": 20, "term": term }), "/")
+ .resource(
+ "AdvancedTypeahead",
+ json!({ "pin_scope": "pins", "count": 20, "term": term }),
+ "/",
+ )
.await?;
let mut out = Vec::new();
for it in data["items"].as_array().cloned().unwrap_or_default() {
- if let Some(t) = s(&it["label"]).or_else(|| s(&it["title"])).or_else(|| s(&it["query"])).or_else(|| s(&it["term"])) {
+ if let Some(t) = s(&it["label"])
+ .or_else(|| s(&it["title"]))
+ .or_else(|| s(&it["query"]))
+ .or_else(|| s(&it["term"]))
+ {
if !out.contains(&t) {
out.push(t);
}
@@ -943,11 +1217,19 @@ impl PinClient {
.ok_or_else(|| anyhow!("o pin.it nao redirecionou"))?;
// às vezes há um segundo pulo (pinterest.com/pin/…/sent/?…)
for _ in 0..3 {
- if parse_target(&loc).map(|t| !matches!(t, Target::Short { .. })).unwrap_or(false) && !loc.ends_with("pinterest.com/") {
+ if parse_target(&loc)
+ .map(|t| !matches!(t, Target::Short { .. }))
+ .unwrap_or(false)
+ && !loc.ends_with("pinterest.com/")
+ {
break;
}
let r = self.http.get(&loc).send().await?;
- match r.headers().get(reqwest::header::LOCATION).and_then(|v| v.to_str().ok()) {
+ match r
+ .headers()
+ .get(reqwest::header::LOCATION)
+ .and_then(|v| v.to_str().ok())
+ {
Some(l) => loc = l.to_string(),
None => break,
}
@@ -957,7 +1239,9 @@ impl PinClient {
/// Desfaz o save de um pin seu (exige cookies com `csrftoken`).
pub async fn unsave(&self, pin_id: &str) -> anyhow::Result<()> {
- let csrf = self.csrf.clone().ok_or_else(|| anyhow!("para desfazer saves informe os cookies da sua sessao (com csrftoken)"))?;
+ let csrf = self.csrf.clone().ok_or_else(|| {
+ anyhow!("para desfazer saves informe os cookies da sua sessao (com csrftoken)")
+ })?;
let data = json!({ "options": { "id": pin_id }, "context": {} }).to_string();
let req = self
.http
@@ -969,8 +1253,15 @@ impl PinClient {
let status = resp.status();
let body: Value = resp.json().await.unwrap_or(Value::Null);
if !status.is_success() || body["resource_response"]["status"].as_str() != Some("success") {
- let msg = body["resource_response"]["error"]["message"].as_str().unwrap_or("falhou");
- return Err(anyhow!("nao consegui desfazer o save de {} (HTTP {}): {}", pin_id, status, msg));
+ let msg = body["resource_response"]["error"]["message"]
+ .as_str()
+ .unwrap_or("falhou");
+ return Err(anyhow!(
+ "nao consegui desfazer o save de {} (HTTP {}): {}",
+ pin_id,
+ status,
+ msg
+ ));
}
Ok(())
}
@@ -980,24 +1271,59 @@ impl PinClient {
match target {
Target::Board { user, slug } => {
let b = self.board(user, slug).await?;
- Ok((Feed::Board { board_id: b.id.clone(), include_sections: true }, b.name))
+ Ok((
+ Feed::Board {
+ board_id: b.id.clone(),
+ include_sections: true,
+ },
+ b.name,
+ ))
}
- Target::Section { user, slug, section } => {
+ Target::Section {
+ user,
+ slug,
+ section,
+ } => {
let b = self.board(user, slug).await?;
let secs = self.board_sections(&b.id).await?;
let sec = secs
.into_iter()
.find(|x| &x.slug == section || x.title.eq_ignore_ascii_case(section))
- .ok_or_else(|| anyhow!("secao '{}' nao encontrada no board {}", section, b.name))?;
- Ok((Feed::Section { section_id: sec.id }, format!("{} · {}", b.name, sec.title)))
+ .ok_or_else(|| {
+ anyhow!("secao '{}' nao encontrada no board {}", section, b.name)
+ })?;
+ Ok((
+ Feed::Section { section_id: sec.id },
+ format!("{} · {}", b.name, sec.title),
+ ))
}
- Target::User { username } => Ok((Feed::UserPins { username: username.clone() }, username.clone())),
- Target::UserCreated { username } => Ok((Feed::UserCreated { username: username.clone() }, format!("{} (criados)", username))),
- Target::Search { query, scope } => Ok((Feed::Search { query: query.clone(), scope: scope.clone() }, query.clone())),
- Target::Pin { id } => Ok((Feed::Related { pin_id: id.clone() }, format!("parecidos com {}", id))),
+ Target::User { username } => Ok((
+ Feed::UserPins {
+ username: username.clone(),
+ },
+ username.clone(),
+ )),
+ Target::UserCreated { username } => Ok((
+ Feed::UserCreated {
+ username: username.clone(),
+ },
+ format!("{} (criados)", username),
+ )),
+ Target::Search { query, scope } => Ok((
+ Feed::Search {
+ query: query.clone(),
+ scope: scope.clone(),
+ },
+ query.clone(),
+ )),
+ Target::Pin { id } => Ok((
+ Feed::Related { pin_id: id.clone() },
+ format!("parecidos com {}", id),
+ )),
Target::Short { code } => {
let url = self.resolve_short(code).await?;
- let t = parse_target(&url).ok_or_else(|| anyhow!("nao entendi o destino de pin.it/{}", code))?;
+ let t = parse_target(&url)
+ .ok_or_else(|| anyhow!("nao entendi o destino de pin.it/{}", code))?;
Box::pin(self.feed_for(&t)).await
}
}
@@ -1010,19 +1336,71 @@ mod tests {
#[test]
fn parses_targets() {
- assert_eq!(parse_target("https://www.pinterest.com/pin/8373949304441833/"), Some(Target::Pin { id: "8373949304441833".into() }));
- assert_eq!(parse_target("https://br.pinterest.com/pin/mid-century--8373949304441833/"), Some(Target::Pin { id: "8373949304441833".into() }));
- assert_eq!(parse_target("8373949304441833"), Some(Target::Pin { id: "8373949304441833".into() }));
- assert_eq!(parse_target("pin.it/2u3CBgh"), Some(Target::Short { code: "2u3CBgh".into() }));
- assert_eq!(parse_target("https://www.pinterest.com/pinterest/home-decor/"), Some(Target::Board { user: "pinterest".into(), slug: "home-decor".into() }));
+ assert_eq!(
+ parse_target("https://www.pinterest.com/pin/8373949304441833/"),
+ Some(Target::Pin {
+ id: "8373949304441833".into()
+ })
+ );
+ assert_eq!(
+ parse_target("https://br.pinterest.com/pin/mid-century--8373949304441833/"),
+ Some(Target::Pin {
+ id: "8373949304441833".into()
+ })
+ );
+ assert_eq!(
+ parse_target("8373949304441833"),
+ Some(Target::Pin {
+ id: "8373949304441833".into()
+ })
+ );
+ assert_eq!(
+ parse_target("pin.it/2u3CBgh"),
+ Some(Target::Short {
+ code: "2u3CBgh".into()
+ })
+ );
+ assert_eq!(
+ parse_target("https://www.pinterest.com/pinterest/home-decor/"),
+ Some(Target::Board {
+ user: "pinterest".into(),
+ slug: "home-decor".into()
+ })
+ );
assert_eq!(
parse_target("https://www.pinterest.fr/pinterest/home-decor/living-room/"),
- Some(Target::Section { user: "pinterest".into(), slug: "home-decor".into(), section: "living-room".into() })
+ Some(Target::Section {
+ user: "pinterest".into(),
+ slug: "home-decor".into(),
+ section: "living-room".into()
+ })
+ );
+ assert_eq!(
+ parse_target("https://www.pinterest.com/pinterest/"),
+ Some(Target::User {
+ username: "pinterest".into()
+ })
+ );
+ assert_eq!(
+ parse_target("https://www.pinterest.com/pinterest/_created/"),
+ Some(Target::UserCreated {
+ username: "pinterest".into()
+ })
+ );
+ assert_eq!(
+ parse_target("https://www.pinterest.com/search/videos/?q=cats&rs=typed"),
+ Some(Target::Search {
+ query: "cats".into(),
+ scope: "videos".into()
+ })
+ );
+ assert_eq!(
+ parse_target("mid century living room"),
+ Some(Target::Search {
+ query: "mid century living room".into(),
+ scope: "pins".into()
+ })
);
- assert_eq!(parse_target("https://www.pinterest.com/pinterest/"), Some(Target::User { username: "pinterest".into() }));
- assert_eq!(parse_target("https://www.pinterest.com/pinterest/_created/"), Some(Target::UserCreated { username: "pinterest".into() }));
- assert_eq!(parse_target("https://www.pinterest.com/search/videos/?q=cats&rs=typed"), Some(Target::Search { query: "cats".into(), scope: "videos".into() }));
- assert_eq!(parse_target("mid century living room"), Some(Target::Search { query: "mid century living room".into(), scope: "pins".into() }));
assert_eq!(parse_target("https://www.pinterest.com/settings/"), None);
}
@@ -1032,7 +1410,10 @@ mod tests {
to_originals("https://i.pinimg.com/236x/3e/57/c1/3e57c1b723b8e9d39b8c09f6c5efbfb0.jpg"),
"https://i.pinimg.com/originals/3e/57/c1/3e57c1b723b8e9d39b8c09f6c5efbfb0.jpg"
);
- assert_eq!(to_originals("https://example.com/a.jpg"), "https://example.com/a.jpg");
+ assert_eq!(
+ to_originals("https://example.com/a.jpg"),
+ "https://example.com/a.jpg"
+ );
}
#[test]
@@ -1051,19 +1432,31 @@ mod tests {
let p = parse_pin(&v).unwrap();
assert_eq!(p.kind, "video");
assert_eq!(p.image.unwrap().width, 1000);
- assert_eq!(p.video.as_ref().unwrap().mp4.as_deref(), Some("https://v1.pinimg.com/videos/mc/720p/a.mp4"));
- assert_eq!(p.video.unwrap().hls.as_deref(), Some("https://v1.pinimg.com/videos/iht/hls/v2/a.m3u8"));
+ assert_eq!(
+ p.video.as_ref().unwrap().mp4.as_deref(),
+ Some("https://v1.pinimg.com/videos/mc/720p/a.mp4")
+ );
+ assert_eq!(
+ p.video.unwrap().hls.as_deref(),
+ Some("https://v1.pinimg.com/videos/iht/hls/v2/a.m3u8")
+ );
assert_eq!(p.saves, 12);
assert_eq!(p.reactions, 5);
assert!(p.is_promoted);
assert!(p.ai.labeled);
assert_eq!(p.ai.keyword_level, 2);
- assert_eq!(p.board.unwrap().url.unwrap(), "https://www.pinterest.com/u/b/");
+ assert_eq!(
+ p.board.unwrap().url.unwrap(),
+ "https://www.pinterest.com/u/b/"
+ );
}
#[test]
fn cookie_header_from_raw_string() {
- assert_eq!(cookie_header(Some(" csrftoken=abc; _pinterest_sess=xyz ")).as_deref(), Some("csrftoken=abc; _pinterest_sess=xyz"));
+ assert_eq!(
+ cookie_header(Some(" csrftoken=abc; _pinterest_sess=xyz ")).as_deref(),
+ Some("csrftoken=abc; _pinterest_sess=xyz")
+ );
assert_eq!(cookie_header(Some("")), None);
assert_eq!(cookie_header(None), None);
}
@@ -1082,7 +1475,17 @@ mod live {
assert!(b.pin_count > 100, "{:?}", b);
let secs = c.board_sections(&b.id).await.unwrap();
assert!(!secs.is_empty());
- let (pins, next, _) = c.feed_page(&Feed::Board { board_id: b.id.clone(), include_sections: true }, None, 10).await.unwrap();
+ let (pins, next, _) = c
+ .feed_page(
+ &Feed::Board {
+ board_id: b.id.clone(),
+ include_sections: true,
+ },
+ None,
+ 10,
+ )
+ .await
+ .unwrap();
assert!(pins.len() >= 5, "{}", pins.len());
assert!(next.is_some());
let p = c.pin(&pins[0].id).await.unwrap();
@@ -1091,12 +1494,41 @@ mod live {
assert!(u.board_count > 10);
let boards = c.user_boards("pinterest").await.unwrap();
assert!(boards.len() > 10, "{}", boards.len());
- let (pins, _, guides) = c.feed_page(&Feed::Search { query: "mid century living room".into(), scope: "pins".into() }, None, 10).await.unwrap();
+ let (pins, _, guides) = c
+ .feed_page(
+ &Feed::Search {
+ query: "mid century living room".into(),
+ scope: "pins".into(),
+ },
+ None,
+ 10,
+ )
+ .await
+ .unwrap();
assert!(pins.len() >= 5);
assert!(!guides.is_empty(), "guides vazios");
- let (vids, _, _) = c.feed_page(&Feed::Search { query: "cats".into(), scope: "videos".into() }, None, 5).await.unwrap();
+ let (vids, _, _) = c
+ .feed_page(
+ &Feed::Search {
+ query: "cats".into(),
+ scope: "videos".into(),
+ },
+ None,
+ 5,
+ )
+ .await
+ .unwrap();
assert!(vids.iter().any(|v| v.video.is_some()), "nenhum video");
- let rel = c.collect(&Feed::Related { pin_id: p.id.clone() }, 8, |_| {}).await.unwrap();
+ let rel = c
+ .collect(
+ &Feed::Related {
+ pin_id: p.id.clone(),
+ },
+ 8,
+ |_| {},
+ )
+ .await
+ .unwrap();
assert!(rel.len() >= 4, "{}", rel.len());
let sug = c.typeahead("mid century").await.unwrap();
assert!(!sug.is_empty());
@@ -1104,22 +1536,43 @@ mod live {
assert!(!bs.is_empty());
// originais + dHash + paleta
let img = p.image.clone().or(p.image_large.clone()).unwrap();
- let (bytes, ext) = super::super::media::fetch_image(&c, &img.url).await.unwrap();
+ let (bytes, ext) = super::super::media::fetch_image(&c, &img.url)
+ .await
+ .unwrap();
assert!(bytes.len() > 1000);
- println!("orig {} bytes ext {} ({}x{})", bytes.len(), ext, img.width, img.height);
+ println!(
+ "orig {} bytes ext {} ({}x{})",
+ bytes.len(),
+ ext,
+ img.width,
+ img.height
+ );
let h = super::super::analysis::dhash(&bytes).unwrap();
assert_ne!(h, 0);
let samples = super::super::analysis::sample_pixels(&bytes, 500, true);
let pal = super::super::analysis::kmeans_palette(&samples, 5);
assert_eq!(pal.len(), 5);
- println!("palette {:?}", pal.iter().map(|s| s.hex.clone()).collect::<Vec<_>>());
+ println!(
+ "palette {:?}",
+ pal.iter().map(|s| s.hex.clone()).collect::<Vec<_>>()
+ );
}
#[tokio::test]
#[ignore]
async fn live_short_link() {
let c = PinClient::new(None).unwrap();
- let (pins, _, _) = c.feed_page(&Feed::Search { query: "cats".into(), scope: "pins".into() }, None, 1).await.unwrap();
+ let (pins, _, _) = c
+ .feed_page(
+ &Feed::Search {
+ query: "cats".into(),
+ scope: "pins".into(),
+ },
+ None,
+ 1,
+ )
+ .await
+ .unwrap();
let p = &pins[0];
assert!(p.url.contains("/pin/"));
}
diff --git a/src-tauri/omniget-core/src/core/tools/pinterest/export.rs b/src-tauri/omniget-core/src/core/tools/pinterest/export.rs
index 90cbc335..48be7e44 100644
--- a/src-tauri/omniget-core/src/core/tools/pinterest/export.rs
+++ b/src-tauri/omniget-core/src/core/tools/pinterest/export.rs
@@ -23,9 +23,32 @@ fn csv_cell(s: &str) -> String {
}
pub const CSV_HEADER: &[&str] = &[
- "id", "pin_url", "title", "description", "alt_text", "link", "domain", "board", "section", "pinner", "creator", "created_at",
- "kind", "image_url", "width", "height", "video_url", "saves", "repins", "comments", "reactions", "promoted", "ai_labeled",
- "ai_keyword", "dominant_color", "local_files",
+ "id",
+ "pin_url",
+ "title",
+ "description",
+ "alt_text",
+ "link",
+ "domain",
+ "board",
+ "section",
+ "pinner",
+ "creator",
+ "created_at",
+ "kind",
+ "image_url",
+ "width",
+ "height",
+ "video_url",
+ "saves",
+ "repins",
+ "comments",
+ "reactions",
+ "promoted",
+ "ai_labeled",
+ "ai_keyword",
+ "dominant_color",
+ "local_files",
];
pub fn csv(pins: &[Pin], files: &HashMap<String, Vec<String>>) -> String {
@@ -42,16 +65,28 @@ pub fn csv(pins: &[Pin], files: &HashMap<String, Vec<String>>) -> String {
p.alt_text.clone(),
p.link.clone().unwrap_or_default(),
p.domain.clone().unwrap_or_default(),
- p.board.as_ref().and_then(|b| b.name.clone()).unwrap_or_default(),
+ p.board
+ .as_ref()
+ .and_then(|b| b.name.clone())
+ .unwrap_or_default(),
p.section.clone().unwrap_or_default(),
- p.pinner.as_ref().and_then(|x| x.username.clone()).unwrap_or_default(),
- p.creator.as_ref().and_then(|x| x.username.clone()).unwrap_or_default(),
+ p.pinner
+ .as_ref()
+ .and_then(|x| x.username.clone())
+ .unwrap_or_default(),
+ p.creator
+ .as_ref()
+ .and_then(|x| x.username.clone())
+ .unwrap_or_default(),
p.created_at.clone().unwrap_or_default(),
p.kind.clone(),
img.map(|m| m.url.clone()).unwrap_or_default(),
img.map(|m| m.width.to_string()).unwrap_or_default(),
img.map(|m| m.height.to_string()).unwrap_or_default(),
- p.video.as_ref().and_then(|v| v.mp4.clone().or_else(|| v.hls.clone())).unwrap_or_default(),
+ p.video
+ .as_ref()
+ .and_then(|v| v.mp4.clone().or_else(|| v.hls.clone()))
+ .unwrap_or_default(),
p.saves.to_string(),
p.repins.to_string(),
p.comments.to_string(),
@@ -62,14 +97,22 @@ pub fn csv(pins: &[Pin], files: &HashMap<String, Vec<String>>) -> String {
p.dominant_color.clone().unwrap_or_default(),
files.get(&p.id).map(|f| f.join(" | ")).unwrap_or_default(),
];
- out.push_str(&row.iter().map(|c| csv_cell(c)).collect::<Vec<_>>().join(","));
+ out.push_str(
+ &row.iter()
+ .map(|c| csv_cell(c))
+ .collect::<Vec<_>>()
+ .join(","),
+ );
out.push('\n');
}
out
}
fn esc(s: &str) -> String {
- s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
+ s.replace('&', "&amp;")
+ .replace('<', "&lt;")
+ .replace('>', "&gt;")
+ .replace('"', "&quot;")
}
/// Caminho relativo à pasta da galeria (os arquivos ficam dentro dela).
@@ -84,7 +127,13 @@ fn rel(root: &str, file: &str) -> String {
/// Galeria HTML de arquivo único. `files` aponta para os arquivos locais;
/// sem arquivo local a imagem vem do CDN (736x).
-pub fn html_gallery(title: &str, subtitle: &str, pins: &[Pin], files: &HashMap<String, Vec<String>>, root: &str) -> String {
+pub fn html_gallery(
+ title: &str,
+ subtitle: &str,
+ pins: &[Pin],
+ files: &HashMap<String, Vec<String>>,
+ root: &str,
+) -> String {
let mut sections: Vec<String> = Vec::new();
for p in pins {
let s = p.section.clone().unwrap_or_default();
@@ -99,11 +148,19 @@ pub fn html_gallery(title: &str, subtitle: &str, pins: &[Pin], files: &HashMap<S
f.iter()
.find(|x| {
let l = x.to_lowercase();
- l.ends_with(".jpg") || l.ends_with(".jpeg") || l.ends_with(".png") || l.ends_with(".webp") || l.ends_with(".gif")
+ l.ends_with(".jpg")
+ || l.ends_with(".jpeg")
+ || l.ends_with(".png")
+ || l.ends_with(".webp")
+ || l.ends_with(".gif")
})
.cloned()
});
- let video_local = files.get(&p.id).and_then(|f| f.iter().find(|x| x.to_lowercase().ends_with(".mp4")).cloned());
+ let video_local = files.get(&p.id).and_then(|f| {
+ f.iter()
+ .find(|x| x.to_lowercase().ends_with(".mp4"))
+ .cloned()
+ });
let src = local
.map(|f| rel(root, &f))
.or_else(|| p.image_large.as_ref().map(|m| m.url.clone()))
@@ -112,20 +169,46 @@ pub fn html_gallery(title: &str, subtitle: &str, pins: &[Pin], files: &HashMap<S
let sec = p.section.clone().unwrap_or_default();
let text = format!("{} {} {}", p.title, p.description, p.alt_text).to_lowercase();
let media = if let Some(v) = video_local {
- format!(r#"<video src="{}" controls muted loop playsinline poster="{}"></video>"#, esc(&rel(root, &v)), esc(&src))
+ format!(
+ r#"<video src="{}" controls muted loop playsinline poster="{}"></video>"#,
+ esc(&rel(root, &v)),
+ esc(&src)
+ )
} else {
- format!(r#"<img src="{}" alt="{}" loading="lazy">"#, esc(&src), esc(&p.title))
+ format!(
+ r#"<img src="{}" alt="{}" loading="lazy">"#,
+ esc(&src),
+ esc(&p.title)
+ )
};
let link = p
.link
.as_ref()
- .map(|l| format!(r#" · <a href="{}" target="_blank" rel="noopener">{}</a>"#, esc(l), esc(p.domain.as_deref().unwrap_or("site"))))
+ .map(|l| {
+ format!(
+ r#" · <a href="{}" target="_blank" rel="noopener">{}</a>"#,
+ esc(l),
+ esc(p.domain.as_deref().unwrap_or("site"))
+ )
+ })
.unwrap_or_default();
let badges = format!(
"{}{}{}",
- if p.kind == "video" { r#"<span class="b">vídeo</span>"# } else { "" },
- if p.is_promoted { r#"<span class="b warn">anúncio</span>"# } else { "" },
- if p.ai.labeled || p.ai.keyword_level >= 2 { r#"<span class="b ai">IA</span>"# } else { "" },
+ if p.kind == "video" {
+ r#"<span class="b">vídeo</span>"#
+ } else {
+ ""
+ },
+ if p.is_promoted {
+ r#"<span class="b warn">anúncio</span>"#
+ } else {
+ ""
+ },
+ if p.ai.labeled || p.ai.keyword_level >= 2 {
+ r#"<span class="b ai">IA</span>"#
+ } else {
+ ""
+ },
);
items.push_str(&format!(
r#"<figure data-sec="{sec}" data-text="{text}" data-kind="{kind}">{media}<figcaption><strong>{title}</strong><span class="meta">{saves} saves{link}</span>{badges}<a class="open" href="{url}" target="_blank" rel="noopener">abrir no Pinterest</a></figcaption></figure>
@@ -143,7 +226,13 @@ pub fn html_gallery(title: &str, subtitle: &str, pins: &[Pin], files: &HashMap<S
}
let section_buttons: String = sections
.iter()
- .map(|s| format!(r#"<button data-sec="{0}">{1}</button>"#, esc(s), if s.is_empty() { "sem seção" } else { s }))
+ .map(|s| {
+ format!(
+ r#"<button data-sec="{0}">{1}</button>"#,
+ esc(s),
+ if s.is_empty() { "sem seção" } else { s }
+ )
+ })
.collect();
format!(
r##"<!doctype html><html lang="pt"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{title}</title>
@@ -174,7 +263,11 @@ q.addEventListener('input',apply);btns.forEach(b=>b.addEventListener('click',()=
</script></body></html>"##,
title = esc(title),
subtitle = esc(subtitle),
- secs = if sections.len() > 1 { section_buttons } else { String::new() },
+ secs = if sections.len() > 1 {
+ section_buttons
+ } else {
+ String::new()
+ },
items = items,
)
}
@@ -185,7 +278,11 @@ mod tests {
#[test]
fn csv_escapes() {
- let p = Pin { id: "1".into(), title: "a, \"b\"".into(), ..Default::default() };
+ let p = Pin {
+ id: "1".into(),
+ title: "a, \"b\"".into(),
+ ..Default::default()
+ };
let out = csv(&[p], &HashMap::new());
assert!(out.lines().nth(1).unwrap().contains("\"a, \"\"b\"\"\""));
assert!(out.starts_with("id,pin_url,title"));
@@ -193,9 +290,18 @@ mod tests {
#[test]
fn gallery_has_items_and_sections() {
- let mut a = Pin { id: "1".into(), title: "One".into(), section: Some("Sala".into()), ..Default::default() };
+ let mut a = Pin {
+ id: "1".into(),
+ title: "One".into(),
+ section: Some("Sala".into()),
+ ..Default::default()
+ };
a.thumb = Some("https://i.pinimg.com/236x/x.jpg".into());
- let b = Pin { id: "2".into(), title: "Two".into(), ..Default::default() };
+ let b = Pin {
+ id: "2".into(),
+ title: "Two".into(),
+ ..Default::default()
+ };
let html = html_gallery("Board", "2 pins", &[a, b], &HashMap::new(), "/tmp/x");
assert!(html.contains("<figure data-sec=\"Sala\""));
assert!(html.contains("sem seção"));
diff --git a/src-tauri/omniget-core/src/core/tools/pinterest/media.rs b/src-tauri/omniget-core/src/core/tools/pinterest/media.rs
index afb51a90..72c49c35 100644
--- a/src-tauri/omniget-core/src/core/tools/pinterest/media.rs
+++ b/src-tauri/omniget-core/src/core/tools/pinterest/media.rs
@@ -56,13 +56,22 @@ pub const ARCHIVE: &str = ".omniget-pinterest.txt";
pub fn load_archive(dest: &Path) -> HashSet<String> {
std::fs::read_to_string(dest.join(ARCHIVE))
- .map(|s| s.lines().map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect())
+ .map(|s| {
+ s.lines()
+ .map(|l| l.trim().to_string())
+ .filter(|l| !l.is_empty())
+ .collect()
+ })
.unwrap_or_default()
}
pub fn append_archive(dest: &Path, id: &str) {
use std::io::Write;
- if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dest.join(ARCHIVE)) {
+ if let Ok(mut f) = std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(dest.join(ARCHIVE))
+ {
let _ = writeln!(f, "{}", id);
}
}
@@ -117,7 +126,13 @@ pub fn candidates(url: &str) -> Vec<String> {
pub async fn fetch_image(client: &PinClient, url: &str) -> anyhow::Result<(Vec<u8>, &'static str)> {
let mut last = String::new();
for cand in candidates(url) {
- let resp = match client.http().get(&cand).header("Referer", "https://www.pinterest.com/").send().await {
+ let resp = match client
+ .http()
+ .get(&cand)
+ .header("Referer", "https://www.pinterest.com/")
+ .send()
+ .await
+ {
Ok(r) => r,
Err(e) => {
last = e.to_string();
@@ -128,7 +143,12 @@ pub async fn fetch_image(client: &PinClient, url: &str) -> anyhow::Result<(Vec<u
last = format!("HTTP {} em {}", resp.status(), cand);
continue;
}
- let ct = resp.headers().get(reqwest::header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("").to_string();
+ let ct = resp
+ .headers()
+ .get(reqwest::header::CONTENT_TYPE)
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("")
+ .to_string();
let bytes = resp.bytes().await?.to_vec();
if bytes.len() < 64 {
last = format!("resposta vazia em {}", cand);
@@ -160,7 +180,11 @@ fn webp_to_png(bytes: &[u8]) -> anyhow::Result<Vec<u8>> {
pub fn base_name(pin: &Pin, naming: &str) -> String {
let title = pin.title.trim();
- let title = if title.is_empty() { pin.alt_text.trim() } else { title };
+ let title = if title.is_empty() {
+ pin.alt_text.trim()
+ } else {
+ title
+ };
let short: String = title.chars().take(70).collect();
let clean = super::super::sanitize_name(&short);
match naming {
@@ -185,7 +209,12 @@ pub async fn download_video(client: &PinClient, video: &Video, out: &Path) -> an
std::fs::create_dir_all(p)?;
}
if let Some(mp4) = &video.mp4 {
- let resp = client.http().get(mp4).header("Referer", "https://www.pinterest.com/").send().await?;
+ let resp = client
+ .http()
+ .get(mp4)
+ .header("Referer", "https://www.pinterest.com/")
+ .send()
+ .await?;
if resp.status().is_success() {
let bytes = resp.bytes().await?;
if bytes.len() > 1024 {
@@ -194,7 +223,10 @@ pub async fn download_video(client: &PinClient, video: &Video, out: &Path) -> an
}
}
}
- let hls = video.hls.as_ref().ok_or_else(|| anyhow!("pin sem URL de video"))?;
+ let hls = video
+ .hls
+ .as_ref()
+ .ok_or_else(|| anyhow!("pin sem URL de video"))?;
let ffmpeg = crate::core::dependencies::ensure_ffmpeg().await?;
let o = crate::core::process::command(&ffmpeg)
.args([
@@ -222,24 +254,33 @@ pub async fn download_video(client: &PinClient, video: &Video, out: &Path) -> an
.await?;
if !o.status.success() {
let err = String::from_utf8_lossy(&o.stderr);
- return Err(anyhow!("ffmpeg nao converteu o video: {}", err.lines().last().unwrap_or("").trim()));
+ return Err(anyhow!(
+ "ffmpeg nao converteu o video: {}",
+ err.lines().last().unwrap_or("").trim()
+ ));
}
Ok(())
}
/// Baixa tudo de um pin para `dir`. Devolve os caminhos gravados.
-pub async fn download_pin(client: &PinClient, pin: &Pin, dir: &Path, opts: &DownloadOptions) -> anyhow::Result<Vec<String>> {
+pub async fn download_pin(
+ client: &PinClient,
+ pin: &Pin,
+ dir: &Path,
+ opts: &DownloadOptions,
+) -> anyhow::Result<Vec<String>> {
let base = base_name(pin, &opts.naming);
let mut files = Vec::new();
- let save_image = |bytes: Vec<u8>, ext: &str, suffix: &str| -> anyhow::Result<(PathBuf, Vec<u8>)> {
- let (bytes, ext) = if ext == "webp" && opts.convert_webp {
- (webp_to_png(&bytes)?, "png")
- } else {
- (bytes, ext)
+ let save_image =
+ |bytes: Vec<u8>, ext: &str, suffix: &str| -> anyhow::Result<(PathBuf, Vec<u8>)> {
+ let (bytes, ext) = if ext == "webp" && opts.convert_webp {
+ (webp_to_png(&bytes)?, "png")
+ } else {
+ (bytes, ext)
+ };
+ Ok((dir.join(format!("{}{}.{}", base, suffix, ext)), bytes))
};
- Ok((dir.join(format!("{}{}.{}", base, suffix, ext)), bytes))
- };
let has_extras = !pin.extras.is_empty();
if opts.images && !has_extras {
@@ -304,23 +345,46 @@ mod tests {
#[test]
fn candidate_chain() {
- let c = candidates("https://i.pinimg.com/originals/3e/57/c1/3e57c1b723b8e9d39b8c09f6c5efbfb0.jpg");
- assert_eq!(c[0], "https://i.pinimg.com/originals/3e/57/c1/3e57c1b723b8e9d39b8c09f6c5efbfb0.jpg");
- assert!(c.contains(&"https://i.pinimg.com/originals/3e/57/c1/3e57c1b723b8e9d39b8c09f6c5efbfb0.png".to_string()));
- assert!(c.contains(&"https://i.pinimg.com/736x/3e/57/c1/3e57c1b723b8e9d39b8c09f6c5efbfb0.jpg".to_string()));
- assert_eq!(candidates("https://x/y.jpg"), vec!["https://x/y.jpg".to_string()]);
+ let c = candidates(
+ "https://i.pinimg.com/originals/3e/57/c1/3e57c1b723b8e9d39b8c09f6c5efbfb0.jpg",
+ );
+ assert_eq!(
+ c[0],
+ "https://i.pinimg.com/originals/3e/57/c1/3e57c1b723b8e9d39b8c09f6c5efbfb0.jpg"
+ );
+ assert!(c.contains(
+ &"https://i.pinimg.com/originals/3e/57/c1/3e57c1b723b8e9d39b8c09f6c5efbfb0.png"
+ .to_string()
+ ));
+ assert!(c.contains(
+ &"https://i.pinimg.com/736x/3e/57/c1/3e57c1b723b8e9d39b8c09f6c5efbfb0.jpg".to_string()
+ ));
+ assert_eq!(
+ candidates("https://x/y.jpg"),
+ vec!["https://x/y.jpg".to_string()]
+ );
}
#[test]
fn sniff() {
- assert_eq!(sniff_ext(b"\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\x01\x01"), Some("jpg"));
+ assert_eq!(
+ sniff_ext(b"\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\x01\x01"),
+ Some("jpg")
+ );
assert_eq!(sniff_ext(b"RIFF\x00\x00\x00\x00WEBPVP8 "), Some("webp"));
- assert_eq!(sniff_ext(b"GIF89a\x00\x00\x00\x00\x00\x00\x00"), Some("gif"));
+ assert_eq!(
+ sniff_ext(b"GIF89a\x00\x00\x00\x00\x00\x00\x00"),
+ Some("gif")
+ );
}
#[test]
fn names() {
- let mut p = Pin { id: "42".into(), title: "Mid Century: Living / Room".into(), ..Default::default() };
+ let mut p = Pin {
+ id: "42".into(),
+ title: "Mid Century: Living / Room".into(),
+ ..Default::default()
+ };
assert_eq!(base_name(&p, "id"), "42");
assert!(base_name(&p, "title-id").ends_with("-42"));
p.title.clear();
@@ -340,12 +404,41 @@ mod live {
let c = PinClient::new(None).unwrap();
let dir = std::env::temp_dir().join("omniget-pinterest-live");
let _ = std::fs::remove_dir_all(&dir);
- let opts = DownloadOptions { dest: dir.to_string_lossy().to_string(), images: true, videos: true, convert_webp: true, naming: "title-id".into(), sidecar: true, skip_downloaded: true, section_folders: true };
- let (pins, _, _) = c.feed_page(&Feed::Search { query: "mid century living room".into(), scope: "pins".into() }, None, 3).await.unwrap();
+ let opts = DownloadOptions {
+ dest: dir.to_string_lossy().to_string(),
+ images: true,
+ videos: true,
+ convert_webp: true,
+ naming: "title-id".into(),
+ sidecar: true,
+ skip_downloaded: true,
+ section_folders: true,
+ };
+ let (pins, _, _) = c
+ .feed_page(
+ &Feed::Search {
+ query: "mid century living room".into(),
+ scope: "pins".into(),
+ },
+ None,
+ 3,
+ )
+ .await
+ .unwrap();
let files = download_pin(&c, &pins[0], &dir, &opts).await.unwrap();
println!("image files: {:?}", files);
assert!(!files.is_empty());
- let (vids, _, _) = c.feed_page(&Feed::Search { query: "cats".into(), scope: "videos".into() }, None, 3).await.unwrap();
+ let (vids, _, _) = c
+ .feed_page(
+ &Feed::Search {
+ query: "cats".into(),
+ scope: "videos".into(),
+ },
+ None,
+ 3,
+ )
+ .await
+ .unwrap();
let v = vids.iter().find(|p| p.video.is_some()).expect("video pin");
let files = download_pin(&c, v, &dir, &opts).await.unwrap();
println!("video files: {:?}", files);
@@ -354,7 +447,8 @@ mod live {
let size = std::fs::metadata(mp4).unwrap().len();
println!("mp4 {} bytes", size);
assert!(size > 20_000);
- let mut m: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();
+ let mut m: std::collections::HashMap<String, Vec<String>> =
+ std::collections::HashMap::new();
m.insert(pins[0].id.clone(), files.clone());
let html = super::super::export::html_gallery("t", "s", &pins, &m, &dir.to_string_lossy());
std::fs::write(dir.join("index.html"), html).unwrap();
diff --git a/src-tauri/omniget-core/src/core/tools/pricing.rs b/src-tauri/omniget-core/src/core/tools/pricing.rs
index 46e366c5..76b1e95f 100644
--- a/src-tauri/omniget-core/src/core/tools/pricing.rs
+++ b/src-tauri/omniget-core/src/core/tools/pricing.rs
@@ -8,7 +8,8 @@ use std::path::PathBuf;
use anyhow::anyhow;
use serde::Serialize;
-const LITELLM_URL: &str = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
+const LITELLM_URL: &str =
+ "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
const MAX_AGE: std::time::Duration = std::time::Duration::from_secs(24 * 3600);
#[derive(Debug, Clone, Serialize)]
@@ -115,7 +116,10 @@ pub async fn info(force_refresh: bool) -> anyhow::Result<PricingInfo> {
.and_then(|m| m.modified().ok())
.map(|t| chrono::DateTime::<chrono::Utc>::from(t).to_rfc3339());
Ok(PricingInfo {
- models: v.as_object().map(|o| o.len().saturating_sub(1)).unwrap_or(0),
+ models: v
+ .as_object()
+ .map(|o| o.len().saturating_sub(1))
+ .unwrap_or(0),
updated_at: updated,
path: path.map(|p| p.to_string_lossy().to_string()),
})
@@ -124,13 +128,26 @@ pub async fn info(force_refresh: bool) -> anyhow::Result<PricingInfo> {
/// Busca por substring nas chaves; todas as palavras precisam bater.
pub async fn search(query: &str, mode: &str, limit: usize) -> anyhow::Result<Vec<ModelPrice>> {
let v = load(false).await?;
- let obj = v.as_object().ok_or_else(|| anyhow!("tabela de precos invalida"))?;
- let tokens: Vec<String> = query.to_lowercase().split_whitespace().map(|s| s.to_string()).collect();
+ let obj = v
+ .as_object()
+ .ok_or_else(|| anyhow!("tabela de precos invalida"))?;
+ let tokens: Vec<String> = query
+ .to_lowercase()
+ .split_whitespace()
+ .map(|s| s.to_string())
+ .collect();
let mut out: Vec<ModelPrice> = obj
.iter()
.filter(|(k, _)| *k != "sample_spec")
.filter(|(k, val)| {
- let hay = format!("{} {}", k.to_lowercase(), val["litellm_provider"].as_str().unwrap_or("").to_lowercase());
+ let hay = format!(
+ "{} {}",
+ k.to_lowercase(),
+ val["litellm_provider"]
+ .as_str()
+ .unwrap_or("")
+ .to_lowercase()
+ );
tokens.iter().all(|t| hay.contains(t))
&& (mode.is_empty() || val["mode"].as_str() == Some(mode))
})
@@ -151,7 +168,15 @@ pub async fn price_for(model: &str) -> Option<ModelPrice> {
if let Some((_, rest)) = m.split_once('/') {
candidates.push(rest.to_string());
}
- for p in ["openai/", "anthropic/", "gemini/", "openrouter/", "groq/", "deepseek/", "mistral/"] {
+ for p in [
+ "openai/",
+ "anthropic/",
+ "gemini/",
+ "openrouter/",
+ "groq/",
+ "deepseek/",
+ "mistral/",
+ ] {
candidates.push(format!("{}{}", p, m));
}
// "claude-sonnet-4-5-20250929" -> "claude-sonnet-4-5"
diff --git a/src-tauri/omniget-core/src/core/tools/rename.rs b/src-tauri/omniget-core/src/core/tools/rename.rs
index 62349593..790e1a31 100644
--- a/src-tauri/omniget-core/src/core/tools/rename.rs
+++ b/src-tauri/omniget-core/src/core/tools/rename.rs
@@ -55,7 +55,10 @@ pub fn expand_tokens(template: &str, n: u32, name: &str, ext: &str) -> String {
re.replace_all(template, |c: &regex::Captures| {
let key = &c[1];
if key.starts_with('n') {
- let pad = c.get(2).and_then(|m| m.as_str().parse::<usize>().ok()).unwrap_or(1);
+ let pad = c
+ .get(2)
+ .and_then(|m| m.as_str().parse::<usize>().ok())
+ .unwrap_or(1);
format!("{:0width$}", n, width = pad)
} else if key == "name" {
name.to_string()
@@ -84,12 +87,22 @@ pub fn plan(opts: &RenameOptions) -> Result<Vec<RenamePlan>, String> {
let mut n = opts.counter_start;
for f in &opts.files {
let p = Path::new(f);
- let file_name = p.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
+ let file_name = p
+ .file_name()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_default();
let (stem, ext) = match (p.file_stem(), p.extension()) {
- (Some(s), Some(e)) => (s.to_string_lossy().to_string(), e.to_string_lossy().to_string()),
+ (Some(s), Some(e)) => (
+ s.to_string_lossy().to_string(),
+ e.to_string_lossy().to_string(),
+ ),
_ => (file_name.clone(), String::new()),
};
- let subject = if opts.apply_to_extension { file_name.clone() } else { stem.clone() };
+ let subject = if opts.apply_to_extension {
+ file_name.clone()
+ } else {
+ stem.clone()
+ };
let replacement = expand_tokens(&opts.replacement, n, &stem, &ext);
let mut new = match &re {
Some(re) => re.replace_all(&subject, replacement.as_str()).to_string(),
@@ -102,13 +115,22 @@ pub fn plan(opts: &RenameOptions) -> Result<Vec<RenamePlan>, String> {
"title" => title_case(&new),
_ => new,
};
- let new_name = if opts.apply_to_extension || ext.is_empty() { new } else { format!("{}.{}", new, ext) };
+ let new_name = if opts.apply_to_extension || ext.is_empty() {
+ new
+ } else {
+ format!("{}.{}", new, ext)
+ };
let new_name = super::sanitize_name(&new_name);
let to = p.with_file_name(&new_name);
let to_s = to.to_string_lossy().to_string();
let changed = new_name != file_name;
let conflict = changed && (to.exists() || !targets.insert(to_s.to_lowercase()));
- out.push(RenamePlan { from: f.clone(), to: to_s, changed, conflict });
+ out.push(RenamePlan {
+ from: f.clone(),
+ to: to_s,
+ changed,
+ conflict,
+ });
if changed {
n += 1;
}
@@ -135,7 +157,10 @@ mod tests {
#[test]
fn tokens_and_regex() {
let opts = RenameOptions {
- files: vec!["/x/Aula 01 - intro.mp4".into(), "/x/Aula 02 - loops.mp4".into()],
+ files: vec![
+ "/x/Aula 01 - intro.mp4".into(),
+ "/x/Aula 02 - loops.mp4".into(),
+ ],
pattern: r"^Aula (\d+) - ".into(),
replacement: "{n:2}. ".into(),
case_insensitive: false,
diff --git a/src-tauri/omniget-core/src/core/tools/ryd.rs b/src-tauri/omniget-core/src/core/tools/ryd.rs
index 7dc1e6f8..49b718dc 100644
--- a/src-tauri/omniget-core/src/core/tools/ryd.rs
+++ b/src-tauri/omniget-core/src/core/tools/ryd.rs
@@ -23,9 +23,13 @@ pub struct Votes {
}
pub async fn votes(input: &str) -> anyhow::Result<Votes> {
- let id = super::sponsorblock::video_id(input).ok_or_else(|| anyhow!("nao reconheci um video do YouTube em: {}", input))?;
+ let id = super::sponsorblock::video_id(input)
+ .ok_or_else(|| anyhow!("nao reconheci um video do YouTube em: {}", input))?;
let client = super::client()?;
- let resp = client.get(format!("{}/votes?videoId={}", API, id)).send().await?;
+ let resp = client
+ .get(format!("{}/votes?videoId={}", API, id))
+ .send()
+ .await?;
if !resp.status().is_success() {
return Err(anyhow!("Return YouTube Dislike: HTTP {}", resp.status()));
}
diff --git a/src-tauri/omniget-core/src/core/tools/screen_record.rs b/src-tauri/omniget-core/src/core/tools/screen_record.rs
index 6bac2b20..a0d4dc42 100644
--- a/src-tauri/omniget-core/src/core/tools/screen_record.rs
+++ b/src-tauri/omniget-core/src/core/tools/screen_record.rs
@@ -79,8 +79,13 @@ pub fn state() -> RecordState {
RecordState {
running: s.is_some(),
replay: s.as_ref().map(|s| s.ring_dir.is_some()).unwrap_or(false),
- seconds: s.as_ref().map(|s| s.started.elapsed().as_secs()).unwrap_or(0),
- output: s.as_ref().and_then(|s| s.output.as_ref().map(|p| p.to_string_lossy().to_string())),
+ seconds: s
+ .as_ref()
+ .map(|s| s.started.elapsed().as_secs())
+ .unwrap_or(0),
+ output: s
+ .as_ref()
+ .and_then(|s| s.output.as_ref().map(|p| p.to_string_lossy().to_string())),
last_saved: LAST_SAVED.lock().unwrap_or_else(|e| e.into_inner()).clone(),
error: ERROR.lock().unwrap_or_else(|e| e.into_inner()).clone(),
}
@@ -90,8 +95,21 @@ pub fn state() -> RecordState {
pub async fn sources() -> Vec<Source> {
let mut out = Vec::new();
if cfg!(target_os = "macos") {
- let Ok(ffmpeg) = crate::core::dependencies::ensure_ffmpeg().await else { return out };
- let o = crate::core::process::command(&ffmpeg).args(["-hide_banner", "-f", "avfoundation", "-list_devices", "true", "-i", ""]).output().await;
+ let Ok(ffmpeg) = crate::core::dependencies::ensure_ffmpeg().await else {
+ return out;
+ };
+ let o = crate::core::process::command(&ffmpeg)
+ .args([
+ "-hide_banner",
+ "-f",
+ "avfoundation",
+ "-list_devices",
+ "true",
+ "-i",
+ "",
+ ])
+ .output()
+ .await;
if let Ok(o) = o {
let text = String::from_utf8_lossy(&o.stderr);
let mut kind = "";
@@ -111,29 +129,59 @@ pub async fn sources() -> Vec<Source> {
if let Some(j) = l[i..].find(']') {
let idx = &l[i + 1..i + j];
let name = l[i + j + 1..].trim();
- if idx.chars().all(|c| c.is_ascii_digit()) && (kind == "audio" || name.starts_with("Capture screen")) {
- out.push(Source { id: idx.to_string(), name: name.to_string(), kind: kind.into() });
+ if idx.chars().all(|c| c.is_ascii_digit())
+ && (kind == "audio" || name.starts_with("Capture screen"))
+ {
+ out.push(Source {
+ id: idx.to_string(),
+ name: name.to_string(),
+ kind: kind.into(),
+ });
}
}
}
}
}
} else if cfg!(target_os = "windows") {
- out.push(Source { id: "desktop".into(), name: "Área de trabalho (todas as telas)".into(), kind: "screen".into() });
+ out.push(Source {
+ id: "desktop".into(),
+ name: "Área de trabalho (todas as telas)".into(),
+ kind: "screen".into(),
+ });
for d in super::dictation::devices().await {
- out.push(Source { id: d.id, name: d.name, kind: "audio".into() });
+ out.push(Source {
+ id: d.id,
+ name: d.name,
+ kind: "audio".into(),
+ });
}
} else {
let display = std::env::var("DISPLAY").unwrap_or_else(|_| ":0".into());
- out.push(Source { id: format!("{}.0", display), name: format!("X11 {}", display), kind: "screen".into() });
+ out.push(Source {
+ id: format!("{}.0", display),
+ name: format!("X11 {}", display),
+ kind: "screen".into(),
+ });
for d in super::dictation::devices().await {
- out.push(Source { id: d.id, name: d.name, kind: "audio".into() });
+ out.push(Source {
+ id: d.id,
+ name: d.name,
+ kind: "audio".into(),
+ });
}
- if let Ok(o) = crate::core::process::command("pactl").args(["list", "short", "sources"]).output().await {
+ if let Ok(o) = crate::core::process::command("pactl")
+ .args(["list", "short", "sources"])
+ .output()
+ .await
+ {
for l in String::from_utf8_lossy(&o.stdout).lines() {
let cols: Vec<&str> = l.split('\t').collect();
if cols.len() > 1 && cols[1].ends_with(".monitor") {
- out.push(Source { id: cols[1].to_string(), name: format!("Áudio do sistema ({})", cols[1]), kind: "audio".into() });
+ out.push(Source {
+ id: cols[1].to_string(),
+ name: format!("Áudio do sistema ({})", cols[1]),
+ kind: "audio".into(),
+ });
}
}
}
@@ -146,29 +194,94 @@ fn stamp() -> String {
}
fn videos_dir() -> PathBuf {
- dirs::video_dir().or_else(dirs::home_dir).unwrap_or_default().join("OmniGet")
+ dirs::video_dir()
+ .or_else(dirs::home_dir)
+ .unwrap_or_default()
+ .join("OmniGet")
}
fn build_args(opts: &RecordOptions, target: &Path, ring: bool) -> Vec<String> {
- let mut a: Vec<String> = vec!["-y".into(), "-hide_banner".into(), "-loglevel".into(), "error".into()];
+ let mut a: Vec<String> = vec![
+ "-y".into(),
+ "-hide_banner".into(),
+ "-loglevel".into(),
+ "error".into(),
+ ];
let fps = opts.fps.clamp(5, 120).to_string();
if cfg!(target_os = "macos") {
- a.extend(["-f".into(), "avfoundation".into(), "-framerate".into(), fps.clone(), "-capture_cursor".into(), if opts.cursor { "1".into() } else { "0".into() }, "-pix_fmt".into(), "uyvy422".into()]);
- let screen = if opts.screen.is_empty() { "1".to_string() } else { opts.screen.clone() };
- let audio = if opts.audio.is_empty() { "none".to_string() } else { opts.audio.clone() };
+ a.extend([
+ "-f".into(),
+ "avfoundation".into(),
+ "-framerate".into(),
+ fps.clone(),
+ "-capture_cursor".into(),
+ if opts.cursor { "1".into() } else { "0".into() },
+ "-pix_fmt".into(),
+ "uyvy422".into(),
+ ]);
+ let screen = if opts.screen.is_empty() {
+ "1".to_string()
+ } else {
+ opts.screen.clone()
+ };
+ let audio = if opts.audio.is_empty() {
+ "none".to_string()
+ } else {
+ opts.audio.clone()
+ };
a.extend(["-i".into(), format!("{}:{}", screen, audio)]);
} else if cfg!(target_os = "windows") {
- a.extend(["-f".into(), "gdigrab".into(), "-framerate".into(), fps.clone(), "-draw_mouse".into(), if opts.cursor { "1".into() } else { "0".into() }]);
+ a.extend([
+ "-f".into(),
+ "gdigrab".into(),
+ "-framerate".into(),
+ fps.clone(),
+ "-draw_mouse".into(),
+ if opts.cursor { "1".into() } else { "0".into() },
+ ]);
if let Some((x, y, w, h)) = opts.area {
- a.extend(["-offset_x".into(), x.to_string(), "-offset_y".into(), y.to_string(), "-video_size".into(), format!("{}x{}", w, h)]);
+ a.extend([
+ "-offset_x".into(),
+ x.to_string(),
+ "-offset_y".into(),
+ y.to_string(),
+ "-video_size".into(),
+ format!("{}x{}", w, h),
+ ]);
}
- a.extend(["-i".into(), if opts.screen.is_empty() { "desktop".into() } else { opts.screen.clone() }]);
+ a.extend([
+ "-i".into(),
+ if opts.screen.is_empty() {
+ "desktop".into()
+ } else {
+ opts.screen.clone()
+ },
+ ]);
if !opts.audio.is_empty() {
- a.extend(["-f".into(), "dshow".into(), "-i".into(), format!("audio={}", opts.audio)]);
+ a.extend([
+ "-f".into(),
+ "dshow".into(),
+ "-i".into(),
+ format!("audio={}", opts.audio),
+ ]);
}
} else {
- a.extend(["-f".into(), "x11grab".into(), "-framerate".into(), fps.clone(), "-draw_mouse".into(), if opts.cursor { "1".into() } else { "0".into() }]);
- let mut input = if opts.screen.is_empty() { format!("{}.0", std::env::var("DISPLAY").unwrap_or_else(|_| ":0".into())) } else { opts.screen.clone() };
+ a.extend([
+ "-f".into(),
+ "x11grab".into(),
+ "-framerate".into(),
+ fps.clone(),
+ "-draw_mouse".into(),
+ if opts.cursor { "1".into() } else { "0".into() },
+ ]);
+ let mut input = if opts.screen.is_empty() {
+ format!(
+ "{}.0",
+ std::env::var("DISPLAY").unwrap_or_else(|_| ":0".into())
+ )
+ } else {
+ opts.screen.clone()
+ };
if let Some((x, y, w, h)) = opts.area {
a.extend(["-video_size".into(), format!("{}x{}", w, h)]);
input = format!("{}+{},{}", input, x, y);
@@ -183,12 +296,32 @@ fn build_args(opts: &RecordOptions, target: &Path, ring: bool) -> Vec<String> {
a.extend(["-vf".into(), format!("crop={}:{}:{}:{}", w, h, x, y)]);
}
}
- a.extend(["-c:v".into(), "libx264".into(), "-preset".into(), "veryfast".into(), "-crf".into(), opts.crf.clamp(10, 40).to_string(), "-pix_fmt".into(), "yuv420p".into()]);
+ a.extend([
+ "-c:v".into(),
+ "libx264".into(),
+ "-preset".into(),
+ "veryfast".into(),
+ "-crf".into(),
+ opts.crf.clamp(10, 40).to_string(),
+ "-pix_fmt".into(),
+ "yuv420p".into(),
+ ]);
a.extend(["-c:a".into(), "aac".into(), "-b:a".into(), "160k".into()]);
a.extend(["-movflags".into(), "+faststart".into()]);
if ring {
let wrap = (opts.replay_seconds.max(10) / 5 + 2).to_string();
- a.extend(["-f".into(), "segment".into(), "-segment_time".into(), "5".into(), "-segment_wrap".into(), wrap, "-reset_timestamps".into(), "1".into(), "-segment_format_options".into(), "movflags=+faststart".into()]);
+ a.extend([
+ "-f".into(),
+ "segment".into(),
+ "-segment_time".into(),
+ "5".into(),
+ "-segment_wrap".into(),
+ wrap,
+ "-reset_timestamps".into(),
+ "1".into(),
+ "-segment_format_options".into(),
+ "movflags=+faststart".into(),
+ ]);
a.push(target.join("seg-%03d.mp4").to_string_lossy().to_string());
} else {
a.push(target.to_string_lossy().to_string());
@@ -200,11 +333,18 @@ pub async fn start(opts: RecordOptions) -> anyhow::Result<RecordState> {
if SESSION.lock().unwrap_or_else(|e| e.into_inner()).is_some() {
return Err(anyhow!("ja esta gravando"));
}
- if cfg!(target_os = "linux") && std::env::var("WAYLAND_DISPLAY").is_ok() && std::env::var("DISPLAY").is_err() {
+ if cfg!(target_os = "linux")
+ && std::env::var("WAYLAND_DISPLAY").is_ok()
+ && std::env::var("DISPLAY").is_err()
+ {
return Err(anyhow!("sessao Wayland sem XWayland: o x11grab nao enxerga a tela. Use a captura do OmniDisc (PipeWire) ou entre numa sessao X11."));
}
let ffmpeg = crate::core::dependencies::ensure_ffmpeg().await?;
- let dir = if opts.output_dir.trim().is_empty() { videos_dir() } else { PathBuf::from(opts.output_dir.trim()) };
+ let dir = if opts.output_dir.trim().is_empty() {
+ videos_dir()
+ } else {
+ PathBuf::from(opts.output_dir.trim())
+ };
std::fs::create_dir_all(&dir)?;
let ring = opts.replay_seconds > 0;
let (target, ring_dir, output) = if ring {
@@ -217,10 +357,19 @@ pub async fn start(opts: RecordOptions) -> anyhow::Result<RecordState> {
};
let args = build_args(&opts, &target, ring);
let mut cmd = crate::core::process::command(&ffmpeg);
- cmd.args(&args).stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped());
+ cmd.args(&args)
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::piped());
let child = cmd.spawn().map_err(|e| anyhow!("ffmpeg: {}", e))?;
*ERROR.lock().unwrap_or_else(|e| e.into_inner()) = None;
- *SESSION.lock().unwrap_or_else(|e| e.into_inner()) = Some(Session { child, started: Instant::now(), output, ring_dir, opts });
+ *SESSION.lock().unwrap_or_else(|e| e.into_inner()) = Some(Session {
+ child,
+ started: Instant::now(),
+ output,
+ ring_dir,
+ opts,
+ });
// Se o ffmpeg morrer nos primeiros instantes (permissão, dispositivo), avisa.
tokio::time::sleep(std::time::Duration::from_millis(900)).await;
let died = {
@@ -240,7 +389,11 @@ pub async fn start(opts: RecordOptions) -> anyhow::Result<RecordState> {
let _ = e.read_to_string(&mut msg).await;
}
*SESSION.lock().unwrap_or_else(|e| e.into_inner()) = None;
- let msg = if msg.trim().is_empty() { "ffmpeg encerrou na largada (permissao de Gravacao de Tela?)".to_string() } else { msg.trim().to_string() };
+ let msg = if msg.trim().is_empty() {
+ "ffmpeg encerrou na largada (permissao de Gravacao de Tela?)".to_string()
+ } else {
+ msg.trim().to_string()
+ };
*ERROR.lock().unwrap_or_else(|e| e.into_inner()) = Some(msg.clone());
return Err(anyhow!(msg));
}
@@ -253,7 +406,10 @@ async fn stop_child(mut child: tokio::process::Child) {
let _ = stdin.write_all(b"q\n").await;
let _ = stdin.flush().await;
}
- if tokio::time::timeout(std::time::Duration::from_secs(10), child.wait()).await.is_err() {
+ if tokio::time::timeout(std::time::Duration::from_secs(10), child.wait())
+ .await
+ .is_err()
+ {
let _ = child.kill().await;
}
}
@@ -261,10 +417,13 @@ async fn stop_child(mut child: tokio::process::Child) {
/// Para a gravação. Normal: devolve o arquivo. Replay: descarta o anel.
pub async fn stop() -> anyhow::Result<RecordState> {
let sess = SESSION.lock().unwrap_or_else(|e| e.into_inner()).take();
- let Some(sess) = sess else { return Err(anyhow!("nao esta gravando")) };
+ let Some(sess) = sess else {
+ return Err(anyhow!("nao esta gravando"));
+ };
stop_child(sess.child).await;
if let Some(out) = &sess.output {
- *LAST_SAVED.lock().unwrap_or_else(|e| e.into_inner()) = Some(out.to_string_lossy().to_string());
+ *LAST_SAVED.lock().unwrap_or_else(|e| e.into_inner()) =
+ Some(out.to_string_lossy().to_string());
}
if let Some(r) = &sess.ring_dir {
let _ = std::fs::remove_dir_all(r);
@@ -277,8 +436,12 @@ pub async fn stop() -> anyhow::Result<RecordState> {
pub async fn save_replay() -> anyhow::Result<String> {
let (ring, opts) = {
let s = SESSION.lock().unwrap_or_else(|e| e.into_inner());
- let Some(sess) = s.as_ref() else { return Err(anyhow!("o replay nao esta ligado")) };
- let Some(r) = sess.ring_dir.clone() else { return Err(anyhow!("a gravacao atual nao e um replay")) };
+ let Some(sess) = s.as_ref() else {
+ return Err(anyhow!("o replay nao esta ligado"));
+ };
+ let Some(r) = sess.ring_dir.clone() else {
+ return Err(anyhow!("a gravacao atual nao e um replay"));
+ };
(r, sess.opts.clone())
};
let ffmpeg = crate::core::dependencies::ensure_ffmpeg().await?;
@@ -303,21 +466,53 @@ pub async fn save_replay() -> anyhow::Result<String> {
return Err(anyhow!("ainda nao ha nada no buffer"));
}
let want = (opts.replay_seconds.max(10) / 5) as usize;
- let chosen: Vec<PathBuf> = segs.iter().rev().take(want).map(|(_, p)| p.clone()).collect::<Vec<_>>().into_iter().rev().collect();
+ let chosen: Vec<PathBuf> = segs
+ .iter()
+ .rev()
+ .take(want)
+ .map(|(_, p)| p.clone())
+ .collect::<Vec<_>>()
+ .into_iter()
+ .rev()
+ .collect();
let list = ring.join("concat.txt");
- std::fs::write(&list, chosen.iter().map(|p| format!("file '{}'", p.to_string_lossy().replace('\'', "'\\''"))).collect::<Vec<_>>().join("\n"))?;
- let dir = if opts.output_dir.trim().is_empty() { videos_dir() } else { PathBuf::from(opts.output_dir.trim()) };
+ std::fs::write(
+ &list,
+ chosen
+ .iter()
+ .map(|p| format!("file '{}'", p.to_string_lossy().replace('\'', "'\\''")))
+ .collect::<Vec<_>>()
+ .join("\n"),
+ )?;
+ let dir = if opts.output_dir.trim().is_empty() {
+ videos_dir()
+ } else {
+ PathBuf::from(opts.output_dir.trim())
+ };
std::fs::create_dir_all(&dir)?;
let out = dir.join(format!("Replay {}.mp4", stamp()));
let o = crate::core::process::command(&ffmpeg)
- .args(["-y", "-hide_banner", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i"])
+ .args([
+ "-y",
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-f",
+ "concat",
+ "-safe",
+ "0",
+ "-i",
+ ])
.arg(&list)
.args(["-c", "copy", "-movflags", "+faststart"])
.arg(&out)
.output()
.await?;
if !o.status.success() {
- return Err(anyhow!("concat falhou: {}", String::from_utf8_lossy(&o.stderr).trim()));
+ return Err(anyhow!(
+ "concat falhou: {}",
+ String::from_utf8_lossy(&o.stderr).trim()
+ ));
}
let s = out.to_string_lossy().to_string();
*LAST_SAVED.lock().unwrap_or_else(|e| e.into_inner()) = Some(s.clone());
@@ -330,7 +525,8 @@ mod tests {
#[test]
fn args_shape() {
- let o: RecordOptions = serde_json::from_str(r#"{"screen":"","fps":30,"replay_seconds":30}"#).unwrap();
+ let o: RecordOptions =
+ serde_json::from_str(r#"{"screen":"","fps":30,"replay_seconds":30}"#).unwrap();
let a = build_args(&o, Path::new("/tmp/x"), true);
assert!(a.iter().any(|s| s == "segment"));
assert!(a.last().unwrap().ends_with("seg-%03d.mp4"));
diff --git a/src-tauri/omniget-core/src/core/tools/slides.rs b/src-tauri/omniget-core/src/core/tools/slides.rs
index d6cd4cb7..a2079644 100644
--- a/src-tauri/omniget-core/src/core/tools/slides.rs
+++ b/src-tauri/omniget-core/src/core/tools/slides.rs
@@ -25,8 +25,12 @@ pub fn parse_slide_urls(html: &str) -> Vec<String> {
let mut best: Option<(u32, &str)> = None;
for part in c[1].split(',') {
let mut it = part.split_whitespace();
- let (Some(u), w) = (it.next(), it.next()) else { continue };
- let width = w.and_then(|w| w.trim_end_matches('w').parse::<u32>().ok()).unwrap_or(0);
+ let (Some(u), w) = (it.next(), it.next()) else {
+ continue;
+ };
+ let width = w
+ .and_then(|w| w.trim_end_matches('w').parse::<u32>().ok())
+ .unwrap_or(0);
if best.map(|(bw, _)| width > bw).unwrap_or(true) {
best = Some((width, u));
}
@@ -46,7 +50,11 @@ pub fn parse_slide_urls(html: &str) -> Vec<String> {
pub fn og_title(html: &str) -> Option<String> {
let re = regex::Regex::new(r#"<meta[^>]*property="og:title"[^>]*content="([^"]*)""#).ok()?;
- re.captures(html).map(|c| c[1].replace("&amp;", "&").replace("&quot;", "\"").replace("&#39;", "'"))
+ re.captures(html).map(|c| {
+ c[1].replace("&amp;", "&")
+ .replace("&quot;", "\"")
+ .replace("&#39;", "'")
+ })
}
/// Converte qualquer imagem em JPEG pelo ffmpeg (webp/png escapam do DCTDecode).
@@ -71,12 +79,22 @@ pub(crate) async fn ensure_jpeg(data: Vec<u8>, work: &Path, idx: usize) -> anyho
Ok(tokio::fs::read(&output).await?)
}
-pub async fn download(url: &str, dest_dir: &str, progress: super::ProgressFn) -> anyhow::Result<SlidesResult> {
+pub async fn download(
+ url: &str,
+ dest_dir: &str,
+ progress: super::ProgressFn,
+) -> anyhow::Result<SlidesResult> {
if !url.contains("slideshare.net") {
return Err(anyhow!("cole um link do slideshare.net"));
}
let client = super::client()?;
- let html = client.get(url).send().await?.error_for_status()?.text().await?;
+ let html = client
+ .get(url)
+ .send()
+ .await?
+ .error_for_status()?
+ .text()
+ .await?;
let urls = parse_slide_urls(&html);
if urls.is_empty() {
return Err(anyhow!("nao encontrei slides nessa pagina (o SlideShare pode ter mudado o HTML ou o deck e privado)"));
@@ -87,8 +105,22 @@ pub async fn download(url: &str, dest_dir: &str, progress: super::ProgressFn) ->
let mut images = Vec::with_capacity(urls.len());
let id = format!("slides:{}", url);
for (i, u) in urls.iter().enumerate() {
- super::report(&progress, &id, "download", i as u64, Some(urls.len() as u64), None);
- let data = client.get(u).send().await?.error_for_status()?.bytes().await?.to_vec();
+ super::report(
+ &progress,
+ &id,
+ "download",
+ i as u64,
+ Some(urls.len() as u64),
+ None,
+ );
+ let data = client
+ .get(u)
+ .send()
+ .await?
+ .error_for_status()?
+ .bytes()
+ .await?
+ .to_vec();
images.push(ensure_jpeg(data, &work, i).await?);
}
let pdf = super::jpeg_pdf::build_pdf(&images)?;
@@ -97,8 +129,19 @@ pub async fn download(url: &str, dest_dir: &str, progress: super::ProgressFn) ->
let pdf_path = dir.join(format!("{}.pdf", super::sanitize_name(&title)));
tokio::fs::write(&pdf_path, &pdf).await?;
let _ = std::fs::remove_dir_all(&work);
- super::report(&progress, &id, "done", urls.len() as u64, Some(urls.len() as u64), None);
- Ok(SlidesResult { title, pages: images.len(), pdf_path: pdf_path.to_string_lossy().to_string() })
+ super::report(
+ &progress,
+ &id,
+ "done",
+ urls.len() as u64,
+ Some(urls.len() as u64),
+ None,
+ );
+ Ok(SlidesResult {
+ title,
+ pages: images.len(),
+ pdf_path: pdf_path.to_string_lossy().to_string(),
+ })
}
#[cfg(test)]
diff --git a/src-tauri/omniget-core/src/core/tools/sponsorblock.rs b/src-tauri/omniget-core/src/core/tools/sponsorblock.rs
index 461b6c84..352b7444 100644
--- a/src-tauri/omniget-core/src/core/tools/sponsorblock.rs
+++ b/src-tauri/omniget-core/src/core/tools/sponsorblock.rs
@@ -7,7 +7,17 @@ use sha2::{Digest, Sha256};
pub const SERVER: &str = "https://sponsor.ajay.app";
pub const CATEGORIES: &[&str] = &[
- "sponsor", "selfpromo", "interaction", "intro", "outro", "preview", "music_offtopic", "filler", "exclusive_access", "poi_highlight", "chapter",
+ "sponsor",
+ "selfpromo",
+ "interaction",
+ "intro",
+ "outro",
+ "preview",
+ "music_offtopic",
+ "filler",
+ "exclusive_access",
+ "poi_highlight",
+ "chapter",
];
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -40,15 +50,22 @@ pub struct SponsorResult {
/// Aceita URL completa, `youtu.be/ID`, `shorts/ID` ou o próprio ID.
pub fn video_id(input: &str) -> Option<String> {
let s = input.trim();
- if s.len() == 11 && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
+ if s.len() == 11
+ && s.chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
+ {
return Some(s.to_string());
}
- let re = regex::Regex::new(r"(?:v=|youtu\.be/|shorts/|embed/|live/)([A-Za-z0-9_-]{11})").ok()?;
- re.captures(s).and_then(|c| c.get(1)).map(|m| m.as_str().to_string())
+ let re =
+ regex::Regex::new(r"(?:v=|youtu\.be/|shorts/|embed/|live/)([A-Za-z0-9_-]{11})").ok()?;
+ re.captures(s)
+ .and_then(|c| c.get(1))
+ .map(|m| m.as_str().to_string())
}
pub async fn segments(input: &str, categories: &[String]) -> anyhow::Result<SponsorResult> {
- let id = video_id(input).ok_or_else(|| anyhow!("nao reconheci um video do YouTube em: {}", input))?;
+ let id = video_id(input)
+ .ok_or_else(|| anyhow!("nao reconheci um video do YouTube em: {}", input))?;
let cats: Vec<&str> = if categories.is_empty() {
CATEGORIES.to_vec()
} else {
@@ -74,20 +91,31 @@ pub async fn segments(input: &str, categories: &[String]) -> anyhow::Result<Spon
for v in arr {
if v["videoID"].as_str() == Some(id.as_str()) {
if let Some(list) = v["segments"].as_array() {
- segs.extend(list.iter().filter_map(|s| serde_json::from_value(s.clone()).ok()));
+ segs.extend(
+ list.iter()
+ .filter_map(|s| serde_json::from_value(s.clone()).ok()),
+ );
}
}
}
} else {
return Err(anyhow!("SponsorBlock: HTTP {}", resp.status()));
}
- segs.sort_by(|a, b| a.segment[0].partial_cmp(&b.segment[0]).unwrap_or(std::cmp::Ordering::Equal));
+ segs.sort_by(|a, b| {
+ a.segment[0]
+ .partial_cmp(&b.segment[0])
+ .unwrap_or(std::cmp::Ordering::Equal)
+ });
let skipped: f64 = segs
.iter()
.filter(|s| s.action_type == "skip" || s.action_type.is_empty())
.map(|s| (s.segment[1] - s.segment[0]).max(0.0))
.sum();
- let mut used: Vec<&str> = segs.iter().filter(|s| s.action_type != "chapter" && s.action_type != "poi").map(|s| s.category.as_str()).collect();
+ let mut used: Vec<&str> = segs
+ .iter()
+ .filter(|s| s.action_type != "chapter" && s.action_type != "poi")
+ .map(|s| s.category.as_str())
+ .collect();
used.sort();
used.dedup();
let ytdlp_args = if used.is_empty() {
@@ -95,7 +123,12 @@ pub async fn segments(input: &str, categories: &[String]) -> anyhow::Result<Spon
} else {
format!("--sponsorblock-remove {}", used.join(","))
};
- Ok(SponsorResult { video_id: id, segments: segs, skipped_seconds: skipped, ytdlp_args })
+ Ok(SponsorResult {
+ video_id: id,
+ segments: segs,
+ skipped_seconds: skipped,
+ ytdlp_args,
+ })
}
#[cfg(test)]
@@ -104,8 +137,14 @@ mod tests {
#[test]
fn extracts_ids() {
- assert_eq!(video_id("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=1").as_deref(), Some("dQw4w9WgXcQ"));
- assert_eq!(video_id("https://youtu.be/dQw4w9WgXcQ").as_deref(), Some("dQw4w9WgXcQ"));
+ assert_eq!(
+ video_id("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=1").as_deref(),
+ Some("dQw4w9WgXcQ")
+ );
+ assert_eq!(
+ video_id("https://youtu.be/dQw4w9WgXcQ").as_deref(),
+ Some("dQw4w9WgXcQ")
+ );
assert_eq!(video_id("dQw4w9WgXcQ").as_deref(), Some("dQw4w9WgXcQ"));
assert_eq!(video_id("https://example.com"), None);
}
diff --git a/src-tauri/omniget-core/src/core/tools/srt_translate.rs b/src-tauri/omniget-core/src/core/tools/srt_translate.rs
index 0f16ce8a..079d1b50 100644
--- a/src-tauri/omniget-core/src/core/tools/srt_translate.rs
+++ b/src-tauri/omniget-core/src/core/tools/srt_translate.rs
@@ -42,7 +42,14 @@ pub struct TranslateResult {
pub failed: Vec<usize>,
}
-fn llm_prompt(lines: &[&str], src: &str, tgt: &str, context: &str, prev: &str, next: &str) -> (String, String) {
+fn llm_prompt(
+ lines: &[&str],
+ src: &str,
+ tgt: &str,
+ context: &str,
+ prev: &str,
+ next: &str,
+) -> (String, String) {
let system = format!(
"You are a professional subtitle translator from {src} to {tgt}. Translate each numbered line faithfully, keeping meaning, tone and terminology. Keep each line a subtitle: short, no explanations, no empty lines. Reply ONLY with a JSON object mapping the line number (as string) to the translated text."
);
@@ -83,8 +90,20 @@ fn parse_llm_json(text: &str, n: usize) -> Option<Vec<Option<String>>> {
Some(out)
}
-async fn translate_batch_llm(lines: &[&str], opts: &TranslateOptions, prev: &str, next: &str) -> anyhow::Result<Vec<Option<String>>> {
- let (system, user) = llm_prompt(lines, &opts.source_lang, &opts.target_lang, &opts.context, prev, next);
+async fn translate_batch_llm(
+ lines: &[&str],
+ opts: &TranslateOptions,
+ prev: &str,
+ next: &str,
+) -> anyhow::Result<Vec<Option<String>>> {
+ let (system, user) = llm_prompt(
+ lines,
+ &opts.source_lang,
+ &opts.target_lang,
+ &opts.context,
+ prev,
+ next,
+ );
let mut last_err = String::new();
for _ in 0..2 {
match crate::core::ai::chat(&system, &user).await {
@@ -100,7 +119,12 @@ async fn translate_batch_llm(lines: &[&str], opts: &TranslateOptions, prev: &str
Err(anyhow!("tradução por IA falhou: {}", last_err))
}
-async fn translate_batch_libre(lines: &[&str], base_url: &str, api_key: &str, opts: &TranslateOptions) -> anyhow::Result<Vec<Option<String>>> {
+async fn translate_batch_libre(
+ lines: &[&str],
+ base_url: &str,
+ api_key: &str,
+ opts: &TranslateOptions,
+) -> anyhow::Result<Vec<Option<String>>> {
let client = super::client()?;
let url = format!("{}/translate", base_url.trim_end_matches('/'));
let mut body = serde_json::json!({
@@ -114,7 +138,10 @@ async fn translate_batch_libre(lines: &[&str], base_url: &str, api_key: &str, op
}
let resp = client.post(&url).json(&body).send().await?;
let status = resp.status();
- let v: serde_json::Value = resp.json().await.map_err(|e| anyhow!("LibreTranslate: resposta invalida ({})", e))?;
+ let v: serde_json::Value = resp
+ .json()
+ .await
+ .map_err(|e| anyhow!("LibreTranslate: resposta invalida ({})", e))?;
if !status.is_success() {
return Err(anyhow!(
"LibreTranslate: HTTP {} {}",
@@ -123,14 +150,21 @@ async fn translate_batch_libre(lines: &[&str], base_url: &str, api_key: &str, op
));
}
let out = match &v["translatedText"] {
- serde_json::Value::Array(a) => a.iter().map(|x| x.as_str().map(|s| s.to_string())).collect(),
+ serde_json::Value::Array(a) => a
+ .iter()
+ .map(|x| x.as_str().map(|s| s.to_string()))
+ .collect(),
serde_json::Value::String(s) => vec![Some(s.clone())],
_ => vec![None; lines.len()],
};
Ok(out)
}
-pub async fn translate_cues(cues: &[Cue], opts: &TranslateOptions, progress: super::ProgressFn) -> anyhow::Result<TranslateResult> {
+pub async fn translate_cues(
+ cues: &[Cue],
+ opts: &TranslateOptions,
+ progress: super::ProgressFn,
+) -> anyhow::Result<TranslateResult> {
let id = "translate";
let batch = opts.batch_size.clamp(1, 100);
let mut out = cues.to_vec();
@@ -140,12 +174,22 @@ pub async fn translate_cues(cues: &[Cue], opts: &TranslateOptions, progress: sup
for (bi, chunk) in cues.chunks(batch).enumerate() {
let lines: Vec<&str> = chunk.iter().map(|c| c.text.as_str()).collect();
let start = bi * batch;
- let prev = cues[start.saturating_sub(3)..start].iter().map(|c| c.text.as_str()).collect::<Vec<_>>().join(" ");
+ let prev = cues[start.saturating_sub(3)..start]
+ .iter()
+ .map(|c| c.text.as_str())
+ .collect::<Vec<_>>()
+ .join(" ");
let end = (start + chunk.len()).min(cues.len());
- let next = cues[end..(end + 3).min(cues.len())].iter().map(|c| c.text.as_str()).collect::<Vec<_>>().join(" ");
+ let next = cues[end..(end + 3).min(cues.len())]
+ .iter()
+ .map(|c| c.text.as_str())
+ .collect::<Vec<_>>()
+ .join(" ");
let translated = match &opts.translator {
Translator::Llm => translate_batch_llm(&lines, opts, &prev, &next).await?,
- Translator::LibreTranslate { base_url, api_key } => translate_batch_libre(&lines, base_url, api_key, opts).await?,
+ Translator::LibreTranslate { base_url, api_key } => {
+ translate_batch_libre(&lines, base_url, api_key, opts).await?
+ }
};
for (i, t) in translated.into_iter().enumerate() {
match t {
diff --git a/src-tauri/omniget-core/src/core/tools/startup.rs b/src-tauri/omniget-core/src/core/tools/startup.rs
index a2cec74a..56b0ef4f 100644
--- a/src-tauri/omniget-core/src/core/tools/startup.rs
+++ b/src-tauri/omniget-core/src/core/tools/startup.rs
@@ -28,9 +28,16 @@ fn home() -> PathBuf {
}
async fn run(program: &str, args: &[&str]) -> anyhow::Result<String> {
- let o = crate::core::process::command(program).args(args).output().await?;
+ let o = crate::core::process::command(program)
+ .args(args)
+ .output()
+ .await?;
if !o.status.success() {
- return Err(anyhow!("{} falhou: {}", program, String::from_utf8_lossy(&o.stderr).trim()));
+ return Err(anyhow!(
+ "{} falhou: {}",
+ program,
+ String::from_utf8_lossy(&o.stderr).trim()
+ ));
}
Ok(String::from_utf8_lossy(&o.stdout).to_string())
}
@@ -38,7 +45,12 @@ async fn run(program: &str, args: &[&str]) -> anyhow::Result<String> {
// ── macOS ──────────────────────────────────────────────────────────────
async fn plist_json(path: &Path) -> Option<serde_json::Value> {
- let o = crate::core::process::command("plutil").args(["-convert", "json", "-o", "-"]).arg(path).output().await.ok()?;
+ let o = crate::core::process::command("plutil")
+ .args(["-convert", "json", "-o", "-"])
+ .arg(path)
+ .output()
+ .await
+ .ok()?;
if !o.status.success() {
return None;
}
@@ -47,23 +59,60 @@ async fn plist_json(path: &Path) -> Option<serde_json::Value> {
async fn mac_items() -> Vec<StartupItem> {
let mut out = Vec::new();
- let uid = run("id", &["-u"]).await.map(|s| s.trim().to_string()).unwrap_or_else(|_| "501".into());
- let disabled = run("launchctl", &["print-disabled", &format!("gui/{}", uid)]).await.unwrap_or_default();
- for (dir, scope) in [(home().join("Library/LaunchAgents"), "user"), (PathBuf::from("/Library/LaunchAgents"), "system")] {
- let Ok(rd) = std::fs::read_dir(&dir) else { continue };
- let mut entries: Vec<_> = rd.flatten().map(|e| e.path()).filter(|p| p.extension().map(|e| e == "plist").unwrap_or(false)).collect();
+ let uid = run("id", &["-u"])
+ .await
+ .map(|s| s.trim().to_string())
+ .unwrap_or_else(|_| "501".into());
+ let disabled = run("launchctl", &["print-disabled", &format!("gui/{}", uid)])
+ .await
+ .unwrap_or_default();
+ for (dir, scope) in [
+ (home().join("Library/LaunchAgents"), "user"),
+ (PathBuf::from("/Library/LaunchAgents"), "system"),
+ ] {
+ let Ok(rd) = std::fs::read_dir(&dir) else {
+ continue;
+ };
+ let mut entries: Vec<_> = rd
+ .flatten()
+ .map(|e| e.path())
+ .filter(|p| p.extension().map(|e| e == "plist").unwrap_or(false))
+ .collect();
entries.sort();
for p in entries {
let json = plist_json(&p).await.unwrap_or(serde_json::Value::Null);
- let label = json.get("Label").and_then(|v| v.as_str()).map(String::from).unwrap_or_else(|| p.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default());
+ let label = json
+ .get("Label")
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ .unwrap_or_else(|| {
+ p.file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_default()
+ });
let command = json
.get("ProgramArguments")
.and_then(|v| v.as_array())
- .map(|a| a.iter().filter_map(|x| x.as_str()).collect::<Vec<_>>().join(" "))
- .or_else(|| json.get("Program").and_then(|v| v.as_str()).map(String::from))
+ .map(|a| {
+ a.iter()
+ .filter_map(|x| x.as_str())
+ .collect::<Vec<_>>()
+ .join(" ")
+ })
+ .or_else(|| {
+ json.get("Program")
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ })
.unwrap_or_default();
- let disabled_key = json.get("Disabled").and_then(|v| v.as_bool()).unwrap_or(false);
- let disabled_override = disabled.lines().any(|l| l.contains(&format!("\"{}\" => disabled", label)) || l.contains(&format!("\"{}\" => true", label)));
+ let disabled_key = json
+ .get("Disabled")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+ let disabled_override = disabled.lines().any(|l| {
+ l.contains(&format!("\"{}\" => disabled", label))
+ || l.contains(&format!("\"{}\" => true", label))
+ });
out.push(StartupItem {
id: format!("la:{}", p.display()),
name: label,
@@ -77,14 +126,28 @@ async fn mac_items() -> Vec<StartupItem> {
}
}
// Itens de Login (System Settings → Geral → Itens de Login)
- if let Ok(list) = run("osascript", &["-e", "tell application \"System Events\" to get {name, path, hidden} of every login item"]).await {
+ if let Ok(list) = run(
+ "osascript",
+ &[
+ "-e",
+ "tell application \"System Events\" to get {name, path, hidden} of every login item",
+ ],
+ )
+ .await
+ {
// Saída: {{n1, n2}, {p1, p2}, {false, true}} → parse simples
let parts: Vec<Vec<String>> = list
.trim()
.trim_start_matches('{')
.trim_end_matches('}')
.split("}, {")
- .map(|g| g.trim_matches(|c| c == '{' || c == '}').split(", ").map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect())
+ .map(|g| {
+ g.trim_matches(|c| c == '{' || c == '}')
+ .split(", ")
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ .collect()
+ })
.collect();
if parts.len() >= 2 {
for (i, name) in parts[0].iter().enumerate() {
@@ -104,8 +167,20 @@ async fn mac_items() -> Vec<StartupItem> {
}
// Itens de login desligados por nós ficam guardados para religar.
for (name, path) in removed_login_items() {
- if !out.iter().any(|i| i.source == "login-item" && i.name == name) {
- out.push(StartupItem { id: format!("li:{}", name), name, command: path.clone(), source: "login-item".into(), scope: "user".into(), path, enabled: false, can_toggle: true });
+ if !out
+ .iter()
+ .any(|i| i.source == "login-item" && i.name == name)
+ {
+ out.push(StartupItem {
+ id: format!("li:{}", name),
+ name,
+ command: path.clone(),
+ source: "login-item".into(),
+ scope: "user".into(),
+ path,
+ enabled: false,
+ can_toggle: true,
+ });
}
}
out
@@ -116,7 +191,10 @@ fn removed_file() -> Option<PathBuf> {
}
fn removed_login_items() -> Vec<(String, String)> {
- removed_file().and_then(|p| std::fs::read_to_string(p).ok()).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
+ removed_file()
+ .and_then(|p| std::fs::read_to_string(p).ok())
+ .and_then(|s| serde_json::from_str(&s).ok())
+ .unwrap_or_default()
}
fn save_removed(list: &[(String, String)]) {
@@ -129,28 +207,59 @@ fn save_removed(list: &[(String, String)]) {
async fn mac_set(item: &StartupItem, enabled: bool) -> anyhow::Result<()> {
match item.source.as_str() {
"launch-agent" => {
- let uid = run("id", &["-u"]).await.map(|s| s.trim().to_string()).unwrap_or_else(|_| "501".into());
+ let uid = run("id", &["-u"])
+ .await
+ .map(|s| s.trim().to_string())
+ .unwrap_or_else(|_| "501".into());
let target = format!("gui/{}", uid);
if enabled {
- let _ = run("launchctl", &["enable", &format!("{}/{}", target, item.name)]).await;
- run("launchctl", &["bootstrap", &target, &item.path]).await.or_else(|_| Ok::<_, anyhow::Error>(String::new()))?;
+ let _ = run(
+ "launchctl",
+ &["enable", &format!("{}/{}", target, item.name)],
+ )
+ .await;
+ run("launchctl", &["bootstrap", &target, &item.path])
+ .await
+ .or_else(|_| Ok::<_, anyhow::Error>(String::new()))?;
} else {
- let _ = run("launchctl", &["bootout", &format!("{}/{}", target, item.name)]).await;
- run("launchctl", &["disable", &format!("{}/{}", target, item.name)]).await?;
+ let _ = run(
+ "launchctl",
+ &["bootout", &format!("{}/{}", target, item.name)],
+ )
+ .await;
+ run(
+ "launchctl",
+ &["disable", &format!("{}/{}", target, item.name)],
+ )
+ .await?;
}
Ok(())
}
"login-item" => {
let mut removed = removed_login_items();
if enabled {
- let path = removed.iter().find(|(n, _)| *n == item.name).map(|(_, p)| p.clone()).unwrap_or_else(|| item.path.clone());
+ let path = removed
+ .iter()
+ .find(|(n, _)| *n == item.name)
+ .map(|(_, p)| p.clone())
+ .unwrap_or_else(|| item.path.clone());
if path.is_empty() {
return Err(anyhow!("caminho do item de login desconhecido"));
}
run("osascript", &["-e", &format!("tell application \"System Events\" to make login item at end with properties {{path:\"{}\", hidden:false}}", path.replace('"', "\\\""))]).await?;
removed.retain(|(n, _)| *n != item.name);
} else {
- run("osascript", &["-e", &format!("tell application \"System Events\" to delete login item \"{}\"", item.name.replace('"', "\\\""))]).await?;
+ run(
+ "osascript",
+ &[
+ "-e",
+ &format!(
+ "tell application \"System Events\" to delete login item \"{}\"",
+ item.name.replace('"', "\\\"")
+ ),
+ ],
+ )
+ .await?;
removed.retain(|(n, _)| *n != item.name);
removed.push((item.name.clone(), item.path.clone()));
}
@@ -164,16 +273,40 @@ async fn mac_set(item: &StartupItem, enabled: bool) -> anyhow::Result<()> {
// ── Windows ────────────────────────────────────────────────────────────
const WIN_RUN: &[(&str, &str, &str)] = &[
- (r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "run", "user"),
- (r"HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce", "run-once", "user"),
- (r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run", "run", "system"),
- (r"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run", "run", "system"),
- (r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", "run-once", "system"),
+ (
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run",
+ "run",
+ "user",
+ ),
+ (
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce",
+ "run-once",
+ "user",
+ ),
+ (
+ r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
+ "run",
+ "system",
+ ),
+ (
+ r"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run",
+ "run",
+ "system",
+ ),
+ (
+ r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce",
+ "run-once",
+ "system",
+ ),
];
fn approved_key(scope: &str, folder: bool) -> String {
let root = if scope == "user" { "HKCU" } else { "HKLM" };
- format!(r"{}\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\{}", root, if folder { "StartupFolder" } else { "Run" })
+ format!(
+ r"{}\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\{}",
+ root,
+ if folder { "StartupFolder" } else { "Run" }
+ )
}
async fn win_approved(scope: &str, folder: bool) -> std::collections::HashMap<String, bool> {
@@ -181,7 +314,11 @@ async fn win_approved(scope: &str, folder: bool) -> std::collections::HashMap<St
for key in super::win_registry::reg_query(&approved_key(scope, folder), false).await {
for v in key.values {
// REG_BINARY: primeiro byte 02/06 = ligado, 03/07 = desligado
- let enabled = v.data.get(0..2).map(|b| b == "02" || b == "06").unwrap_or(true);
+ let enabled = v
+ .data
+ .get(0..2)
+ .map(|b| b == "02" || b == "06")
+ .unwrap_or(true);
map.insert(v.name.to_ascii_lowercase(), enabled);
}
}
@@ -212,12 +349,22 @@ async fn win_items() -> Vec<StartupItem> {
}
}
for (dir, scope) in [
- (std::env::var("APPDATA").map(|a| PathBuf::from(a).join(r"Microsoft\Windows\Start Menu\Programs\Startup")), "user"),
- (std::env::var("ProgramData").map(|a| PathBuf::from(a).join(r"Microsoft\Windows\Start Menu\Programs\StartUp")), "system"),
+ (
+ std::env::var("APPDATA")
+ .map(|a| PathBuf::from(a).join(r"Microsoft\Windows\Start Menu\Programs\Startup")),
+ "user",
+ ),
+ (
+ std::env::var("ProgramData")
+ .map(|a| PathBuf::from(a).join(r"Microsoft\Windows\Start Menu\Programs\StartUp")),
+ "system",
+ ),
] {
let Ok(dir) = dir else { continue };
let approved = win_approved(scope, true).await;
- let Ok(rd) = std::fs::read_dir(&dir) else { continue };
+ let Ok(rd) = std::fs::read_dir(&dir) else {
+ continue;
+ };
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().to_string();
if name.eq_ignore_ascii_case("desktop.ini") {
@@ -242,36 +389,69 @@ async fn win_items() -> Vec<StartupItem> {
async fn win_set(item: &StartupItem, enabled: bool) -> anyhow::Result<()> {
let folder = item.source == "startup-folder";
let key = approved_key(&item.scope, folder);
- let name = if folder { Path::new(&item.path).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default() } else { item.name.clone() };
- let data = if enabled { "020000000000000000000000" } else { "030000000000000000000000" };
+ let name = if folder {
+ Path::new(&item.path)
+ .file_name()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_default()
+ } else {
+ item.name.clone()
+ };
+ let data = if enabled {
+ "020000000000000000000000"
+ } else {
+ "030000000000000000000000"
+ };
super::win_registry::reg_add(&key, &name, "REG_BINARY", data).await
}
// ── Linux ──────────────────────────────────────────────────────────────
fn desktop_field(text: &str, key: &str) -> Option<String> {
- text.lines().find_map(|l| l.strip_prefix(&format!("{}=", key)).map(|v| v.trim().to_string()))
+ text.lines().find_map(|l| {
+ l.strip_prefix(&format!("{}=", key))
+ .map(|v| v.trim().to_string())
+ })
}
async fn linux_items() -> Vec<StartupItem> {
let mut out = Vec::new();
- let user_dir = dirs::config_dir().unwrap_or_else(|| home().join(".config")).join("autostart");
+ let user_dir = dirs::config_dir()
+ .unwrap_or_else(|| home().join(".config"))
+ .join("autostart");
let mut seen = std::collections::HashSet::new();
- for (dir, scope) in [(user_dir.clone(), "user"), (PathBuf::from("/etc/xdg/autostart"), "system")] {
- let Ok(rd) = std::fs::read_dir(&dir) else { continue };
- let mut entries: Vec<_> = rd.flatten().map(|e| e.path()).filter(|p| p.extension().map(|e| e == "desktop").unwrap_or(false)).collect();
+ for (dir, scope) in [
+ (user_dir.clone(), "user"),
+ (PathBuf::from("/etc/xdg/autostart"), "system"),
+ ] {
+ let Ok(rd) = std::fs::read_dir(&dir) else {
+ continue;
+ };
+ let mut entries: Vec<_> = rd
+ .flatten()
+ .map(|e| e.path())
+ .filter(|p| p.extension().map(|e| e == "desktop").unwrap_or(false))
+ .collect();
entries.sort();
for p in entries {
- let file = p.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
+ let file = p
+ .file_name()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_default();
if !seen.insert(file.clone()) {
continue; // o do usuário sobrepõe o do sistema
}
let text = std::fs::read_to_string(&p).unwrap_or_default();
- let hidden = desktop_field(&text, "Hidden").map(|v| v == "true").unwrap_or(false);
- let gnome_off = desktop_field(&text, "X-GNOME-Autostart-enabled").map(|v| v == "false").unwrap_or(false);
+ let hidden = desktop_field(&text, "Hidden")
+ .map(|v| v == "true")
+ .unwrap_or(false);
+ let gnome_off = desktop_field(&text, "X-GNOME-Autostart-enabled")
+ .map(|v| v == "false")
+ .unwrap_or(false);
out.push(StartupItem {
id: format!("autostart:{}", file),
- name: desktop_field(&text, "Name").unwrap_or_else(|| file.trim_end_matches(".desktop").to_string()),
+ name: desktop_field(&text, "Name")
+ .unwrap_or_else(|| file.trim_end_matches(".desktop").to_string()),
command: desktop_field(&text, "Exec").unwrap_or_default(),
source: "autostart".into(),
scope: scope.into(),
@@ -281,10 +461,23 @@ async fn linux_items() -> Vec<StartupItem> {
});
}
}
- if let Ok(list) = run("systemctl", &["--user", "list-unit-files", "--type=service", "--no-legend", "--no-pager"]).await {
+ if let Ok(list) = run(
+ "systemctl",
+ &[
+ "--user",
+ "list-unit-files",
+ "--type=service",
+ "--no-legend",
+ "--no-pager",
+ ],
+ )
+ .await
+ {
for l in list.lines() {
let mut cols = l.split_whitespace();
- let (Some(unit), Some(state)) = (cols.next(), cols.next()) else { continue };
+ let (Some(unit), Some(state)) = (cols.next(), cols.next()) else {
+ continue;
+ };
if !matches!(state, "enabled" | "disabled") {
continue;
}
@@ -306,12 +499,22 @@ async fn linux_items() -> Vec<StartupItem> {
async fn linux_set(item: &StartupItem, enabled: bool) -> anyhow::Result<()> {
match item.source.as_str() {
"autostart" => {
- let user_dir = dirs::config_dir().unwrap_or_else(|| home().join(".config")).join("autostart");
+ let user_dir = dirs::config_dir()
+ .unwrap_or_else(|| home().join(".config"))
+ .join("autostart");
std::fs::create_dir_all(&user_dir)?;
- let file = Path::new(&item.path).file_name().ok_or_else(|| anyhow!("arquivo invalido"))?;
+ let file = Path::new(&item.path)
+ .file_name()
+ .ok_or_else(|| anyhow!("arquivo invalido"))?;
let target = user_dir.join(file);
let mut text = std::fs::read_to_string(&item.path).unwrap_or_default();
- let mut lines: Vec<String> = text.lines().filter(|l| !l.starts_with("Hidden=") && !l.starts_with("X-GNOME-Autostart-enabled=")).map(String::from).collect();
+ let mut lines: Vec<String> = text
+ .lines()
+ .filter(|l| {
+ !l.starts_with("Hidden=") && !l.starts_with("X-GNOME-Autostart-enabled=")
+ })
+ .map(String::from)
+ .collect();
if !enabled {
lines.push("Hidden=true".into());
lines.push("X-GNOME-Autostart-enabled=false".into());
@@ -321,7 +524,15 @@ async fn linux_set(item: &StartupItem, enabled: bool) -> anyhow::Result<()> {
Ok(())
}
"systemd-user" => {
- run("systemctl", &["--user", if enabled { "enable" } else { "disable" }, &item.path]).await?;
+ run(
+ "systemctl",
+ &[
+ "--user",
+ if enabled { "enable" } else { "disable" },
+ &item.path,
+ ],
+ )
+ .await?;
Ok(())
}
_ => Err(anyhow!("nao da para alterar este item")),
@@ -344,7 +555,9 @@ pub async fn list() -> Vec<StartupItem> {
pub async fn set_enabled(item: &StartupItem, enabled: bool) -> anyhow::Result<()> {
if !item.can_toggle {
- return Err(anyhow!("este item so pode ser alterado com privilegios de administrador"));
+ return Err(anyhow!(
+ "este item so pode ser alterado com privilegios de administrador"
+ ));
}
if cfg!(target_os = "macos") {
mac_set(item, enabled).await
@@ -363,7 +576,10 @@ mod tests {
fn desktop() {
let t = "[Desktop Entry]\nName=Foo\nExec=/usr/bin/foo --x\nHidden=true\n";
assert_eq!(desktop_field(t, "Name").as_deref(), Some("Foo"));
- assert_eq!(desktop_field(t, "Exec").as_deref(), Some("/usr/bin/foo --x"));
+ assert_eq!(
+ desktop_field(t, "Exec").as_deref(),
+ Some("/usr/bin/foo --x")
+ );
assert_eq!(desktop_field(t, "Hidden").as_deref(), Some("true"));
assert!(desktop_field(t, "Nope").is_none());
}
@@ -377,7 +593,14 @@ mod live {
async fn list_here() {
let items = super::list().await;
for i in &items {
- println!("{:<14} {:<6} {:<5} {} :: {}", i.source, i.scope, i.enabled, i.name, i.command.chars().take(80).collect::<String>());
+ println!(
+ "{:<14} {:<6} {:<5} {} :: {}",
+ i.source,
+ i.scope,
+ i.enabled,
+ i.name,
+ i.command.chars().take(80).collect::<String>()
+ );
}
println!("{} itens", items.len());
}
diff --git a/src-tauri/omniget-core/src/core/tools/sysclean.rs b/src-tauri/omniget-core/src/core/tools/sysclean.rs
index 1804f14f..04a01c28 100644
--- a/src-tauri/omniget-core/src/core/tools/sysclean.rs
+++ b/src-tauri/omniget-core/src/core/tools/sysclean.rs
@@ -29,8 +29,20 @@ struct Def {
paths: &'static [&'static str],
}
-const fn d(id: &'static str, group: &'static str, name: &'static str, risk: &'static str, paths: &'static [&'static str]) -> Def {
- Def { id, group, name, risk, paths }
+const fn d(
+ id: &'static str,
+ group: &'static str,
+ name: &'static str,
+ risk: &'static str,
+ paths: &'static [&'static str],
+) -> Def {
+ Def {
+ id,
+ group,
+ name,
+ risk,
+ paths,
+ }
}
// Caminhos: `~` = home; `%X%` = variável de ambiente; `*` num componente = glob.
@@ -77,81 +89,625 @@ const DEFS: &[Def] = &[
#[cfg(target_os = "windows")]
const DEFS: &[Def] = &[
- d("temp-user", "system", "Temporários do usuário (%TEMP%)", "safe", &["%TEMP%"]),
- d("temp-windows", "system", "Temporários do Windows (precisa de administrador)", "safe", &["%SystemRoot%\\Temp"]),
- d("inetcache", "system", "Cache do Internet Explorer/WebView", "safe", &["%LOCALAPPDATA%\\Microsoft\\Windows\\INetCache"]),
- d("thumbcache", "system", "Cache de miniaturas do Explorer", "review", &["%LOCALAPPDATA%\\Microsoft\\Windows\\Explorer"]),
- d("crashdumps", "system", "Despejos de falhas", "safe", &["%LOCALAPPDATA%\\CrashDumps", "%LOCALAPPDATA%\\Microsoft\\Windows\\WER"]),
- d("windows-update", "system", "Downloads do Windows Update (precisa de administrador)", "review", &["%SystemRoot%\\SoftwareDistribution\\Download"]),
- d("prefetch", "system", "Prefetch (precisa de administrador)", "review", &["%SystemRoot%\\Prefetch"]),
- d("delivery-opt", "system", "Otimização de Entrega", "safe", &["%SystemRoot%\\SoftwareDistribution\\DeliveryOptimization"]),
- d("d3d-cache", "system", "Cache de shaders DirectX", "safe", &["%LOCALAPPDATA%\\D3DSCache"]),
- d("nvidia-cache", "system", "Cache de shaders NVIDIA", "safe", &["%LOCALAPPDATA%\\NVIDIA\\DXCache", "%LOCALAPPDATA%\\NVIDIA\\GLCache", "%LOCALAPPDATA%\\NVIDIA Corporation\\NV_Cache"]),
- d("amd-cache", "system", "Cache de shaders AMD", "safe", &["%LOCALAPPDATA%\\AMD\\DxCache", "%LOCALAPPDATA%\\AMD\\GLCache", "%LOCALAPPDATA%\\AMD\\VkCache"]),
- d("intel-cache", "system", "Cache de shaders Intel", "safe", &["%LOCALAPPDATA%\\Intel\\ShaderCache"]),
- d("chrome", "browsers", "Google Chrome", "safe", &["%LOCALAPPDATA%\\Google\\Chrome\\User Data\\*\\Cache", "%LOCALAPPDATA%\\Google\\Chrome\\User Data\\*\\Code Cache", "%LOCALAPPDATA%\\Google\\Chrome\\User Data\\*\\GPUCache", "%LOCALAPPDATA%\\Google\\Chrome\\User Data\\ShaderCache"]),
- d("edge", "browsers", "Microsoft Edge", "safe", &["%LOCALAPPDATA%\\Microsoft\\Edge\\User Data\\*\\Cache", "%LOCALAPPDATA%\\Microsoft\\Edge\\User Data\\*\\Code Cache", "%LOCALAPPDATA%\\Microsoft\\Edge\\User Data\\*\\GPUCache"]),
- d("brave", "browsers", "Brave", "safe", &["%LOCALAPPDATA%\\BraveSoftware\\Brave-Browser\\User Data\\*\\Cache", "%LOCALAPPDATA%\\BraveSoftware\\Brave-Browser\\User Data\\*\\Code Cache"]),
- d("firefox", "browsers", "Firefox", "safe", &["%LOCALAPPDATA%\\Mozilla\\Firefox\\Profiles\\*\\cache2", "%LOCALAPPDATA%\\Mozilla\\Firefox\\Profiles\\*\\startupCache"]),
- d("opera", "browsers", "Opera / Opera GX", "safe", &["%APPDATA%\\Opera Software\\Opera Stable\\Cache", "%APPDATA%\\Opera Software\\Opera GX Stable\\Cache", "%LOCALAPPDATA%\\Opera Software\\Opera Stable\\Cache"]),
- d("vivaldi", "browsers", "Vivaldi", "safe", &["%LOCALAPPDATA%\\Vivaldi\\User Data\\*\\Cache", "%LOCALAPPDATA%\\Vivaldi\\User Data\\*\\Code Cache"]),
- d("spotify", "apps", "Spotify", "safe", &["%LOCALAPPDATA%\\Spotify\\Storage", "%LOCALAPPDATA%\\Spotify\\Data", "%APPDATA%\\Spotify\\Storage"]),
- d("discord", "apps", "Discord", "safe", &["%APPDATA%\\discord\\Cache", "%APPDATA%\\discord\\Code Cache", "%APPDATA%\\discord\\GPUCache"]),
- d("slack", "apps", "Slack", "safe", &["%APPDATA%\\Slack\\Cache", "%APPDATA%\\Slack\\Code Cache", "%APPDATA%\\Slack\\GPUCache", "%APPDATA%\\Slack\\logs"]),
- d("teams", "apps", "Microsoft Teams", "safe", &["%APPDATA%\\Microsoft\\Teams\\Cache", "%APPDATA%\\Microsoft\\Teams\\Code Cache", "%APPDATA%\\Microsoft\\Teams\\GPUCache", "%LOCALAPPDATA%\\Packages\\MSTeams_8wekyb3d8bbwe\\LocalCache\\Microsoft\\MSTeams\\Logs"]),
+ d(
+ "temp-user",
+ "system",
+ "Temporários do usuário (%TEMP%)",
+ "safe",
+ &["%TEMP%"],
+ ),
+ d(
+ "temp-windows",
+ "system",
+ "Temporários do Windows (precisa de administrador)",
+ "safe",
+ &["%SystemRoot%\\Temp"],
+ ),
+ d(
+ "inetcache",
+ "system",
+ "Cache do Internet Explorer/WebView",
+ "safe",
+ &["%LOCALAPPDATA%\\Microsoft\\Windows\\INetCache"],
+ ),
+ d(
+ "thumbcache",
+ "system",
+ "Cache de miniaturas do Explorer",
+ "review",
+ &["%LOCALAPPDATA%\\Microsoft\\Windows\\Explorer"],
+ ),
+ d(
+ "crashdumps",
+ "system",
+ "Despejos de falhas",
+ "safe",
+ &[
+ "%LOCALAPPDATA%\\CrashDumps",
+ "%LOCALAPPDATA%\\Microsoft\\Windows\\WER",
+ ],
+ ),
+ d(
+ "windows-update",
+ "system",
+ "Downloads do Windows Update (precisa de administrador)",
+ "review",
+ &["%SystemRoot%\\SoftwareDistribution\\Download"],
+ ),
+ d(
+ "prefetch",
+ "system",
+ "Prefetch (precisa de administrador)",
+ "review",
+ &["%SystemRoot%\\Prefetch"],
+ ),
+ d(
+ "delivery-opt",
+ "system",
+ "Otimização de Entrega",
+ "safe",
+ &["%SystemRoot%\\SoftwareDistribution\\DeliveryOptimization"],
+ ),
+ d(
+ "d3d-cache",
+ "system",
+ "Cache de shaders DirectX",
+ "safe",
+ &["%LOCALAPPDATA%\\D3DSCache"],
+ ),
+ d(
+ "nvidia-cache",
+ "system",
+ "Cache de shaders NVIDIA",
+ "safe",
+ &[
+ "%LOCALAPPDATA%\\NVIDIA\\DXCache",
+ "%LOCALAPPDATA%\\NVIDIA\\GLCache",
+ "%LOCALAPPDATA%\\NVIDIA Corporation\\NV_Cache",
+ ],
+ ),
+ d(
+ "amd-cache",
+ "system",
+ "Cache de shaders AMD",
+ "safe",
+ &[
+ "%LOCALAPPDATA%\\AMD\\DxCache",
+ "%LOCALAPPDATA%\\AMD\\GLCache",
+ "%LOCALAPPDATA%\\AMD\\VkCache",
+ ],
+ ),
+ d(
+ "intel-cache",
+ "system",
+ "Cache de shaders Intel",
+ "safe",
+ &["%LOCALAPPDATA%\\Intel\\ShaderCache"],
+ ),
+ d(
+ "chrome",
+ "browsers",
+ "Google Chrome",
+ "safe",
+ &[
+ "%LOCALAPPDATA%\\Google\\Chrome\\User Data\\*\\Cache",
+ "%LOCALAPPDATA%\\Google\\Chrome\\User Data\\*\\Code Cache",
+ "%LOCALAPPDATA%\\Google\\Chrome\\User Data\\*\\GPUCache",
+ "%LOCALAPPDATA%\\Google\\Chrome\\User Data\\ShaderCache",
+ ],
+ ),
+ d(
+ "edge",
+ "browsers",
+ "Microsoft Edge",
+ "safe",
+ &[
+ "%LOCALAPPDATA%\\Microsoft\\Edge\\User Data\\*\\Cache",
+ "%LOCALAPPDATA%\\Microsoft\\Edge\\User Data\\*\\Code Cache",
+ "%LOCALAPPDATA%\\Microsoft\\Edge\\User Data\\*\\GPUCache",
+ ],
+ ),
+ d(
+ "brave",
+ "browsers",
+ "Brave",
+ "safe",
+ &[
+ "%LOCALAPPDATA%\\BraveSoftware\\Brave-Browser\\User Data\\*\\Cache",
+ "%LOCALAPPDATA%\\BraveSoftware\\Brave-Browser\\User Data\\*\\Code Cache",
+ ],
+ ),
+ d(
+ "firefox",
+ "browsers",
+ "Firefox",
+ "safe",
+ &[
+ "%LOCALAPPDATA%\\Mozilla\\Firefox\\Profiles\\*\\cache2",
+ "%LOCALAPPDATA%\\Mozilla\\Firefox\\Profiles\\*\\startupCache",
+ ],
+ ),
+ d(
+ "opera",
+ "browsers",
+ "Opera / Opera GX",
+ "safe",
+ &[
+ "%APPDATA%\\Opera Software\\Opera Stable\\Cache",
+ "%APPDATA%\\Opera Software\\Opera GX Stable\\Cache",
+ "%LOCALAPPDATA%\\Opera Software\\Opera Stable\\Cache",
+ ],
+ ),
+ d(
+ "vivaldi",
+ "browsers",
+ "Vivaldi",
+ "safe",
+ &[
+ "%LOCALAPPDATA%\\Vivaldi\\User Data\\*\\Cache",
+ "%LOCALAPPDATA%\\Vivaldi\\User Data\\*\\Code Cache",
+ ],
+ ),
+ d(
+ "spotify",
+ "apps",
+ "Spotify",
+ "safe",
+ &[
+ "%LOCALAPPDATA%\\Spotify\\Storage",
+ "%LOCALAPPDATA%\\Spotify\\Data",
+ "%APPDATA%\\Spotify\\Storage",
+ ],
+ ),
+ d(
+ "discord",
+ "apps",
+ "Discord",
+ "safe",
+ &[
+ "%APPDATA%\\discord\\Cache",
+ "%APPDATA%\\discord\\Code Cache",
+ "%APPDATA%\\discord\\GPUCache",
+ ],
+ ),
+ d(
+ "slack",
+ "apps",
+ "Slack",
+ "safe",
+ &[
+ "%APPDATA%\\Slack\\Cache",
+ "%APPDATA%\\Slack\\Code Cache",
+ "%APPDATA%\\Slack\\GPUCache",
+ "%APPDATA%\\Slack\\logs",
+ ],
+ ),
+ d(
+ "teams",
+ "apps",
+ "Microsoft Teams",
+ "safe",
+ &[
+ "%APPDATA%\\Microsoft\\Teams\\Cache",
+ "%APPDATA%\\Microsoft\\Teams\\Code Cache",
+ "%APPDATA%\\Microsoft\\Teams\\GPUCache",
+ "%LOCALAPPDATA%\\Packages\\MSTeams_8wekyb3d8bbwe\\LocalCache\\Microsoft\\MSTeams\\Logs",
+ ],
+ ),
d("zoom", "apps", "Zoom", "safe", &["%APPDATA%\\Zoom\\logs"]),
- d("vscode", "apps", "Visual Studio Code", "safe", &["%APPDATA%\\Code\\Cache", "%APPDATA%\\Code\\CachedData", "%APPDATA%\\Code\\CachedExtensionVSIXs", "%APPDATA%\\Code\\logs"]),
- d("adobe", "apps", "Adobe (Media Cache)", "review", &["%APPDATA%\\Adobe\\Common\\Media Cache Files", "%APPDATA%\\Adobe\\Common\\Media Cache", "%APPDATA%\\Adobe\\Common\\Peak Files"]),
- d("telegram", "apps", "Telegram Desktop", "review", &["%APPDATA%\\Telegram Desktop\\tdata\\user_data\\cache", "%APPDATA%\\Telegram Desktop\\tdata\\user_data\\media_cache"]),
- d("whatsapp", "apps", "WhatsApp", "safe", &["%LOCALAPPDATA%\\WhatsApp\\Cache", "%LOCALAPPDATA%\\WhatsApp\\Code Cache"]),
- d("omniget-tmp", "apps", "OmniGet (temporários das tools)", "safe", &["%APPDATA%\\wtf.tonho.omniget\\tools\\tmp"]),
- d("npm", "dev", "npm cache", "safe", &["%LOCALAPPDATA%\\npm-cache"]),
- d("pnpm", "dev", "pnpm store", "review", &["%LOCALAPPDATA%\\pnpm\\store"]),
- d("yarn", "dev", "Yarn cache", "safe", &["%LOCALAPPDATA%\\Yarn\\Cache"]),
- d("pip", "dev", "pip cache", "safe", &["%LOCALAPPDATA%\\pip\\cache"]),
- d("cargo", "dev", "Cargo registry cache", "safe", &["%USERPROFILE%\\.cargo\\registry\\cache"]),
- d("gradle", "dev", "Gradle caches", "review", &["%USERPROFILE%\\.gradle\\caches"]),
- d("nuget", "dev", "NuGet cache", "safe", &["%LOCALAPPDATA%\\NuGet\\v3-cache", "%LOCALAPPDATA%\\NuGet\\Cache"]),
- d("go", "dev", "Go build cache", "safe", &["%LOCALAPPDATA%\\go-build"]),
- d("composer", "dev", "Composer cache", "safe", &["%LOCALAPPDATA%\\Composer"]),
- d("steam", "gaming", "Steam (http e shader cache)", "safe", &["%ProgramFiles(x86)%\\Steam\\appcache\\httpcache", "%ProgramFiles(x86)%\\Steam\\steamapps\\shadercache", "%ProgramFiles(x86)%\\Steam\\logs", "%ProgramFiles(x86)%\\Steam\\dumps"]),
- d("epic", "gaming", "Epic Games Launcher", "safe", &["%LOCALAPPDATA%\\EpicGamesLauncher\\Saved\\webcache", "%LOCALAPPDATA%\\EpicGamesLauncher\\Saved\\Logs"]),
- d("battlenet", "gaming", "Battle.net", "safe", &["%ProgramData%\\Battle.net\\Agent\\data\\cache", "%LOCALAPPDATA%\\Battle.net\\Cache"]),
- d("riot", "gaming", "Riot Client", "safe", &["%LOCALAPPDATA%\\Riot Games\\Riot Client\\Logs"]),
- d("ubisoft", "gaming", "Ubisoft Connect", "safe", &["%LOCALAPPDATA%\\Ubisoft Game Launcher\\cache", "%LOCALAPPDATA%\\Ubisoft Game Launcher\\logs"]),
+ d(
+ "vscode",
+ "apps",
+ "Visual Studio Code",
+ "safe",
+ &[
+ "%APPDATA%\\Code\\Cache",
+ "%APPDATA%\\Code\\CachedData",
+ "%APPDATA%\\Code\\CachedExtensionVSIXs",
+ "%APPDATA%\\Code\\logs",
+ ],
+ ),
+ d(
+ "adobe",
+ "apps",
+ "Adobe (Media Cache)",
+ "review",
+ &[
+ "%APPDATA%\\Adobe\\Common\\Media Cache Files",
+ "%APPDATA%\\Adobe\\Common\\Media Cache",
+ "%APPDATA%\\Adobe\\Common\\Peak Files",
+ ],
+ ),
+ d(
+ "telegram",
+ "apps",
+ "Telegram Desktop",
+ "review",
+ &[
+ "%APPDATA%\\Telegram Desktop\\tdata\\user_data\\cache",
+ "%APPDATA%\\Telegram Desktop\\tdata\\user_data\\media_cache",
+ ],
+ ),
+ d(
+ "whatsapp",
+ "apps",
+ "WhatsApp",
+ "safe",
+ &[
+ "%LOCALAPPDATA%\\WhatsApp\\Cache",
+ "%LOCALAPPDATA%\\WhatsApp\\Code Cache",
+ ],
+ ),
+ d(
+ "omniget-tmp",
+ "apps",
+ "OmniGet (temporários das tools)",
+ "safe",
+ &["%APPDATA%\\wtf.tonho.omniget\\tools\\tmp"],
+ ),
+ d(
+ "npm",
+ "dev",
+ "npm cache",
+ "safe",
+ &["%LOCALAPPDATA%\\npm-cache"],
+ ),
+ d(
+ "pnpm",
+ "dev",
+ "pnpm store",
+ "review",
+ &["%LOCALAPPDATA%\\pnpm\\store"],
+ ),
+ d(
+ "yarn",
+ "dev",
+ "Yarn cache",
+ "safe",
+ &["%LOCALAPPDATA%\\Yarn\\Cache"],
+ ),
+ d(
+ "pip",
+ "dev",
+ "pip cache",
+ "safe",
+ &["%LOCALAPPDATA%\\pip\\cache"],
+ ),
+ d(
+ "cargo",
+ "dev",
+ "Cargo registry cache",
+ "safe",
+ &["%USERPROFILE%\\.cargo\\registry\\cache"],
+ ),
+ d(
+ "gradle",
+ "dev",
+ "Gradle caches",
+ "review",
+ &["%USERPROFILE%\\.gradle\\caches"],
+ ),
+ d(
+ "nuget",
+ "dev",
+ "NuGet cache",
+ "safe",
+ &[
+ "%LOCALAPPDATA%\\NuGet\\v3-cache",
+ "%LOCALAPPDATA%\\NuGet\\Cache",
+ ],
+ ),
+ d(
+ "go",
+ "dev",
+ "Go build cache",
+ "safe",
+ &["%LOCALAPPDATA%\\go-build"],
+ ),
+ d(
+ "composer",
+ "dev",
+ "Composer cache",
+ "safe",
+ &["%LOCALAPPDATA%\\Composer"],
+ ),
+ d(
+ "steam",
+ "gaming",
+ "Steam (http e shader cache)",
+ "safe",
+ &[
+ "%ProgramFiles(x86)%\\Steam\\appcache\\httpcache",
+ "%ProgramFiles(x86)%\\Steam\\steamapps\\shadercache",
+ "%ProgramFiles(x86)%\\Steam\\logs",
+ "%ProgramFiles(x86)%\\Steam\\dumps",
+ ],
+ ),
+ d(
+ "epic",
+ "gaming",
+ "Epic Games Launcher",
+ "safe",
+ &[
+ "%LOCALAPPDATA%\\EpicGamesLauncher\\Saved\\webcache",
+ "%LOCALAPPDATA%\\EpicGamesLauncher\\Saved\\Logs",
+ ],
+ ),
+ d(
+ "battlenet",
+ "gaming",
+ "Battle.net",
+ "safe",
+ &[
+ "%ProgramData%\\Battle.net\\Agent\\data\\cache",
+ "%LOCALAPPDATA%\\Battle.net\\Cache",
+ ],
+ ),
+ d(
+ "riot",
+ "gaming",
+ "Riot Client",
+ "safe",
+ &["%LOCALAPPDATA%\\Riot Games\\Riot Client\\Logs"],
+ ),
+ d(
+ "ubisoft",
+ "gaming",
+ "Ubisoft Connect",
+ "safe",
+ &[
+ "%LOCALAPPDATA%\\Ubisoft Game Launcher\\cache",
+ "%LOCALAPPDATA%\\Ubisoft Game Launcher\\logs",
+ ],
+ ),
];
#[cfg(all(unix, not(target_os = "macos")))]
const DEFS: &[Def] = &[
- d("user-cache", "system", "Cache do usuário (~/.cache)", "review", &["~/.cache"]),
- d("thumbnails", "system", "Miniaturas", "safe", &["~/.cache/thumbnails", "~/.thumbnails"]),
- d("shader-cache", "system", "Cache de shaders (Mesa/NVIDIA)", "safe", &["~/.cache/mesa_shader_cache", "~/.cache/mesa_shader_cache_db", "~/.cache/nvidia", "~/.nv/GLCache"]),
- d("crash", "system", "Relatórios de erro", "safe", &["~/.cache/abrt", "~/.local/share/apport"]),
- d("chrome", "browsers", "Google Chrome", "safe", &["~/.cache/google-chrome", "~/.var/app/com.google.Chrome/cache"]),
- d("chromium", "browsers", "Chromium", "safe", &["~/.cache/chromium", "~/.var/app/org.chromium.Chromium/cache", "~/snap/chromium/common/.cache"]),
- d("brave", "browsers", "Brave", "safe", &["~/.cache/BraveSoftware", "~/.var/app/com.brave.Browser/cache"]),
- d("edge", "browsers", "Microsoft Edge", "safe", &["~/.cache/microsoft-edge", "~/.var/app/com.microsoft.Edge/cache"]),
- d("firefox", "browsers", "Firefox", "safe", &["~/.cache/mozilla/firefox/*/cache2", "~/.var/app/org.mozilla.firefox/cache/mozilla/firefox/*/cache2", "~/snap/firefox/common/.cache/mozilla/firefox/*/cache2"]),
- d("vivaldi", "browsers", "Vivaldi", "safe", &["~/.cache/vivaldi"]),
+ d(
+ "user-cache",
+ "system",
+ "Cache do usuário (~/.cache)",
+ "review",
+ &["~/.cache"],
+ ),
+ d(
+ "thumbnails",
+ "system",
+ "Miniaturas",
+ "safe",
+ &["~/.cache/thumbnails", "~/.thumbnails"],
+ ),
+ d(
+ "shader-cache",
+ "system",
+ "Cache de shaders (Mesa/NVIDIA)",
+ "safe",
+ &[
+ "~/.cache/mesa_shader_cache",
+ "~/.cache/mesa_shader_cache_db",
+ "~/.cache/nvidia",
+ "~/.nv/GLCache",
+ ],
+ ),
+ d(
+ "crash",
+ "system",
+ "Relatórios de erro",
+ "safe",
+ &["~/.cache/abrt", "~/.local/share/apport"],
+ ),
+ d(
+ "chrome",
+ "browsers",
+ "Google Chrome",
+ "safe",
+ &[
+ "~/.cache/google-chrome",
+ "~/.var/app/com.google.Chrome/cache",
+ ],
+ ),
+ d(
+ "chromium",
+ "browsers",
+ "Chromium",
+ "safe",
+ &[
+ "~/.cache/chromium",
+ "~/.var/app/org.chromium.Chromium/cache",
+ "~/snap/chromium/common/.cache",
+ ],
+ ),
+ d(
+ "brave",
+ "browsers",
+ "Brave",
+ "safe",
+ &[
+ "~/.cache/BraveSoftware",
+ "~/.var/app/com.brave.Browser/cache",
+ ],
+ ),
+ d(
+ "edge",
+ "browsers",
+ "Microsoft Edge",
+ "safe",
+ &[
+ "~/.cache/microsoft-edge",
+ "~/.var/app/com.microsoft.Edge/cache",
+ ],
+ ),
+ d(
+ "firefox",
+ "browsers",
+ "Firefox",
+ "safe",
+ &[
+ "~/.cache/mozilla/firefox/*/cache2",
+ "~/.var/app/org.mozilla.firefox/cache/mozilla/firefox/*/cache2",
+ "~/snap/firefox/common/.cache/mozilla/firefox/*/cache2",
+ ],
+ ),
+ d(
+ "vivaldi",
+ "browsers",
+ "Vivaldi",
+ "safe",
+ &["~/.cache/vivaldi"],
+ ),
d("opera", "browsers", "Opera", "safe", &["~/.cache/opera"]),
- d("spotify", "apps", "Spotify", "safe", &["~/.cache/spotify", "~/.var/app/com.spotify.Client/cache", "~/snap/spotify/common/.cache"]),
- d("discord", "apps", "Discord", "safe", &["~/.config/discord/Cache", "~/.config/discord/Code Cache", "~/.config/discord/GPUCache", "~/.var/app/com.discordapp.Discord/config/discord/Cache", "~/.var/app/com.discordapp.Discord/config/discord/Code Cache"]),
- d("slack", "apps", "Slack", "safe", &["~/.config/Slack/Cache", "~/.config/Slack/Code Cache", "~/.var/app/com.slack.Slack/config/Slack/Cache"]),
- d("vscode", "apps", "Visual Studio Code", "safe", &["~/.config/Code/Cache", "~/.config/Code/CachedData", "~/.config/Code/CachedExtensionVSIXs", "~/.config/Code/logs", "~/.var/app/com.visualstudio.code/config/Code/Cache"]),
- d("telegram", "apps", "Telegram Desktop", "review", &["~/.local/share/TelegramDesktop/tdata/user_data/cache", "~/.var/app/org.telegram.desktop/data/TelegramDesktop/tdata/user_data/cache"]),
- d("omniget-tmp", "apps", "OmniGet (temporários das tools)", "safe", &["~/.local/share/wtf.tonho.omniget/tools/tmp", "~/.var/app/wtf.tonho.omniget/data/wtf.tonho.omniget/tools/tmp"]),
- d("flatpak-unused", "apps", "Flatpak (.removed)", "safe", &["~/.local/share/flatpak/.removed"]),
- d("npm", "dev", "npm cache", "safe", &["~/.npm/_cacache", "~/.npm/_logs"]),
- d("pnpm", "dev", "pnpm store", "review", &["~/.local/share/pnpm/store", "~/.cache/pnpm"]),
- d("yarn", "dev", "Yarn cache", "safe", &["~/.cache/yarn", "~/.yarn/berry/cache"]),
+ d(
+ "spotify",
+ "apps",
+ "Spotify",
+ "safe",
+ &[
+ "~/.cache/spotify",
+ "~/.var/app/com.spotify.Client/cache",
+ "~/snap/spotify/common/.cache",
+ ],
+ ),
+ d(
+ "discord",
+ "apps",
+ "Discord",
+ "safe",
+ &[
+ "~/.config/discord/Cache",
+ "~/.config/discord/Code Cache",
+ "~/.config/discord/GPUCache",
+ "~/.var/app/com.discordapp.Discord/config/discord/Cache",
+ "~/.var/app/com.discordapp.Discord/config/discord/Code Cache",
+ ],
+ ),
+ d(
+ "slack",
+ "apps",
+ "Slack",
+ "safe",
+ &[
+ "~/.config/Slack/Cache",
+ "~/.config/Slack/Code Cache",
+ "~/.var/app/com.slack.Slack/config/Slack/Cache",
+ ],
+ ),
+ d(
+ "vscode",
+ "apps",
+ "Visual Studio Code",
+ "safe",
+ &[
+ "~/.config/Code/Cache",
+ "~/.config/Code/CachedData",
+ "~/.config/Code/CachedExtensionVSIXs",
+ "~/.config/Code/logs",
+ "~/.var/app/com.visualstudio.code/config/Code/Cache",
+ ],
+ ),
+ d(
+ "telegram",
+ "apps",
+ "Telegram Desktop",
+ "review",
+ &[
+ "~/.local/share/TelegramDesktop/tdata/user_data/cache",
+ "~/.var/app/org.telegram.desktop/data/TelegramDesktop/tdata/user_data/cache",
+ ],
+ ),
+ d(
+ "omniget-tmp",
+ "apps",
+ "OmniGet (temporários das tools)",
+ "safe",
+ &[
+ "~/.local/share/wtf.tonho.omniget/tools/tmp",
+ "~/.var/app/wtf.tonho.omniget/data/wtf.tonho.omniget/tools/tmp",
+ ],
+ ),
+ d(
+ "flatpak-unused",
+ "apps",
+ "Flatpak (.removed)",
+ "safe",
+ &["~/.local/share/flatpak/.removed"],
+ ),
+ d(
+ "npm",
+ "dev",
+ "npm cache",
+ "safe",
+ &["~/.npm/_cacache", "~/.npm/_logs"],
+ ),
+ d(
+ "pnpm",
+ "dev",
+ "pnpm store",
+ "review",
+ &["~/.local/share/pnpm/store", "~/.cache/pnpm"],
+ ),
+ d(
+ "yarn",
+ "dev",
+ "Yarn cache",
+ "safe",
+ &["~/.cache/yarn", "~/.yarn/berry/cache"],
+ ),
d("pip", "dev", "pip cache", "safe", &["~/.cache/pip"]),
- d("cargo", "dev", "Cargo registry cache", "safe", &["~/.cargo/registry/cache"]),
- d("gradle", "dev", "Gradle caches", "review", &["~/.gradle/caches"]),
- d("go", "dev", "Go build cache", "safe", &["~/.cache/go-build"]),
- d("composer", "dev", "Composer cache", "safe", &["~/.cache/composer"]),
- d("steam", "gaming", "Steam (http e shader cache)", "safe", &["~/.local/share/Steam/appcache/httpcache", "~/.local/share/Steam/steamapps/shadercache", "~/.local/share/Steam/logs", "~/.steam/steam/appcache/httpcache", "~/.steam/steam/steamapps/shadercache", "~/.var/app/com.valvesoftware.Steam/data/Steam/appcache/httpcache", "~/.var/app/com.valvesoftware.Steam/data/Steam/steamapps/shadercache"]),
+ d(
+ "cargo",
+ "dev",
+ "Cargo registry cache",
+ "safe",
+ &["~/.cargo/registry/cache"],
+ ),
+ d(
+ "gradle",
+ "dev",
+ "Gradle caches",
+ "review",
+ &["~/.gradle/caches"],
+ ),
+ d(
+ "go",
+ "dev",
+ "Go build cache",
+ "safe",
+ &["~/.cache/go-build"],
+ ),
+ d(
+ "composer",
+ "dev",
+ "Composer cache",
+ "safe",
+ &["~/.cache/composer"],
+ ),
+ d(
+ "steam",
+ "gaming",
+ "Steam (http e shader cache)",
+ "safe",
+ &[
+ "~/.local/share/Steam/appcache/httpcache",
+ "~/.local/share/Steam/steamapps/shadercache",
+ "~/.local/share/Steam/logs",
+ "~/.steam/steam/appcache/httpcache",
+ "~/.steam/steam/steamapps/shadercache",
+ "~/.var/app/com.valvesoftware.Steam/data/Steam/appcache/httpcache",
+ "~/.var/app/com.valvesoftware.Steam/data/Steam/steamapps/shadercache",
+ ],
+ ),
d("lutris", "gaming", "Lutris", "safe", &["~/.cache/lutris"]),
- d("heroic", "gaming", "Heroic Games Launcher", "safe", &["~/.config/heroic/Cache", "~/.var/app/com.heroicgameslauncher.hgl/config/heroic/Cache"]),
+ d(
+ "heroic",
+ "gaming",
+ "Heroic Games Launcher",
+ "safe",
+ &[
+ "~/.config/heroic/Cache",
+ "~/.var/app/com.heroicgameslauncher.hgl/config/heroic/Cache",
+ ],
+ ),
];
fn expand_vars(p: &str) -> String {
@@ -199,7 +755,11 @@ pub fn expand(pattern: &str) -> Vec<PathBuf> {
if s.contains('*') {
let mut next = Vec::new();
for base in &current {
- if let Ok(rd) = std::fs::read_dir(if base.as_os_str().is_empty() { Path::new("/") } else { base.as_path() }) {
+ if let Ok(rd) = std::fs::read_dir(if base.as_os_str().is_empty() {
+ Path::new("/")
+ } else {
+ base.as_path()
+ }) {
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().to_string();
if glob_match(&s, &name) {
@@ -254,7 +814,11 @@ pub fn measure(path: &Path) -> (u64, u64) {
if path.is_file() {
return (std::fs::metadata(path).map(|m| m.len()).unwrap_or(0), 1);
}
- for entry in walkdir::WalkDir::new(path).follow_links(false).into_iter().flatten() {
+ for entry in walkdir::WalkDir::new(path)
+ .follow_links(false)
+ .into_iter()
+ .flatten()
+ {
if entry.file_type().is_file() {
files += 1;
bytes += entry.metadata().map(|m| m.len()).unwrap_or(0);
@@ -267,7 +831,14 @@ pub fn scan(progress: &super::ProgressFn) -> Vec<CleanRule> {
let total = DEFS.len() as u64;
let mut out = Vec::new();
for (i, def) in DEFS.iter().enumerate() {
- super::report(progress, "sysclean", "progress", i as u64, Some(total), Some(def.name.to_string()));
+ super::report(
+ progress,
+ "sysclean",
+ "progress",
+ i as u64,
+ Some(total),
+ Some(def.name.to_string()),
+ );
let mut paths = Vec::new();
let mut bytes = 0u64;
let mut files = 0u64;
@@ -285,7 +856,15 @@ pub fn scan(progress: &super::ProgressFn) -> Vec<CleanRule> {
if paths.is_empty() {
continue;
}
- out.push(CleanRule { id: def.id.into(), group: def.group.into(), name: def.name.into(), risk: def.risk.into(), paths, bytes, files });
+ out.push(CleanRule {
+ id: def.id.into(),
+ group: def.group.into(),
+ name: def.name.into(),
+ risk: def.risk.into(),
+ paths,
+ bytes,
+ files,
+ });
}
super::report(progress, "sysclean", "done", total, Some(total), None);
out.sort_by_key(|b| std::cmp::Reverse(b.bytes));
@@ -326,17 +905,29 @@ fn remove_entry(path: &Path, to_trash: bool, result: &mut CleanResult) {
/// Apaga o conteúdo das pastas das regras escolhidas (não as pastas).
pub fn clean(req: &CleanRequest, progress: &super::ProgressFn) -> CleanResult {
let mut result = CleanResult::default();
- let defs: Vec<&Def> = DEFS.iter().filter(|d| req.ids.iter().any(|id| id == d.id)).collect();
+ let defs: Vec<&Def> = DEFS
+ .iter()
+ .filter(|d| req.ids.iter().any(|id| id == d.id))
+ .collect();
let total = defs.len() as u64;
for (i, def) in defs.iter().enumerate() {
- super::report(progress, "sysclean", "clean", i as u64, Some(total), Some(def.name.to_string()));
+ super::report(
+ progress,
+ "sysclean",
+ "clean",
+ i as u64,
+ Some(total),
+ Some(def.name.to_string()),
+ );
for pat in def.paths {
for root in expand(pat) {
if root.is_file() {
remove_entry(&root, req.to_trash, &mut result);
continue;
}
- let Ok(rd) = std::fs::read_dir(&root) else { continue };
+ let Ok(rd) = std::fs::read_dir(&root) else {
+ continue;
+ };
for e in rd.flatten() {
remove_entry(&e.path(), req.to_trash, &mut result);
}
@@ -392,7 +983,14 @@ mod live {
fn scan_here() {
let rules = super::scan(&super::super::noop_progress());
for r in &rules {
- println!("{:<9} {:<45} {:>12} {:>7} {}", r.group, r.name, r.bytes, r.files, r.paths.len());
+ println!(
+ "{:<9} {:<45} {:>12} {:>7} {}",
+ r.group,
+ r.name,
+ r.bytes,
+ r.files,
+ r.paths.len()
+ );
}
println!("{} regras com conteudo", rules.len());
}
diff --git a/src-tauri/omniget-core/src/core/tools/uninstall.rs b/src-tauri/omniget-core/src/core/tools/uninstall.rs
index f6f0ef83..f79d347f 100644
--- a/src-tauri/omniget-core/src/core/tools/uninstall.rs
+++ b/src-tauri/omniget-core/src/core/tools/uninstall.rs
@@ -39,9 +39,21 @@ fn size_of(path: &Path) -> u64 {
}
async fn run(program: &str, args: &[&str]) -> anyhow::Result<String> {
- let o = crate::core::process::command(program).args(args).output().await?;
+ let o = crate::core::process::command(program)
+ .args(args)
+ .output()
+ .await?;
if !o.status.success() {
- return Err(anyhow!("{} falhou: {}", program, String::from_utf8_lossy(if o.stderr.is_empty() { &o.stdout } else { &o.stderr }).trim()));
+ return Err(anyhow!(
+ "{} falhou: {}",
+ program,
+ String::from_utf8_lossy(if o.stderr.is_empty() {
+ &o.stdout
+ } else {
+ &o.stderr
+ })
+ .trim()
+ ));
}
Ok(String::from_utf8_lossy(&o.stdout).to_string())
}
@@ -64,7 +76,18 @@ async fn mac_list(progress: &super::ProgressFn) -> Vec<App> {
paths.sort();
let total = paths.len() as u64;
for (i, p) in paths.iter().enumerate() {
- super::report(progress, "uninstall", "progress", i as u64, Some(total), Some(p.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default()));
+ super::report(
+ progress,
+ "uninstall",
+ "progress",
+ i as u64,
+ Some(total),
+ Some(
+ p.file_name()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_default(),
+ ),
+ );
let info = p.join("Contents/Info.plist");
let json = crate::core::process::command("plutil")
.args(["-convert", "json", "-o", "-"])
@@ -75,14 +98,26 @@ async fn mac_list(progress: &super::ProgressFn) -> Vec<App> {
.filter(|o| o.status.success())
.and_then(|o| serde_json::from_slice::<serde_json::Value>(&o.stdout).ok())
.unwrap_or(serde_json::Value::Null);
- let bundle = json.get("CFBundleIdentifier").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ let bundle = json
+ .get("CFBundleIdentifier")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
let name = json
.get("CFBundleDisplayName")
.or_else(|| json.get("CFBundleName"))
.and_then(|v| v.as_str())
.map(String::from)
- .unwrap_or_else(|| p.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default());
- let version = json.get("CFBundleShortVersionString").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ .unwrap_or_else(|| {
+ p.file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_default()
+ });
+ let version = json
+ .get("CFBundleShortVersionString")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
let apple = bundle.starts_with("com.apple.");
out.push(App {
id: format!("mac:{}", p.display()),
@@ -92,7 +127,10 @@ async fn mac_list(progress: &super::ProgressFn) -> Vec<App> {
kind: "app".into(),
path: p.to_string_lossy().to_string(),
bytes: size_of(p),
- needs_admin: apple || std::fs::metadata(p).map(|m| !is_writable(&m)).unwrap_or(false),
+ needs_admin: apple
+ || std::fs::metadata(p)
+ .map(|m| !is_writable(&m))
+ .unwrap_or(false),
key: bundle,
});
}
@@ -124,8 +162,15 @@ fn mac_leftovers(app: &App) -> Vec<Leftover> {
let h = home();
let lib = h.join("Library");
let mut out = Vec::new();
- let stem = Path::new(&app.path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
- let needles: Vec<String> = [app.key.clone(), stem.clone(), app.name.clone()].into_iter().filter(|s| s.len() >= 3).map(|s| s.to_lowercase()).collect();
+ let stem = Path::new(&app.path)
+ .file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_default();
+ let needles: Vec<String> = [app.key.clone(), stem.clone(), app.name.clone()]
+ .into_iter()
+ .filter(|s| s.len() >= 3)
+ .map(|s| s.to_lowercase())
+ .collect();
let dirs = [
"Application Support",
"Caches",
@@ -141,18 +186,27 @@ fn mac_leftovers(app: &App) -> Vec<Leftover> {
"Application Scripts",
];
for d in dirs {
- let Ok(rd) = std::fs::read_dir(lib.join(d)) else { continue };
+ let Ok(rd) = std::fs::read_dir(lib.join(d)) else {
+ continue;
+ };
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().to_lowercase();
let hit = needles.iter().any(|n| {
if n.contains('.') {
- name == *n || name.starts_with(&format!("{}.", n)) || name.starts_with(&format!("{}-", n))
+ name == *n
+ || name.starts_with(&format!("{}.", n))
+ || name.starts_with(&format!("{}-", n))
} else {
- name == *n || name == format!("{}.plist", n) || name.starts_with(&format!("{}.", n))
+ name == *n
+ || name == format!("{}.plist", n)
+ || name.starts_with(&format!("{}.", n))
}
});
if hit {
- out.push(Leftover { path: e.path().to_string_lossy().to_string(), bytes: size_of(&e.path()) });
+ out.push(Leftover {
+ path: e.path().to_string_lossy().to_string(),
+ bytes: size_of(&e.path()),
+ });
}
}
}
@@ -162,30 +216,64 @@ fn mac_leftovers(app: &App) -> Vec<Leftover> {
// ── Windows ────────────────────────────────────────────────────────────
const UNINSTALL_KEYS: &[(&str, bool)] = &[
- (r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", true),
- (r"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall", true),
- (r"HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall", false),
+ (
+ r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
+ true,
+ ),
+ (
+ r"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
+ true,
+ ),
+ (
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall",
+ false,
+ ),
];
async fn win_list(progress: &super::ProgressFn) -> Vec<App> {
let mut out = Vec::new();
for (i, (root, admin)) in UNINSTALL_KEYS.iter().enumerate() {
- super::report(progress, "uninstall", "progress", i as u64, Some(3), Some(root.to_string()));
+ super::report(
+ progress,
+ "uninstall",
+ "progress",
+ i as u64,
+ Some(3),
+ Some(root.to_string()),
+ );
for key in super::win_registry::reg_query(root, true).await {
if key.path.eq_ignore_ascii_case(root) {
continue;
}
- let get = |n: &str| key.values.iter().find(|v| v.name.eq_ignore_ascii_case(n)).map(|v| v.data.clone()).unwrap_or_default();
+ let get = |n: &str| {
+ key.values
+ .iter()
+ .find(|v| v.name.eq_ignore_ascii_case(n))
+ .map(|v| v.data.clone())
+ .unwrap_or_default()
+ };
let name = get("DisplayName");
- if name.trim().is_empty() || get("SystemComponent") == "0x1" || !get("ParentKeyName").is_empty() && get("ReleaseType").contains("Update") {
+ if name.trim().is_empty()
+ || get("SystemComponent") == "0x1"
+ || !get("ParentKeyName").is_empty() && get("ReleaseType").contains("Update")
+ {
continue;
}
- let unins = if get("QuietUninstallString").is_empty() { get("UninstallString") } else { get("QuietUninstallString") };
+ let unins = if get("QuietUninstallString").is_empty() {
+ get("UninstallString")
+ } else {
+ get("QuietUninstallString")
+ };
if unins.trim().is_empty() {
continue;
}
- let kb = u64::from_str_radix(get("EstimatedSize").trim_start_matches("0x"), 16).unwrap_or(0);
- let kind = if unins.to_ascii_lowercase().contains("msiexec") { "msi" } else { "exe" };
+ let kb =
+ u64::from_str_radix(get("EstimatedSize").trim_start_matches("0x"), 16).unwrap_or(0);
+ let kind = if unins.to_ascii_lowercase().contains("msiexec") {
+ "msi"
+ } else {
+ "exe"
+ };
out.push(App {
id: format!("win:{}", key.path),
name,
@@ -206,9 +294,16 @@ async fn win_list(progress: &super::ProgressFn) -> Vec<App> {
fn win_leftovers(app: &App) -> Vec<Leftover> {
let mut out = Vec::new();
if !app.path.trim().is_empty() && Path::new(app.path.trim()).exists() {
- out.push(Leftover { path: app.path.clone(), bytes: size_of(Path::new(&app.path)) });
+ out.push(Leftover {
+ path: app.path.clone(),
+ bytes: size_of(Path::new(&app.path)),
+ });
}
- let needles: Vec<String> = [app.name.clone(), app.publisher.clone()].into_iter().filter(|s| s.len() >= 3).map(|s| s.to_lowercase()).collect();
+ let needles: Vec<String> = [app.name.clone(), app.publisher.clone()]
+ .into_iter()
+ .filter(|s| s.len() >= 3)
+ .map(|s| s.to_lowercase())
+ .collect();
let mut bases = Vec::new();
for var in ["APPDATA", "LOCALAPPDATA", "ProgramData"] {
if let Ok(v) = std::env::var(var) {
@@ -219,13 +314,18 @@ fn win_leftovers(app: &App) -> Vec<Leftover> {
bases.push(PathBuf::from(v).join("Programs"));
}
for base in bases {
- let Ok(rd) = std::fs::read_dir(&base) else { continue };
+ let Ok(rd) = std::fs::read_dir(&base) else {
+ continue;
+ };
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().to_lowercase();
if needles.contains(&name) {
let p = e.path();
if p.to_string_lossy() != app.path {
- out.push(Leftover { path: p.to_string_lossy().to_string(), bytes: size_of(&p) });
+ out.push(Leftover {
+ path: p.to_string_lossy().to_string(),
+ bytes: size_of(&p),
+ });
}
}
}
@@ -237,8 +337,24 @@ fn win_leftovers(app: &App) -> Vec<Leftover> {
async fn linux_list(progress: &super::ProgressFn) -> Vec<App> {
let mut out = Vec::new();
- super::report(progress, "uninstall", "progress", 0, Some(4), Some("flatpak".into()));
- if let Ok(list) = run("flatpak", &["list", "--app", "--columns=application,name,version,installation,size"]).await {
+ super::report(
+ progress,
+ "uninstall",
+ "progress",
+ 0,
+ Some(4),
+ Some("flatpak".into()),
+ );
+ if let Ok(list) = run(
+ "flatpak",
+ &[
+ "list",
+ "--app",
+ "--columns=application,name,version,installation,size",
+ ],
+ )
+ .await
+ {
for l in list.lines() {
let cols: Vec<&str> = l.split('\t').collect();
if cols.len() < 2 {
@@ -249,21 +365,42 @@ async fn linux_list(progress: &super::ProgressFn) -> Vec<App> {
out.push(App {
id: format!("flatpak:{}", id),
name: cols[1].trim().to_string(),
- version: cols.get(2).map(|s| s.trim().to_string()).unwrap_or_default(),
+ version: cols
+ .get(2)
+ .map(|s| s.trim().to_string())
+ .unwrap_or_default(),
publisher: id.rsplit('.').nth(1).unwrap_or("").to_string(),
kind: "flatpak".into(),
- path: home().join(".var/app").join(id).to_string_lossy().to_string(),
+ path: home()
+ .join(".var/app")
+ .join(id)
+ .to_string_lossy()
+ .to_string(),
bytes: size,
needs_admin: cols.get(3).map(|s| s.trim() == "system").unwrap_or(false),
key: id.to_string(),
});
}
}
- super::report(progress, "uninstall", "progress", 1, Some(4), Some("snap".into()));
+ super::report(
+ progress,
+ "uninstall",
+ "progress",
+ 1,
+ Some(4),
+ Some("snap".into()),
+ );
if let Ok(list) = run("snap", &["list"]).await {
for l in list.lines().skip(1) {
let cols: Vec<&str> = l.split_whitespace().collect();
- if cols.len() < 2 || matches!(cols[0], "core" | "core18" | "core20" | "core22" | "core24" | "snapd" | "bare") || cols[0].starts_with("gnome-") || cols[0].starts_with("gtk-common") {
+ if cols.len() < 2
+ || matches!(
+ cols[0],
+ "core" | "core18" | "core20" | "core22" | "core24" | "snapd" | "bare"
+ )
+ || cols[0].starts_with("gnome-")
+ || cols[0].starts_with("gtk-common")
+ {
continue;
}
out.push(App {
@@ -279,15 +416,34 @@ async fn linux_list(progress: &super::ProgressFn) -> Vec<App> {
});
}
}
- super::report(progress, "uninstall", "progress", 2, Some(4), Some("AppImage".into()));
- for dir in [home().join("Applications"), home().join(".local/bin"), home().join("AppImages")] {
- let Ok(rd) = std::fs::read_dir(&dir) else { continue };
+ super::report(
+ progress,
+ "uninstall",
+ "progress",
+ 2,
+ Some(4),
+ Some("AppImage".into()),
+ );
+ for dir in [
+ home().join("Applications"),
+ home().join(".local/bin"),
+ home().join("AppImages"),
+ ] {
+ let Ok(rd) = std::fs::read_dir(&dir) else {
+ continue;
+ };
for e in rd.flatten() {
let p = e.path();
- if p.extension().map(|x| x.eq_ignore_ascii_case("appimage")).unwrap_or(false) {
+ if p.extension()
+ .map(|x| x.eq_ignore_ascii_case("appimage"))
+ .unwrap_or(false)
+ {
out.push(App {
id: format!("appimage:{}", p.display()),
- name: p.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(),
+ name: p
+ .file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_default(),
version: String::new(),
publisher: String::new(),
kind: "appimage".into(),
@@ -299,11 +455,34 @@ async fn linux_list(progress: &super::ProgressFn) -> Vec<App> {
}
}
}
- super::report(progress, "uninstall", "progress", 3, Some(4), Some("pacotes".into()));
+ super::report(
+ progress,
+ "uninstall",
+ "progress",
+ 3,
+ Some(4),
+ Some("pacotes".into()),
+ );
// Pacotes com .desktop (apps de verdade, não bibliotecas)
let mut desktop_pkgs = std::collections::HashSet::new();
- if let Ok(list) = run("dpkg-query", &["-W", "-f=${Package}\t${Version}\t${Installed-Size}\t${Maintainer}\n"]).await {
- if let Ok(files) = run("bash", &["-lc", "dpkg -S /usr/share/applications/*.desktop 2>/dev/null | cut -d: -f1 | sort -u"]).await {
+ if let Ok(list) = run(
+ "dpkg-query",
+ &[
+ "-W",
+ "-f=${Package}\t${Version}\t${Installed-Size}\t${Maintainer}\n",
+ ],
+ )
+ .await
+ {
+ if let Ok(files) = run(
+ "bash",
+ &[
+ "-lc",
+ "dpkg -S /usr/share/applications/*.desktop 2>/dev/null | cut -d: -f1 | sort -u",
+ ],
+ )
+ .await
+ {
desktop_pkgs.extend(files.lines().map(|s| s.trim().to_string()));
}
for l in list.lines() {
@@ -315,7 +494,14 @@ async fn linux_list(progress: &super::ProgressFn) -> Vec<App> {
id: format!("deb:{}", cols[0]),
name: cols[0].to_string(),
version: cols[1].to_string(),
- publisher: cols.get(3).unwrap_or(&"").split('<').next().unwrap_or("").trim().to_string(),
+ publisher: cols
+ .get(3)
+ .unwrap_or(&"")
+ .split('<')
+ .next()
+ .unwrap_or("")
+ .trim()
+ .to_string(),
kind: "deb".into(),
path: String::new(),
bytes: cols[2].trim().parse::<u64>().unwrap_or(0) * 1024,
@@ -323,8 +509,25 @@ async fn linux_list(progress: &super::ProgressFn) -> Vec<App> {
key: cols[0].to_string(),
});
}
- } else if let Ok(list) = run("rpm", &["-qa", "--queryformat", "%{NAME}\t%{VERSION}\t%{SIZE}\t%{VENDOR}\n"]).await {
- if let Ok(files) = run("bash", &["-lc", "rpm -qf /usr/share/applications/*.desktop 2>/dev/null | sort -u"]).await {
+ } else if let Ok(list) = run(
+ "rpm",
+ &[
+ "-qa",
+ "--queryformat",
+ "%{NAME}\t%{VERSION}\t%{SIZE}\t%{VENDOR}\n",
+ ],
+ )
+ .await
+ {
+ if let Ok(files) = run(
+ "bash",
+ &[
+ "-lc",
+ "rpm -qf /usr/share/applications/*.desktop 2>/dev/null | sort -u",
+ ],
+ )
+ .await
+ {
for f in files.lines() {
// nome-versao-release.arch → nome
if let Some(idx) = f.rfind('-').and_then(|i| f[..i].rfind('-')) {
@@ -370,13 +573,27 @@ fn parse_size(s: &str) -> u64 {
fn linux_leftovers(app: &App) -> Vec<Leftover> {
let h = home();
let mut out = Vec::new();
- let needles: Vec<String> = [app.key.clone(), app.name.clone()].into_iter().filter(|s| s.len() >= 3).map(|s| s.to_lowercase()).collect();
- for base in [h.join(".config"), h.join(".local/share"), h.join(".cache"), h.join(".var/app")] {
- let Ok(rd) = std::fs::read_dir(&base) else { continue };
+ let needles: Vec<String> = [app.key.clone(), app.name.clone()]
+ .into_iter()
+ .filter(|s| s.len() >= 3)
+ .map(|s| s.to_lowercase())
+ .collect();
+ for base in [
+ h.join(".config"),
+ h.join(".local/share"),
+ h.join(".cache"),
+ h.join(".var/app"),
+ ] {
+ let Ok(rd) = std::fs::read_dir(&base) else {
+ continue;
+ };
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().to_lowercase();
if needles.contains(&name) {
- out.push(Leftover { path: e.path().to_string_lossy().to_string(), bytes: size_of(&e.path()) });
+ out.push(Leftover {
+ path: e.path().to_string_lossy().to_string(),
+ bytes: size_of(&e.path()),
+ });
}
}
}
@@ -423,8 +640,14 @@ pub async fn uninstall(app: &App, leftover_paths: &[String]) -> UninstallResult
Ok(_) => Ok("movido para a Lixeira".into()),
Err(e) => {
// Sem permissão: pede ao Finder (dialogo de senha do sistema)
- let script = format!("tell application \"Finder\" to delete POSIX file \"{}\"", app.path.replace('"', "\\\""));
- run("osascript", &["-e", &script]).await.map(|_| "movido para a Lixeira".into()).map_err(|_| anyhow!("{}", e))
+ let script = format!(
+ "tell application \"Finder\" to delete POSIX file \"{}\"",
+ app.path.replace('"', "\\\"")
+ );
+ run("osascript", &["-e", &script])
+ .await
+ .map(|_| "movido para a Lixeira".into())
+ .map_err(|_| anyhow!("{}", e))
}
}
} else if cfg!(target_os = "windows") {
@@ -432,22 +655,53 @@ pub async fn uninstall(app: &App, leftover_paths: &[String]) -> UninstallResult
let lower = cmd.to_ascii_lowercase();
if lower.contains("msiexec") {
// MsiExec.exe /I{GUID} → /X{GUID} silencioso
- let guid = cmd.split(['{', '}']).nth(1).map(|g| format!("{{{}}}", g)).unwrap_or_default();
+ let guid = cmd
+ .split(['{', '}'])
+ .nth(1)
+ .map(|g| format!("{{{}}}", g))
+ .unwrap_or_default();
if guid.is_empty() {
Err(anyhow!("UninstallString sem GUID: {}", cmd))
} else {
- run("msiexec", &["/x", &guid, "/passive", "/norestart"]).await.map(|_| "desinstalado".into())
+ run("msiexec", &["/x", &guid, "/passive", "/norestart"])
+ .await
+ .map(|_| "desinstalado".into())
}
} else {
- run("cmd", &["/C", cmd]).await.map(|_| "desinstalador executado".into())
+ run("cmd", &["/C", cmd])
+ .await
+ .map(|_| "desinstalador executado".into())
}
} else {
match app.kind.as_str() {
- "flatpak" => run("flatpak", &["uninstall", "-y", "--delete-data", if app.needs_admin { "--system" } else { "--user" }, &app.key]).await.map(|_| "desinstalado".into()),
- "snap" => run("pkexec", &["snap", "remove", &app.key]).await.map(|_| "desinstalado".into()),
- "deb" => run("pkexec", &["apt-get", "remove", "-y", &app.key]).await.map(|_| "desinstalado".into()),
- "rpm" => run("pkexec", &["dnf", "remove", "-y", &app.key]).await.map(|_| "desinstalado".into()),
- _ => trash::delete(&app.path).map(|_| "movido para a lixeira".to_string()).map_err(|e| anyhow!("{}", e)),
+ "flatpak" => run(
+ "flatpak",
+ &[
+ "uninstall",
+ "-y",
+ "--delete-data",
+ if app.needs_admin {
+ "--system"
+ } else {
+ "--user"
+ },
+ &app.key,
+ ],
+ )
+ .await
+ .map(|_| "desinstalado".into()),
+ "snap" => run("pkexec", &["snap", "remove", &app.key])
+ .await
+ .map(|_| "desinstalado".into()),
+ "deb" => run("pkexec", &["apt-get", "remove", "-y", &app.key])
+ .await
+ .map(|_| "desinstalado".into()),
+ "rpm" => run("pkexec", &["dnf", "remove", "-y", &app.key])
+ .await
+ .map(|_| "desinstalado".into()),
+ _ => trash::delete(&app.path)
+ .map(|_| "movido para a lixeira".to_string())
+ .map_err(|e| anyhow!("{}", e)),
}
};
match res {
@@ -490,10 +744,22 @@ mod live {
async fn list_here() {
let apps = super::list(super::super::noop_progress()).await;
for a in apps.iter().take(15) {
- println!("{:<9} {:<40} {:<10} {:>10} admin={} {}", a.kind, a.name.chars().take(40).collect::<String>(), a.version, a.bytes, a.needs_admin, a.key);
+ println!(
+ "{:<9} {:<40} {:<10} {:>10} admin={} {}",
+ a.kind,
+ a.name.chars().take(40).collect::<String>(),
+ a.version,
+ a.bytes,
+ a.needs_admin,
+ a.key
+ );
}
println!("{} apps", apps.len());
- if let Some(a) = apps.iter().find(|a| a.name.to_lowercase().contains("spotify") || a.name.to_lowercase().contains("discord") || a.name.to_lowercase().contains("code")) {
+ if let Some(a) = apps.iter().find(|a| {
+ a.name.to_lowercase().contains("spotify")
+ || a.name.to_lowercase().contains("discord")
+ || a.name.to_lowercase().contains("code")
+ }) {
for l in super::leftovers(a) {
println!(" sobra: {} ({})", l.path, l.bytes);
}
diff --git a/src-tauri/omniget-core/src/core/tools/upscale.rs b/src-tauri/omniget-core/src/core/tools/upscale.rs
index d2e65d29..7ea78253 100644
--- a/src-tauri/omniget-core/src/core/tools/upscale.rs
+++ b/src-tauri/omniget-core/src/core/tools/upscale.rs
@@ -53,8 +53,16 @@ fn models_of(bin: &Path) -> Vec<String> {
pub fn status() -> UpscaleStatus {
match locate() {
- Some(p) => UpscaleStatus { installed: true, models: models_of(&p), path: Some(p.to_string_lossy().to_string()) },
- None => UpscaleStatus { installed: false, path: None, models: vec![] },
+ Some(p) => UpscaleStatus {
+ installed: true,
+ models: models_of(&p),
+ path: Some(p.to_string_lossy().to_string()),
+ },
+ None => UpscaleStatus {
+ installed: false,
+ path: None,
+ models: vec![],
+ },
}
}
@@ -88,7 +96,9 @@ pub async fn install(progress: super::ProgressFn) -> anyhow::Result<String> {
github::make_executable(&exe);
github::swap_dir(&staging, &dir)?;
github::strip_quarantine(&dir).await;
- locate().map(|p| p.to_string_lossy().to_string()).ok_or_else(|| anyhow!("binario sumiu apos instalar"))
+ locate()
+ .map(|p| p.to_string_lossy().to_string())
+ .ok_or_else(|| anyhow!("binario sumiu apos instalar"))
}
#[derive(Debug, Clone, Deserialize)]
@@ -123,7 +133,10 @@ pub struct UpscaleResult {
pub failed: Vec<String>,
}
-pub async fn run(opts: UpscaleOptions, progress: super::ProgressFn) -> anyhow::Result<UpscaleResult> {
+pub async fn run(
+ opts: UpscaleOptions,
+ progress: super::ProgressFn,
+) -> anyhow::Result<UpscaleResult> {
use tokio::io::{AsyncBufReadExt, BufReader};
let bin = locate().ok_or_else(|| anyhow!("Real-ESRGAN nao esta instalado"))?;
let models_dir = bin.parent().map(|p| p.join("models")).unwrap_or_default();
@@ -138,17 +151,34 @@ pub async fn run(opts: UpscaleOptions, progress: super::ProgressFn) -> anyhow::R
PathBuf::from(opts.output_dir.trim())
};
std::fs::create_dir_all(&out_dir)?;
- let stem = inp.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "imagem".into());
+ let stem = inp
+ .file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| "imagem".into());
let out = out_dir.join(format!("{}_{}x.{}", stem, opts.scale, opts.format));
let id = format!("upscale:{}", input);
super::report(&progress, &id, "started", i as u64, Some(total), None);
let mut cmd = crate::core::process::command(&bin);
- cmd.arg("-i").arg(inp).arg("-o").arg(&out).arg("-m").arg(&models_dir);
- cmd.args(["-n", &opts.model, "-s", &opts.scale.to_string(), "-f", &opts.format]);
+ cmd.arg("-i")
+ .arg(inp)
+ .arg("-o")
+ .arg(&out)
+ .arg("-m")
+ .arg(&models_dir);
+ cmd.args([
+ "-n",
+ &opts.model,
+ "-s",
+ &opts.scale.to_string(),
+ "-f",
+ &opts.format,
+ ]);
if opts.tile_size > 0 {
cmd.args(["-t", &opts.tile_size.to_string()]);
}
- cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped());
+ cmd.stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::piped());
let mut child = cmd.spawn()?;
let stderr = child.stderr.take();
let p2 = progress.clone();
@@ -159,7 +189,10 @@ pub async fn run(opts: UpscaleOptions, progress: super::ProgressFn) -> anyhow::R
let mut lines = BufReader::new(e).lines();
while let Ok(Some(line)) = lines.next_line().await {
let l = line.trim().to_string();
- if let Some(pct) = l.strip_suffix('%').and_then(|s| s.trim().parse::<f64>().ok()) {
+ if let Some(pct) = l
+ .strip_suffix('%')
+ .and_then(|s| s.trim().parse::<f64>().ok())
+ {
super::report(&p2, &id2, "progress", pct as u64, Some(100), None);
} else if !l.is_empty() {
tail = l;
diff --git a/src-tauri/omniget-core/src/core/tools/usage.rs b/src-tauri/omniget-core/src/core/tools/usage.rs
index e32d1e6d..4e5756d3 100644
--- a/src-tauri/omniget-core/src/core/tools/usage.rs
+++ b/src-tauri/omniget-core/src/core/tools/usage.rs
@@ -31,7 +31,14 @@ fn path() -> Option<PathBuf> {
}
/// Grava sem bloquear quem chamou; erro de disco vira só um log.
-pub fn record(task: &str, provider: &str, model: &str, input_tokens: u64, output_tokens: u64, cost_usd: Option<f64>) {
+pub fn record(
+ task: &str,
+ provider: &str,
+ model: &str,
+ input_tokens: u64,
+ output_tokens: u64,
+ cost_usd: Option<f64>,
+) {
let entry = UsageEntry {
ts: chrono::Utc::now().to_rfc3339(),
task: task.to_string(),
@@ -47,9 +54,15 @@ pub fn record(task: &str, provider: &str, model: &str, input_tokens: u64, output
if let Some(parent) = p.parent() {
let _ = std::fs::create_dir_all(parent);
}
- let Ok(line) = serde_json::to_string(&entry) else { return };
+ let Ok(line) = serde_json::to_string(&entry) else {
+ return;
+ };
use std::io::Write;
- match std::fs::OpenOptions::new().create(true).append(true).open(&p) {
+ match std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(&p)
+ {
Ok(mut f) => {
let _ = writeln!(f, "{}", line);
}
@@ -59,8 +72,12 @@ pub fn record(task: &str, provider: &str, model: &str, input_tokens: u64, output
pub fn read_all() -> Vec<UsageEntry> {
let Some(p) = path() else { return vec![] };
- let Ok(text) = std::fs::read_to_string(&p) else { return vec![] };
- text.lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
+ let Ok(text) = std::fs::read_to_string(&p) else {
+ return vec![];
+ };
+ text.lines()
+ .filter_map(|l| serde_json::from_str(l).ok())
+ .collect()
}
pub fn clear() -> anyhow::Result<()> {
@@ -100,13 +117,18 @@ pub async fn report(days: u32) -> UsageReport {
let since = chrono::Utc::now() - chrono::Duration::days(days.max(1) as i64);
let entries: Vec<UsageEntry> = read_all()
.into_iter()
- .filter(|e| chrono::DateTime::parse_from_rfc3339(&e.ts).map(|t| t.with_timezone(&chrono::Utc) >= since).unwrap_or(false))
+ .filter(|e| {
+ chrono::DateTime::parse_from_rfc3339(&e.ts)
+ .map(|t| t.with_timezone(&chrono::Utc) >= since)
+ .unwrap_or(false)
+ })
.collect();
let mut by_day: BTreeMap<String, Bucket> = BTreeMap::new();
let mut by_model: BTreeMap<String, Bucket> = BTreeMap::new();
let mut by_task: BTreeMap<String, Bucket> = BTreeMap::new();
let mut total = Bucket::default();
- let mut price_cache: std::collections::HashMap<String, Option<super::pricing::ModelPrice>> = Default::default();
+ let mut price_cache: std::collections::HashMap<String, Option<super::pricing::ModelPrice>> =
+ Default::default();
for e in &entries {
let cost = match e.cost_usd {
Some(c) => Some(c),
@@ -123,8 +145,15 @@ pub async fn report(days: u32) -> UsageReport {
}
};
let day = e.ts.get(..10).unwrap_or("").to_string();
- for (map, key) in [(&mut by_day, day), (&mut by_model, e.model.clone()), (&mut by_task, e.task.clone())] {
- let b = map.entry(key.clone()).or_insert_with(|| Bucket { key, ..Default::default() });
+ for (map, key) in [
+ (&mut by_day, day),
+ (&mut by_model, e.model.clone()),
+ (&mut by_task, e.task.clone()),
+ ] {
+ let b = map.entry(key.clone()).or_insert_with(|| Bucket {
+ key,
+ ..Default::default()
+ });
b.calls += 1;
b.input_tokens += e.input_tokens;
b.output_tokens += e.output_tokens;
@@ -142,7 +171,12 @@ pub async fn report(days: u32) -> UsageReport {
}
}
let mut by_model: Vec<Bucket> = by_model.into_values().collect();
- by_model.sort_by(|a, b| b.cost_usd.partial_cmp(&a.cost_usd).unwrap_or(std::cmp::Ordering::Equal).then(b.calls.cmp(&a.calls)));
+ by_model.sort_by(|a, b| {
+ b.cost_usd
+ .partial_cmp(&a.cost_usd)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ .then(b.calls.cmp(&a.calls))
+ });
UsageReport {
since: since.to_rfc3339(),
calls: total.calls,
diff --git a/src-tauri/omniget-core/src/core/tools/voicestudio.rs b/src-tauri/omniget-core/src/core/tools/voicestudio.rs
index daec9835..0ded242a 100644
--- a/src-tauri/omniget-core/src/core/tools/voicestudio.rs
+++ b/src-tauri/omniget-core/src/core/tools/voicestudio.rs
@@ -46,18 +46,35 @@ fn base(url: &str) -> String {
}
fn client(secs: u64) -> anyhow::Result<reqwest::Client> {
- Ok(reqwest::Client::builder().timeout(std::time::Duration::from_secs(secs)).no_proxy().build()?)
+ Ok(reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(secs))
+ .no_proxy()
+ .build()?)
}
fn find_app() -> Option<PathBuf> {
let candidates: Vec<PathBuf> = if cfg!(target_os = "macos") {
- vec![PathBuf::from("/Applications/VoiceStudio.app"), dirs::home_dir().unwrap_or_default().join("Applications/VoiceStudio.app")]
+ vec![
+ PathBuf::from("/Applications/VoiceStudio.app"),
+ dirs::home_dir()
+ .unwrap_or_default()
+ .join("Applications/VoiceStudio.app"),
+ ]
} else if cfg!(target_os = "windows") {
let mut v = Vec::new();
for var in ["LOCALAPPDATA", "ProgramFiles"] {
if let Ok(b) = std::env::var(var) {
- v.push(PathBuf::from(&b).join("VoiceStudio").join("VoiceStudio.exe"));
- v.push(PathBuf::from(&b).join("Programs").join("VoiceStudio").join("VoiceStudio.exe"));
+ v.push(
+ PathBuf::from(&b)
+ .join("VoiceStudio")
+ .join("VoiceStudio.exe"),
+ );
+ v.push(
+ PathBuf::from(&b)
+ .join("Programs")
+ .join("VoiceStudio")
+ .join("VoiceStudio.exe"),
+ );
}
}
v
@@ -65,8 +82,12 @@ fn find_app() -> Option<PathBuf> {
vec![
PathBuf::from("/usr/bin/voicestudio"),
PathBuf::from("/opt/VoiceStudio/voicestudio"),
- dirs::home_dir().unwrap_or_default().join("Applications/VoiceStudio.AppImage"),
- dirs::home_dir().unwrap_or_default().join(".local/bin/voicestudio"),
+ dirs::home_dir()
+ .unwrap_or_default()
+ .join("Applications/VoiceStudio.AppImage"),
+ dirs::home_dir()
+ .unwrap_or_default()
+ .join(".local/bin/voicestudio"),
]
};
candidates.into_iter().find(|p| p.exists())
@@ -75,7 +96,15 @@ fn find_app() -> Option<PathBuf> {
pub async fn status(base_url: &str) -> VsStatus {
let b = base(base_url);
let app = find_app();
- let mut s = VsStatus { base_url: b.clone(), running: false, installed: app.is_some(), app_path: app.map(|p| p.to_string_lossy().to_string()), version: None, engine: None, profiles: vec![] };
+ let mut s = VsStatus {
+ base_url: b.clone(),
+ running: false,
+ installed: app.is_some(),
+ app_path: app.map(|p| p.to_string_lossy().to_string()),
+ version: None,
+ engine: None,
+ profiles: vec![],
+ };
let Ok(c) = client(4) else { return s };
if let Ok(r) = c.get(format!("{}/health", b)).send().await {
if r.status().is_success() {
@@ -88,7 +117,11 @@ pub async fn status(base_url: &str) -> VsStatus {
if s.running {
if let Ok(r) = c.get(format!("{}/engines/tts", b)).send().await {
if let Ok(j) = r.json::<serde_json::Value>().await {
- s.engine = j.get("active").and_then(|v| v.as_str()).map(String::from).or_else(|| j.get("selected").and_then(|v| v.as_str()).map(String::from));
+ s.engine = j
+ .get("active")
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ .or_else(|| j.get("selected").and_then(|v| v.as_str()).map(String::from));
}
}
s.profiles = profiles(&b).await.unwrap_or_default();
@@ -98,17 +131,43 @@ pub async fn status(base_url: &str) -> VsStatus {
pub async fn profiles(base_url: &str) -> anyhow::Result<Vec<Profile>> {
let c = client(10)?;
- let j: serde_json::Value = c.get(format!("{}/profiles", base(base_url))).send().await?.error_for_status()?.json().await?;
- let arr = j.as_array().cloned().or_else(|| j.get("profiles").and_then(|v| v.as_array()).cloned()).unwrap_or_default();
+ let j: serde_json::Value = c
+ .get(format!("{}/profiles", base(base_url)))
+ .send()
+ .await?
+ .error_for_status()?
+ .json()
+ .await?;
+ let arr = j
+ .as_array()
+ .cloned()
+ .or_else(|| j.get("profiles").and_then(|v| v.as_array()).cloned())
+ .unwrap_or_default();
Ok(arr
.iter()
.filter_map(|p| {
Some(Profile {
id: p.get("id")?.as_str()?.to_string(),
- name: p.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string(),
- kind: p.get("kind").and_then(|v| v.as_str()).unwrap_or("clone").to_string(),
- language: p.get("language").and_then(|v| v.as_str()).unwrap_or("").to_string(),
- instruct: p.get("instruct").and_then(|v| v.as_str()).unwrap_or("").to_string(),
+ name: p
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string(),
+ kind: p
+ .get("kind")
+ .and_then(|v| v.as_str())
+ .unwrap_or("clone")
+ .to_string(),
+ language: p
+ .get("language")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string(),
+ instruct: p
+ .get("instruct")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string(),
})
})
.collect())
@@ -118,7 +177,10 @@ pub async fn profiles(base_url: &str) -> anyhow::Result<Vec<Profile>> {
pub async fn launch() -> anyhow::Result<()> {
let app = find_app().ok_or_else(|| anyhow!("VoiceStudio nao encontrado"))?;
if cfg!(target_os = "macos") {
- crate::core::process::command("open").arg(&app).output().await?;
+ crate::core::process::command("open")
+ .arg(&app)
+ .output()
+ .await?;
} else {
crate::core::process::command(&app).spawn()?;
}
@@ -129,7 +191,11 @@ async fn wav_from(resp: reqwest::Response, output: &Path) -> anyhow::Result<Path
let status = resp.status();
if !status.is_success() {
let text = resp.text().await.unwrap_or_default();
- return Err(anyhow!("VoiceStudio HTTP {}: {}", status.as_u16(), text.chars().take(300).collect::<String>()));
+ return Err(anyhow!(
+ "VoiceStudio HTTP {}: {}",
+ status.as_u16(),
+ text.chars().take(300).collect::<String>()
+ ));
}
let bytes = resp.bytes().await?;
if bytes.len() < 100 {
@@ -147,7 +213,14 @@ fn stamp() -> String {
}
fn out_path(output_dir: &str, name: &str) -> PathBuf {
- let dir = if output_dir.trim().is_empty() { dirs::audio_dir().or_else(dirs::home_dir).unwrap_or_default().join("OmniGet") } else { PathBuf::from(output_dir.trim()) };
+ let dir = if output_dir.trim().is_empty() {
+ dirs::audio_dir()
+ .or_else(dirs::home_dir)
+ .unwrap_or_default()
+ .join("OmniGet")
+ } else {
+ PathBuf::from(output_dir.trim())
+ };
dir.join(format!("{} {}.wav", name, stamp()))
}
@@ -188,25 +261,67 @@ pub struct SpeechResult {
}
/// Clona a voz da amostra (ou usa o perfil) e fala o texto.
-pub async fn clone_speak(opts: CloneOptions, progress: super::ProgressFn) -> anyhow::Result<SpeechResult> {
+pub async fn clone_speak(
+ opts: CloneOptions,
+ progress: super::ProgressFn,
+) -> anyhow::Result<SpeechResult> {
let b = base(&opts.base_url);
let c = client(900)?;
- let mut profile_id = if opts.profile_id.trim().is_empty() { None } else { Some(opts.profile_id.trim().to_string()) };
+ let mut profile_id = if opts.profile_id.trim().is_empty() {
+ None
+ } else {
+ Some(opts.profile_id.trim().to_string())
+ };
if profile_id.is_none() && !opts.save_as.trim().is_empty() {
- super::report(&progress, "voicestudio", "profile", 0, None, Some(opts.save_as.clone()));
+ super::report(
+ &progress,
+ "voicestudio",
+ "profile",
+ 0,
+ None,
+ Some(opts.save_as.clone()),
+ );
let sample = std::fs::read(&opts.sample).map_err(|e| anyhow!("amostra: {}", e))?;
- let file_name = Path::new(&opts.sample).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "sample.wav".into());
+ let file_name = Path::new(&opts.sample)
+ .file_name()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| "sample.wav".into());
let form = reqwest::multipart::Form::new()
.text("name", opts.save_as.trim().to_string())
.text("kind", "clone")
.text("ref_text", opts.sample_text.clone())
- .text("language", if opts.language.is_empty() { "Auto".to_string() } else { opts.language.clone() })
- .part("ref_audio", reqwest::multipart::Part::bytes(sample).file_name(file_name));
- let j: serde_json::Value = c.post(format!("{}/profiles", b)).multipart(form).send().await?.error_for_status().map_err(|e| anyhow!("criar perfil: {}", e))?.json().await?;
- profile_id = j.get("id").or_else(|| j.get("profile_id")).and_then(|v| v.as_str()).map(String::from);
+ .text(
+ "language",
+ if opts.language.is_empty() {
+ "Auto".to_string()
+ } else {
+ opts.language.clone()
+ },
+ )
+ .part(
+ "ref_audio",
+ reqwest::multipart::Part::bytes(sample).file_name(file_name),
+ );
+ let j: serde_json::Value = c
+ .post(format!("{}/profiles", b))
+ .multipart(form)
+ .send()
+ .await?
+ .error_for_status()
+ .map_err(|e| anyhow!("criar perfil: {}", e))?
+ .json()
+ .await?;
+ profile_id = j
+ .get("id")
+ .or_else(|| j.get("profile_id"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
}
super::report(&progress, "voicestudio", "generate", 0, None, None);
- let mut form = reqwest::multipart::Form::new().text("text", opts.text.clone()).text("speed", opts.speed.to_string()).text("stream", "false");
+ let mut form = reqwest::multipart::Form::new()
+ .text("text", opts.text.clone())
+ .text("speed", opts.speed.to_string())
+ .text("stream", "false");
if !opts.language.is_empty() {
form = form.text("language", opts.language.clone());
}
@@ -214,17 +329,35 @@ pub async fn clone_speak(opts: CloneOptions, progress: super::ProgressFn) -> any
form = form.text("profile_id", pid.clone());
} else {
let sample = std::fs::read(&opts.sample).map_err(|e| anyhow!("amostra: {}", e))?;
- let file_name = Path::new(&opts.sample).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "sample.wav".into());
- form = form.part("ref_audio", reqwest::multipart::Part::bytes(sample).file_name(file_name));
+ let file_name = Path::new(&opts.sample)
+ .file_name()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| "sample.wav".into());
+ form = form.part(
+ "ref_audio",
+ reqwest::multipart::Part::bytes(sample).file_name(file_name),
+ );
if !opts.sample_text.trim().is_empty() {
form = form.text("ref_text", opts.sample_text.clone());
}
}
- let resp = c.post(format!("{}/generate", b)).multipart(form).send().await?;
- let seconds = resp.headers().get("x-audio-duration").and_then(|v| v.to_str().ok()).and_then(|s| s.parse::<f64>().ok());
+ let resp = c
+ .post(format!("{}/generate", b))
+ .multipart(form)
+ .send()
+ .await?;
+ let seconds = resp
+ .headers()
+ .get("x-audio-duration")
+ .and_then(|v| v.to_str().ok())
+ .and_then(|s| s.parse::<f64>().ok());
let out = wav_from(resp, &out_path(&opts.output_dir, "Voz clonada")).await?;
super::report(&progress, "voicestudio", "done", 1, Some(1), None);
- Ok(SpeechResult { output: out.to_string_lossy().to_string(), profile_id, seconds })
+ Ok(SpeechResult {
+ output: out.to_string_lossy().to_string(),
+ profile_id,
+ seconds,
+ })
}
#[derive(Debug, Clone, Deserialize)]
@@ -252,7 +385,10 @@ pub struct DesignResult {
}
/// Descrição em texto → atributos → voz nova falando o texto.
-pub async fn design_speak(opts: DesignOptions, progress: super::ProgressFn) -> anyhow::Result<DesignResult> {
+pub async fn design_speak(
+ opts: DesignOptions,
+ progress: super::ProgressFn,
+) -> anyhow::Result<DesignResult> {
let b = base(&opts.base_url);
let c = client(900)?;
super::report(&progress, "voicestudio", "describe", 0, None, None);
@@ -265,9 +401,29 @@ pub async fn design_speak(opts: DesignOptions, progress: super::ProgressFn) -> a
.map_err(|e| anyhow!("describe: {}", e))?
.json()
.await?;
- let instruct = j.get("instruct").and_then(|v| v.as_str()).unwrap_or("").to_string();
- let matched: Vec<String> = j.get("matched").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|m| m.get("phrase").and_then(|p| p.as_str()).map(String::from)).collect()).unwrap_or_default();
- let unmatched: Vec<String> = j.get("unmatched").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|m| m.as_str().map(String::from)).collect()).unwrap_or_default();
+ let instruct = j
+ .get("instruct")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ let matched: Vec<String> = j
+ .get("matched")
+ .and_then(|v| v.as_array())
+ .map(|a| {
+ a.iter()
+ .filter_map(|m| m.get("phrase").and_then(|p| p.as_str()).map(String::from))
+ .collect()
+ })
+ .unwrap_or_default();
+ let unmatched: Vec<String> = j
+ .get("unmatched")
+ .and_then(|v| v.as_array())
+ .map(|a| {
+ a.iter()
+ .filter_map(|m| m.as_str().map(String::from))
+ .collect()
+ })
+ .unwrap_or_default();
let mut profile_id = None;
if !opts.save_as.trim().is_empty() {
let attrs = j.get("attrs").cloned().unwrap_or(serde_json::json!({}));
@@ -276,40 +432,91 @@ pub async fn design_speak(opts: DesignOptions, progress: super::ProgressFn) -> a
.text("kind", "design")
.text("instruct", instruct.clone())
.text("vd_states", attrs.to_string())
- .text("language", if opts.language.is_empty() { "Auto".to_string() } else { opts.language.clone() });
- if let Ok(r) = c.post(format!("{}/profiles", b)).multipart(form).send().await {
+ .text(
+ "language",
+ if opts.language.is_empty() {
+ "Auto".to_string()
+ } else {
+ opts.language.clone()
+ },
+ );
+ if let Ok(r) = c
+ .post(format!("{}/profiles", b))
+ .multipart(form)
+ .send()
+ .await
+ {
if let Ok(pj) = r.json::<serde_json::Value>().await {
profile_id = pj.get("id").and_then(|v| v.as_str()).map(String::from);
}
}
}
super::report(&progress, "voicestudio", "generate", 0, None, None);
- let mut form = reqwest::multipart::Form::new().text("text", opts.text.clone()).text("instruct", instruct.clone()).text("stream", "false");
+ let mut form = reqwest::multipart::Form::new()
+ .text("text", opts.text.clone())
+ .text("instruct", instruct.clone())
+ .text("stream", "false");
if !opts.language.is_empty() {
form = form.text("language", opts.language.clone());
}
if let Some(pid) = &profile_id {
form = form.text("profile_id", pid.clone());
}
- let resp = c.post(format!("{}/generate", b)).multipart(form).send().await?;
+ let resp = c
+ .post(format!("{}/generate", b))
+ .multipart(form)
+ .send()
+ .await?;
let out = wav_from(resp, &out_path(&opts.output_dir, "Voz criada")).await?;
super::report(&progress, "voicestudio", "done", 1, Some(1), None);
- Ok(DesignResult { output: out.to_string_lossy().to_string(), instruct, matched, unmatched, profile_id })
+ Ok(DesignResult {
+ output: out.to_string_lossy().to_string(),
+ instruct,
+ matched,
+ unmatched,
+ profile_id,
+ })
}
/// Demucs no VoiceStudio: devolve só a voz. O instrumental é a diferença,
/// feita aqui com o FFmpeg (voz invertida somada ao original).
-pub async fn isolate(base_url: &str, input: &str, output_dir: &str, instrumental: bool, progress: super::ProgressFn) -> anyhow::Result<Vec<String>> {
+pub async fn isolate(
+ base_url: &str,
+ input: &str,
+ output_dir: &str,
+ instrumental: bool,
+ progress: super::ProgressFn,
+) -> anyhow::Result<Vec<String>> {
let b = base(base_url);
let c = client(1800)?;
super::report(&progress, "voicestudio", "upload", 0, None, None);
let data = std::fs::read(input).map_err(|e| anyhow!("entrada: {}", e))?;
- let file_name = Path::new(input).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "audio.wav".into());
- let form = reqwest::multipart::Form::new().part("audio", reqwest::multipart::Part::bytes(data).file_name(file_name));
+ let file_name = Path::new(input)
+ .file_name()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| "audio.wav".into());
+ let form = reqwest::multipart::Form::new().part(
+ "audio",
+ reqwest::multipart::Part::bytes(data).file_name(file_name),
+ );
super::report(&progress, "voicestudio", "separate", 0, None, None);
- let resp = c.post(format!("{}/clean-audio", b)).multipart(form).send().await?;
- let stem = Path::new(input).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "audio".into());
- let dir = if output_dir.trim().is_empty() { Path::new(input).parent().map(Path::to_path_buf).unwrap_or_default() } else { PathBuf::from(output_dir.trim()) };
+ let resp = c
+ .post(format!("{}/clean-audio", b))
+ .multipart(form)
+ .send()
+ .await?;
+ let stem = Path::new(input)
+ .file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| "audio".into());
+ let dir = if output_dir.trim().is_empty() {
+ Path::new(input)
+ .parent()
+ .map(Path::to_path_buf)
+ .unwrap_or_default()
+ } else {
+ PathBuf::from(output_dir.trim())
+ };
std::fs::create_dir_all(&dir)?;
let vocals = dir.join(format!("{} (voz).wav", stem));
wav_from(resp, &vocals).await?;
diff --git a/src-tauri/omniget-core/src/core/tools/whisper.rs b/src-tauri/omniget-core/src/core/tools/whisper.rs
index 99f6ca49..0f8b29e8 100644
--- a/src-tauri/omniget-core/src/core/tools/whisper.rs
+++ b/src-tauri/omniget-core/src/core/tools/whisper.rs
@@ -35,7 +35,11 @@ const MODELS: &[(&str, u64, &str)] = &[
("base-q5_1", 60, "rápido, qualidade básica"),
("small-q5_1", 190, "equilíbrio para máquinas fracas"),
("medium-q5_0", 540, "boa qualidade, mais lento"),
- ("large-v3-turbo-q5_0", 574, "recomendado: quase large-v3, 8× mais rápido"),
+ (
+ "large-v3-turbo-q5_0",
+ 574,
+ "recomendado: quase large-v3, 8× mais rápido",
+ ),
("large-v3-turbo", 1620, "turbo sem quantização"),
("large-v3-q5_0", 1080, "melhor qualidade quantizado"),
("large-v3", 3100, "melhor qualidade, mais pesado"),
@@ -62,11 +66,16 @@ pub fn list_models() -> Vec<ModelInfo> {
.unwrap_or(0);
ModelInfo {
id: id.to_string(),
- label: id.replace('-', " ").replace("q5_0", "(q5)").replace("q5_1", "(q5)"),
+ label: id
+ .replace('-', " ")
+ .replace("q5_0", "(q5)")
+ .replace("q5_1", "(q5)"),
size_mb: *mb,
note: note.to_string(),
installed: size > 0,
- path: path.filter(|_| size > 0).map(|p| p.to_string_lossy().to_string()),
+ path: path
+ .filter(|_| size > 0)
+ .map(|p| p.to_string_lossy().to_string()),
size_bytes: size,
}
})
@@ -82,7 +91,14 @@ pub async fn download_model(id: &str, progress: ProgressFn) -> anyhow::Result<Pa
let dest = dir.join(format!("ggml-{}.bin", id));
let url = format!("{}/ggml-{}.bin", HF_BASE, id);
let client = super::client()?;
- super::download_to(&client, &url, &dest, &progress, &format!("whisper-model:{}", id)).await?;
+ super::download_to(
+ &client,
+ &url,
+ &dest,
+ &progress,
+ &format!("whisper-model:{}", id),
+ )
+ .await?;
Ok(dest)
}
@@ -133,7 +149,9 @@ pub async fn locate() -> Option<(PathBuf, &'static str)> {
fn variants() -> Vec<String> {
if cfg!(target_os = "windows") && cfg!(target_arch = "x86_64") {
vec!["cpu".into(), "cuda".into()]
- } else if cfg!(target_os = "linux") && (cfg!(target_arch = "x86_64") || cfg!(target_arch = "aarch64")) {
+ } else if cfg!(target_os = "linux")
+ && (cfg!(target_arch = "x86_64") || cfg!(target_arch = "aarch64"))
+ {
vec!["cpu".into()]
} else {
vec![]
@@ -269,7 +287,10 @@ async fn to_wav16k(input: &Path) -> anyhow::Result<PathBuf> {
fn parse_whisper_json(text: &str) -> anyhow::Result<(String, Vec<Cue>)> {
let json: serde_json::Value = serde_json::from_str(text)?;
- let language = json["result"]["language"].as_str().unwrap_or("").to_string();
+ let language = json["result"]["language"]
+ .as_str()
+ .unwrap_or("")
+ .to_string();
let mut cues = Vec::new();
if let Some(items) = json["transcription"].as_array() {
for it in items {
@@ -279,14 +300,23 @@ fn parse_whisper_json(text: &str) -> anyhow::Result<(String, Vec<Cue>)> {
if t.is_empty() {
continue;
}
- cues.push(Cue { start_ms: from, end_ms: to.max(from + 1), text: t });
+ cues.push(Cue {
+ start_ms: from,
+ end_ms: to.max(from + 1),
+ text: t,
+ });
}
}
Ok((language, cues))
}
-pub async fn transcribe(opts: TranscribeOptions, progress: ProgressFn) -> anyhow::Result<TranscribeResult> {
- let (bin, _) = locate().await.ok_or_else(|| anyhow!("whisper-cli nao esta instalado"))?;
+pub async fn transcribe(
+ opts: TranscribeOptions,
+ progress: ProgressFn,
+) -> anyhow::Result<TranscribeResult> {
+ let (bin, _) = locate()
+ .await
+ .ok_or_else(|| anyhow!("whisper-cli nao esta instalado"))?;
let model_path = models_dir()
.ok_or_else(|| anyhow!("Could not determine data directory"))?
.join(format!("ggml-{}.bin", opts.model));
@@ -306,7 +336,11 @@ pub async fn transcribe(opts: TranscribeOptions, progress: ProgressFn) -> anyhow
let mut cmd = crate::core::process::command(&bin);
cmd.arg("-m").arg(&model_path).arg("-f").arg(&wav);
cmd.args(["-oj", "-pp", "-np", "-of"]).arg(&out_prefix);
- let lang = if opts.language.trim().is_empty() { "auto" } else { opts.language.trim() };
+ let lang = if opts.language.trim().is_empty() {
+ "auto"
+ } else {
+ opts.language.trim()
+ };
cmd.args(["-l", lang]);
if opts.translate {
cmd.arg("-tr");
@@ -323,7 +357,9 @@ pub async fn transcribe(opts: TranscribeOptions, progress: ProgressFn) -> anyhow
cmd.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
- let mut child = cmd.spawn().map_err(|e| anyhow!("nao foi possivel iniciar o whisper-cli: {}", e))?;
+ let mut child = cmd
+ .spawn()
+ .map_err(|e| anyhow!("nao foi possivel iniciar o whisper-cli: {}", e))?;
// `-pp` escreve "progress = 42%" no stderr.
let stderr = child.stderr.take();
@@ -358,16 +394,26 @@ pub async fn transcribe(opts: TranscribeOptions, progress: ProgressFn) -> anyhow
let (language, cues) = parse_whisper_json(&text)?;
let out_dir = if opts.output_dir.trim().is_empty() {
- input.parent().map(|p| p.to_path_buf()).unwrap_or_else(|| PathBuf::from("."))
+ input
+ .parent()
+ .map(|p| p.to_path_buf())
+ .unwrap_or_else(|| PathBuf::from("."))
} else {
PathBuf::from(opts.output_dir.trim())
};
std::fs::create_dir_all(&out_dir)?;
- let stem = input.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "transcricao".into());
+ let stem = input
+ .file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| "transcricao".into());
let srt_path = out_dir.join(format!("{}.srt", stem));
let vtt_path = out_dir.join(format!("{}.vtt", stem));
let txt_path = out_dir.join(format!("{}.txt", stem));
- let plain = cues.iter().map(|c| c.text.as_str()).collect::<Vec<_>>().join("\n");
+ let plain = cues
+ .iter()
+ .map(|c| c.text.as_str())
+ .collect::<Vec<_>>()
+ .join("\n");
tokio::fs::write(&srt_path, cues_to_srt(&cues)).await?;
tokio::fs::write(&vtt_path, cues_to_vtt(&cues)).await?;
tokio::fs::write(&txt_path, &plain).await?;
diff --git a/src-tauri/omniget-core/src/core/tools/win_apps.rs b/src-tauri/omniget-core/src/core/tools/win_apps.rs
index aa22484a..0faf451a 100644
--- a/src-tauri/omniget-core/src/core/tools/win_apps.rs
+++ b/src-tauri/omniget-core/src/core/tools/win_apps.rs
@@ -29,7 +29,10 @@ const BLOAT: &[(&str, &str)] = &[
("Microsoft.GetHelp", "Obter Ajuda"),
("Microsoft.Getstarted", "Dicas"),
("Microsoft.MicrosoftOfficeHub", "Office Hub"),
- ("Microsoft.MicrosoftSolitaireCollection", "Solitaire Collection"),
+ (
+ "Microsoft.MicrosoftSolitaireCollection",
+ "Solitaire Collection",
+ ),
("Microsoft.People", "Pessoas"),
("Microsoft.PowerAutomateDesktop", "Power Automate"),
("Microsoft.Todos", "To Do"),
@@ -63,7 +66,10 @@ const BLOAT: &[(&str, &str)] = &[
("Microsoft.WindowsCommunicationsApps", "Mail e Calendário"),
("Microsoft.OneDriveSync", "OneDrive (Store)"),
("Microsoft.QuickAssist", "Assistência Rápida"),
- ("Microsoft.Windows.NarratorQuickStart", "Narrador (tutorial)"),
+ (
+ "Microsoft.Windows.NarratorQuickStart",
+ "Narrador (tutorial)",
+ ),
("MicrosoftCorporationII.QuickAssist", "Assistência Rápida"),
("MicrosoftCorporationII.MicrosoftFamily", "Microsoft Family"),
("MicrosoftWindows.CrossDevice", "Cross Device"),
@@ -154,13 +160,29 @@ fn is_protected(name: &str) -> bool {
}
fn suggestion(name: &str) -> Option<&'static str> {
- BLOAT.iter().find(|(prefix, _)| name.starts_with(prefix)).map(|(_, label)| *label)
+ BLOAT
+ .iter()
+ .find(|(prefix, _)| name.starts_with(prefix))
+ .map(|(_, label)| *label)
}
async fn powershell(script: &str) -> anyhow::Result<String> {
- let o = crate::core::process::command("powershell").args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script]).output().await?;
+ let o = crate::core::process::command("powershell")
+ .args([
+ "-NoProfile",
+ "-NonInteractive",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-Command",
+ script,
+ ])
+ .output()
+ .await?;
if !o.status.success() {
- return Err(anyhow!("PowerShell: {}", String::from_utf8_lossy(&o.stderr).trim()));
+ return Err(anyhow!(
+ "PowerShell: {}",
+ String::from_utf8_lossy(&o.stderr).trim()
+ ));
}
Ok(String::from_utf8_lossy(&o.stdout).to_string())
}
@@ -170,7 +192,8 @@ pub async fn list() -> anyhow::Result<Vec<AppxPackage>> {
return Ok(vec![]);
}
let out = powershell("Get-AppxPackage | Where-Object { -not $_.IsFramework -and -not $_.IsResourcePackage } | Select-Object Name,PackageFullName,Version,Publisher,NonRemovable | ConvertTo-Json -Compress").await?;
- let json: serde_json::Value = serde_json::from_str(out.trim()).unwrap_or(serde_json::Value::Null);
+ let json: serde_json::Value =
+ serde_json::from_str(out.trim()).unwrap_or(serde_json::Value::Null);
let items: Vec<serde_json::Value> = match json {
serde_json::Value::Array(a) => a,
serde_json::Value::Object(_) => vec![json],
@@ -178,22 +201,55 @@ pub async fn list() -> anyhow::Result<Vec<AppxPackage>> {
};
let mut pkgs = Vec::new();
for it in items {
- let name = it.get("Name").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ let name = it
+ .get("Name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
if name.is_empty() || is_protected(&name) {
continue;
}
let sug = suggestion(&name);
pkgs.push(AppxPackage {
- label: sug.map(String::from).unwrap_or_else(|| name.rsplit('.').next().unwrap_or(&name).to_string()),
+ label: sug
+ .map(String::from)
+ .unwrap_or_else(|| name.rsplit('.').next().unwrap_or(&name).to_string()),
suggested: sug.is_some(),
- full_name: it.get("PackageFullName").and_then(|v| v.as_str()).unwrap_or("").to_string(),
- version: it.get("Version").and_then(|v| v.as_str()).unwrap_or("").to_string(),
- publisher: it.get("Publisher").and_then(|v| v.as_str()).map(|p| p.split("O=").nth(1).unwrap_or(p).split(',').next().unwrap_or(p).to_string()).unwrap_or_default(),
- non_removable: it.get("NonRemovable").and_then(|v| v.as_bool()).unwrap_or(false),
+ full_name: it
+ .get("PackageFullName")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string(),
+ version: it
+ .get("Version")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string(),
+ publisher: it
+ .get("Publisher")
+ .and_then(|v| v.as_str())
+ .map(|p| {
+ p.split("O=")
+ .nth(1)
+ .unwrap_or(p)
+ .split(',')
+ .next()
+ .unwrap_or(p)
+ .to_string()
+ })
+ .unwrap_or_default(),
+ non_removable: it
+ .get("NonRemovable")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false),
name,
});
}
- pkgs.sort_by(|a, b| b.suggested.cmp(&a.suggested).then(a.label.to_lowercase().cmp(&b.label.to_lowercase())));
+ pkgs.sort_by(|a, b| {
+ b.suggested
+ .cmp(&a.suggested)
+ .then(a.label.to_lowercase().cmp(&b.label.to_lowercase()))
+ });
Ok(pkgs)
}
@@ -205,17 +261,31 @@ pub struct RemoveResult {
/// Remove os pacotes do usuário atual; com `provisioned`, também impede que
/// voltem para contas novas (precisa de administrador).
-pub async fn remove(names: &[String], provisioned: bool, progress: &super::ProgressFn) -> RemoveResult {
+pub async fn remove(
+ names: &[String],
+ provisioned: bool,
+ progress: &super::ProgressFn,
+) -> RemoveResult {
let mut r = RemoveResult::default();
let total = names.len() as u64;
for (i, name) in names.iter().enumerate() {
- super::report(progress, "debloat", "progress", i as u64, Some(total), Some(name.clone()));
+ super::report(
+ progress,
+ "debloat",
+ "progress",
+ i as u64,
+ Some(total),
+ Some(name.clone()),
+ );
if is_protected(name) {
r.failed.push(format!("{}: protegido", name));
continue;
}
let safe = name.replace('\'', "");
- let mut script = format!("Get-AppxPackage -Name '{}' | Remove-AppxPackage -ErrorAction Stop", safe);
+ let mut script = format!(
+ "Get-AppxPackage -Name '{}' | Remove-AppxPackage -ErrorAction Stop",
+ safe
+ );
if provisioned {
script.push_str(&format!("; Get-AppxProvisionedPackage -Online | Where-Object {{ $_.DisplayName -eq '{}' }} | Remove-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue | Out-Null", safe));
}
@@ -249,7 +319,10 @@ mod tests {
assert!(is_protected("Microsoft.WindowsStore"));
assert!(is_protected("Microsoft.VCLibs.140.00"));
assert!(!is_protected("Microsoft.BingNews"));
- assert_eq!(suggestion("Microsoft.XboxGamingOverlay"), Some("Xbox Game Bar"));
+ assert_eq!(
+ suggestion("Microsoft.XboxGamingOverlay"),
+ Some("Xbox Game Bar")
+ );
assert_eq!(suggestion("king.com.CandyCrushSaga"), Some("Candy Crush"));
assert!(suggestion("Contoso.App").is_none());
}
diff --git a/src-tauri/omniget-core/src/core/tools/win_registry.rs b/src-tauri/omniget-core/src/core/tools/win_registry.rs
index 9171dafe..4853fdad 100644
--- a/src-tauri/omniget-core/src/core/tools/win_registry.rs
+++ b/src-tauri/omniget-core/src/core/tools/win_registry.rs
@@ -37,13 +37,19 @@ pub fn parse_reg_output(text: &str) -> Vec<RegKey> {
if !raw.starts_with(' ') && (line.starts_with("HKEY_") || line.starts_with("HK")) {
// Subchave da chave anterior ou chave nova?
if let Some(last) = keys.last_mut() {
- if line.starts_with(&last.path) && line.len() > last.path.len() && line[last.path.len()..].starts_with('\\') {
+ if line.starts_with(&last.path)
+ && line.len() > last.path.len()
+ && line[last.path.len()..].starts_with('\\')
+ {
last.subkeys.push(line.to_string());
// A própria subchave também pode listar valores a seguir
// quando o /s foi usado; abre como chave.
}
}
- keys.push(RegKey { path: line.to_string(), ..Default::default() });
+ keys.push(RegKey {
+ path: line.to_string(),
+ ..Default::default()
+ });
continue;
}
let Some(key) = keys.last_mut() else { continue };
@@ -53,10 +59,21 @@ pub fn parse_reg_output(text: &str) -> Vec<RegKey> {
let name = t[..idx].trim().to_string();
let rest = t[idx + 4..].trim_start();
let (kind, data) = match rest.find(" ") {
- Some(i) => (rest[..i].trim().to_string(), rest[i + 4..].trim().to_string()),
+ Some(i) => (
+ rest[..i].trim().to_string(),
+ rest[i + 4..].trim().to_string(),
+ ),
None => (rest.trim().to_string(), String::new()),
};
- key.values.push(RegValue { name: if name == "(Default)" || name == "(Padrão)" { String::new() } else { name }, kind, data });
+ key.values.push(RegValue {
+ name: if name == "(Default)" || name == "(Padrão)" {
+ String::new()
+ } else {
+ name
+ },
+ kind,
+ data,
+ });
}
}
keys
@@ -92,7 +109,10 @@ pub async fn reg_delete(key: &str, value: Option<&str>) -> anyhow::Result<()> {
cmd.arg("/f");
let o = cmd.output().await?;
if !o.status.success() {
- return Err(anyhow!("reg delete falhou: {}", String::from_utf8_lossy(&o.stderr).trim()));
+ return Err(anyhow!(
+ "reg delete falhou: {}",
+ String::from_utf8_lossy(&o.stderr).trim()
+ ));
}
Ok(())
}
@@ -108,7 +128,10 @@ pub async fn reg_add(key: &str, value: &str, kind: &str, data: &str) -> anyhow::
cmd.arg("/t").arg(kind).arg("/d").arg(data).arg("/f");
let o = cmd.output().await?;
if !o.status.success() {
- return Err(anyhow!("reg add falhou: {}", String::from_utf8_lossy(&o.stderr).trim()));
+ return Err(anyhow!(
+ "reg add falhou: {}",
+ String::from_utf8_lossy(&o.stderr).trim()
+ ));
}
Ok(())
}
@@ -121,11 +144,27 @@ pub fn backups_dir() -> Option<PathBuf> {
pub async fn reg_backup(key: &str) -> anyhow::Result<PathBuf> {
let dir = backups_dir().ok_or_else(|| anyhow!("sem pasta de dados"))?;
std::fs::create_dir_all(&dir)?;
- let safe: String = key.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
- let file = dir.join(format!("{}-{}.reg", chrono::Local::now().format("%Y%m%d-%H%M%S"), safe.chars().take(80).collect::<String>()));
- let o = crate::core::process::command("reg").arg("export").arg(key).arg(&file).arg("/y").output().await?;
+ let safe: String = key
+ .chars()
+ .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
+ .collect();
+ let file = dir.join(format!(
+ "{}-{}.reg",
+ chrono::Local::now().format("%Y%m%d-%H%M%S"),
+ safe.chars().take(80).collect::<String>()
+ ));
+ let o = crate::core::process::command("reg")
+ .arg("export")
+ .arg(key)
+ .arg(&file)
+ .arg("/y")
+ .output()
+ .await?;
if !o.status.success() {
- return Err(anyhow!("reg export falhou: {}", String::from_utf8_lossy(&o.stderr).trim()));
+ return Err(anyhow!(
+ "reg export falhou: {}",
+ String::from_utf8_lossy(&o.stderr).trim()
+ ));
}
Ok(file)
}
@@ -227,7 +266,10 @@ const RUN_KEYS: &[&str] = &[
];
fn value_of<'a>(key: &'a RegKey, name: &str) -> Option<&'a str> {
- key.values.iter().find(|v| v.name.eq_ignore_ascii_case(name)).map(|v| v.data.as_str())
+ key.values
+ .iter()
+ .find(|v| v.name.eq_ignore_ascii_case(name))
+ .map(|v| v.data.as_str())
}
pub async fn scan(progress: &super::ProgressFn) -> Vec<Orphan> {
@@ -242,30 +284,55 @@ pub async fn scan(progress: &super::ProgressFn) -> Vec<Orphan> {
};
// 1) Programas desinstalados que deixaram a entrada
- super::report(progress, "winreg", "progress", 0, Some(5), Some("Uninstall".into()));
+ super::report(
+ progress,
+ "winreg",
+ "progress",
+ 0,
+ Some(5),
+ Some("Uninstall".into()),
+ );
for root in UNINSTALL_KEYS {
for key in reg_query(root, true).await {
if key.path.eq_ignore_ascii_case(root) {
continue;
}
- let Some(name) = value_of(&key, "DisplayName") else { continue };
+ let Some(name) = value_of(&key, "DisplayName") else {
+ continue;
+ };
if value_of(&key, "SystemComponent") == Some("0x1") {
continue;
}
- let loc = value_of(&key, "InstallLocation").map(expand_env).unwrap_or_default();
+ let loc = value_of(&key, "InstallLocation")
+ .map(expand_env)
+ .unwrap_or_default();
let unins = value_of(&key, "UninstallString").and_then(command_exe);
let icon = value_of(&key, "DisplayIcon").and_then(command_exe);
- let loc_missing = !loc.trim().is_empty() && !Path::new(loc.trim().trim_matches('"')).exists();
- let unins_missing = unins.as_ref().map(|p| exe_missing(p) && !p.to_string_lossy().to_ascii_lowercase().contains("msiexec")).unwrap_or(false);
+ let loc_missing =
+ !loc.trim().is_empty() && !Path::new(loc.trim().trim_matches('"')).exists();
+ let unins_missing = unins
+ .as_ref()
+ .map(|p| {
+ exe_missing(p) && !p.to_string_lossy().to_ascii_lowercase().contains("msiexec")
+ })
+ .unwrap_or(false);
let icon_missing = icon.as_ref().map(|p| exe_missing(p)).unwrap_or(false);
- if (loc_missing && (unins_missing || icon_missing || unins.is_none())) || (unins_missing && loc.trim().is_empty()) {
+ if (loc_missing && (unins_missing || icon_missing || unins.is_none()))
+ || (unins_missing && loc.trim().is_empty())
+ {
push(Orphan {
id: format!("u:{}", key.path),
category: "uninstall".into(),
key: key.path.clone(),
value: None,
name: name.to_string(),
- data: if loc.is_empty() { unins.map(|p| p.to_string_lossy().to_string()).unwrap_or_default() } else { loc },
+ data: if loc.is_empty() {
+ unins
+ .map(|p| p.to_string_lossy().to_string())
+ .unwrap_or_default()
+ } else {
+ loc
+ },
reason: "pasta e desinstalador nao existem mais".into(),
});
}
@@ -273,13 +340,22 @@ pub async fn scan(progress: &super::ProgressFn) -> Vec<Orphan> {
}
// 2) App Paths apontando para exe inexistente
- super::report(progress, "winreg", "progress", 1, Some(5), Some("App Paths".into()));
+ super::report(
+ progress,
+ "winreg",
+ "progress",
+ 1,
+ Some(5),
+ Some("App Paths".into()),
+ );
for root in APP_PATH_KEYS {
for key in reg_query(root, true).await {
if key.path.eq_ignore_ascii_case(root) {
continue;
}
- let Some(target) = value_of(&key, "") else { continue };
+ let Some(target) = value_of(&key, "") else {
+ continue;
+ };
if let Some(p) = command_exe(target) {
if exe_missing(&p) {
push(Orphan {
@@ -297,11 +373,25 @@ pub async fn scan(progress: &super::ProgressFn) -> Vec<Orphan> {
}
// 3) MuiCache
- super::report(progress, "winreg", "progress", 2, Some(5), Some("MuiCache".into()));
+ super::report(
+ progress,
+ "winreg",
+ "progress",
+ 2,
+ Some(5),
+ Some("MuiCache".into()),
+ );
let mui = r"HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\MuiCache";
for key in reg_query(mui, false).await {
for v in &key.values {
- let file = v.name.split(".FriendlyAppName").next().unwrap_or("").split(".ApplicationCompany").next().unwrap_or("");
+ let file = v
+ .name
+ .split(".FriendlyAppName")
+ .next()
+ .unwrap_or("")
+ .split(".ApplicationCompany")
+ .next()
+ .unwrap_or("");
if file.is_empty() {
continue;
}
@@ -321,7 +411,14 @@ pub async fn scan(progress: &super::ProgressFn) -> Vec<Orphan> {
}
// 4) SharedDLLs
- super::report(progress, "winreg", "progress", 3, Some(5), Some("SharedDLLs".into()));
+ super::report(
+ progress,
+ "winreg",
+ "progress",
+ 3,
+ Some(5),
+ Some("SharedDLLs".into()),
+ );
let shared = r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\SharedDLLs";
for key in reg_query(shared, false).await {
for v in &key.values {
@@ -332,7 +429,10 @@ pub async fn scan(progress: &super::ProgressFn) -> Vec<Orphan> {
category: "shared-dlls".into(),
key: shared.to_string(),
value: Some(v.name.clone()),
- name: p.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(),
+ name: p
+ .file_name()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_default(),
data: p.to_string_lossy().to_string(),
reason: "arquivo nao existe".into(),
});
@@ -341,7 +441,14 @@ pub async fn scan(progress: &super::ProgressFn) -> Vec<Orphan> {
}
// 5) Run com executável sumido
- super::report(progress, "winreg", "progress", 4, Some(5), Some("Run".into()));
+ super::report(
+ progress,
+ "winreg",
+ "progress",
+ 4,
+ Some(5),
+ Some("Run".into()),
+ );
for root in RUN_KEYS {
for key in reg_query(root, false).await {
for v in &key.values {
@@ -385,7 +492,8 @@ pub async fn fix(items: &[Orphan]) -> FixResult {
backed.insert(item.key.clone());
}
Err(e) => {
- r.failed.push(format!("{}: backup falhou ({})", item.name, e));
+ r.failed
+ .push(format!("{}: backup falhou ({})", item.name, e));
continue;
}
}
@@ -418,9 +526,18 @@ mod tests {
#[test]
fn exe() {
- assert_eq!(command_exe("\"C:\\a b\\x.exe\" /q").unwrap(), PathBuf::from("C:\\a b\\x.exe"));
- assert_eq!(command_exe("C:\\a b\\x.exe /q").unwrap(), PathBuf::from("C:\\a b\\x.exe"));
- assert_eq!(command_exe("rundll32 foo").unwrap(), PathBuf::from("rundll32"));
+ assert_eq!(
+ command_exe("\"C:\\a b\\x.exe\" /q").unwrap(),
+ PathBuf::from("C:\\a b\\x.exe")
+ );
+ assert_eq!(
+ command_exe("C:\\a b\\x.exe /q").unwrap(),
+ PathBuf::from("C:\\a b\\x.exe")
+ );
+ assert_eq!(
+ command_exe("rundll32 foo").unwrap(),
+ PathBuf::from("rundll32")
+ );
assert!(command_exe("").is_none());
assert!(exe_missing(Path::new("C:\\nao\\existe\\x.exe")));
assert!(!exe_missing(Path::new("notepad.exe")));
diff --git a/src-tauri/omniget-core/src/core/tools/win_tweaks.rs b/src-tauri/omniget-core/src/core/tools/win_tweaks.rs
index c581fb46..b4baa606 100644
--- a/src-tauri/omniget-core/src/core/tools/win_tweaks.rs
+++ b/src-tauri/omniget-core/src/core/tools/win_tweaks.rs
@@ -32,53 +32,444 @@ pub struct Rule {
}
#[allow(clippy::too_many_arguments)]
-fn r(id: &str, group: &str, source: &str, key: &str, name: &str, on: RegValue, off: RegValue, admin: bool, restart: bool) -> Rule {
- Rule { id: id.into(), group: group.into(), source: source.into(), key: key.into(), name: name.into(), on, off, requires_admin: admin, restart, applied: None }
+fn r(
+ id: &str,
+ group: &str,
+ source: &str,
+ key: &str,
+ name: &str,
+ on: RegValue,
+ off: RegValue,
+ admin: bool,
+ restart: bool,
+) -> Rule {
+ Rule {
+ id: id.into(),
+ group: group.into(),
+ source: source.into(),
+ key: key.into(),
+ name: name.into(),
+ on,
+ off,
+ requires_admin: admin,
+ restart,
+ applied: None,
+ }
}
pub fn rules() -> Vec<Rule> {
use RegValue::*;
vec![
// ── Privacidade (Sophia: Privacy & Telemetry) ──
- r("advertising-id", "privacy", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\AdvertisingInfo", "Enabled", Dword(0), Dword(1), false, false),
- r("tailored-experiences", "privacy", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Privacy", "TailoredExperiencesWithDiagnosticDataEnabled", Dword(0), Dword(1), false, false),
- r("settings-suggested-content", "privacy", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SubscribedContent-338393Enabled", Dword(0), Dword(1), false, false),
- r("apps-silent-install", "privacy", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SilentInstalledAppsEnabled", Dword(0), Dword(1), false, false),
- r("welcome-experience", "privacy", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SubscribedContent-310093Enabled", Dword(0), Dword(1), false, false),
- r("start-suggestions", "privacy", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SubscribedContent-338388Enabled", Dword(0), Dword(1), false, false),
- r("lockscreen-tips", "privacy", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "RotatingLockScreenOverlayEnabled", Dword(0), Dword(1), false, false),
- r("bing-search", "privacy", "sophia", r"HKCU\Software\Policies\Microsoft\Windows\Explorer", "DisableSearchBoxSuggestions", Dword(1), Delete, false, true),
- r("diagnostic-data-minimal", "privacy", "sophia", r"HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection", "AllowTelemetry", Dword(1), Delete, true, true),
- r("feedback-never", "privacy", "sophia", r"HKCU\Software\Microsoft\Siuf\Rules", "NumberOfSIUFInPeriod", Dword(0), Delete, false, false),
- r("activity-history", "privacy", "sophia", r"HKLM\SOFTWARE\Policies\Microsoft\Windows\System", "PublishUserActivities", Dword(0), Delete, true, false),
- r("location-tracking", "privacy", "sophia", r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location", "Value", Str("Deny".into()), Str("Allow".into()), true, false),
- r("copilot-off", "privacy", "sophia", r"HKCU\Software\Policies\Microsoft\Windows\WindowsCopilot", "TurnOffWindowsCopilot", Dword(1), Delete, false, true),
- r("recall-off", "privacy", "hardentools", r"HKCU\Software\Policies\Microsoft\Windows\WindowsAI", "DisableAIDataAnalysis", Dword(1), Delete, false, true),
+ r(
+ "advertising-id",
+ "privacy",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\AdvertisingInfo",
+ "Enabled",
+ Dword(0),
+ Dword(1),
+ false,
+ false,
+ ),
+ r(
+ "tailored-experiences",
+ "privacy",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Privacy",
+ "TailoredExperiencesWithDiagnosticDataEnabled",
+ Dword(0),
+ Dword(1),
+ false,
+ false,
+ ),
+ r(
+ "settings-suggested-content",
+ "privacy",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager",
+ "SubscribedContent-338393Enabled",
+ Dword(0),
+ Dword(1),
+ false,
+ false,
+ ),
+ r(
+ "apps-silent-install",
+ "privacy",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager",
+ "SilentInstalledAppsEnabled",
+ Dword(0),
+ Dword(1),
+ false,
+ false,
+ ),
+ r(
+ "welcome-experience",
+ "privacy",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager",
+ "SubscribedContent-310093Enabled",
+ Dword(0),
+ Dword(1),
+ false,
+ false,
+ ),
+ r(
+ "start-suggestions",
+ "privacy",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager",
+ "SubscribedContent-338388Enabled",
+ Dword(0),
+ Dword(1),
+ false,
+ false,
+ ),
+ r(
+ "lockscreen-tips",
+ "privacy",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager",
+ "RotatingLockScreenOverlayEnabled",
+ Dword(0),
+ Dword(1),
+ false,
+ false,
+ ),
+ r(
+ "bing-search",
+ "privacy",
+ "sophia",
+ r"HKCU\Software\Policies\Microsoft\Windows\Explorer",
+ "DisableSearchBoxSuggestions",
+ Dword(1),
+ Delete,
+ false,
+ true,
+ ),
+ r(
+ "diagnostic-data-minimal",
+ "privacy",
+ "sophia",
+ r"HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection",
+ "AllowTelemetry",
+ Dword(1),
+ Delete,
+ true,
+ true,
+ ),
+ r(
+ "feedback-never",
+ "privacy",
+ "sophia",
+ r"HKCU\Software\Microsoft\Siuf\Rules",
+ "NumberOfSIUFInPeriod",
+ Dword(0),
+ Delete,
+ false,
+ false,
+ ),
+ r(
+ "activity-history",
+ "privacy",
+ "sophia",
+ r"HKLM\SOFTWARE\Policies\Microsoft\Windows\System",
+ "PublishUserActivities",
+ Dword(0),
+ Delete,
+ true,
+ false,
+ ),
+ r(
+ "location-tracking",
+ "privacy",
+ "sophia",
+ r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location",
+ "Value",
+ Str("Deny".into()),
+ Str("Allow".into()),
+ true,
+ false,
+ ),
+ r(
+ "copilot-off",
+ "privacy",
+ "sophia",
+ r"HKCU\Software\Policies\Microsoft\Windows\WindowsCopilot",
+ "TurnOffWindowsCopilot",
+ Dword(1),
+ Delete,
+ false,
+ true,
+ ),
+ r(
+ "recall-off",
+ "privacy",
+ "hardentools",
+ r"HKCU\Software\Policies\Microsoft\Windows\WindowsAI",
+ "DisableAIDataAnalysis",
+ Dword(1),
+ Delete,
+ false,
+ true,
+ ),
// ── Interface (Sophia: UI & Personalization) ──
- r("show-file-extensions", "ui", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "HideFileExt", Dword(0), Dword(1), false, false),
- r("show-hidden-files", "ui", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "Hidden", Dword(1), Dword(2), false, false),
- r("explorer-this-pc", "ui", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "LaunchTo", Dword(1), Dword(2), false, false),
- r("taskbar-left", "ui", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "TaskbarAl", Dword(0), Dword(1), false, false),
- r("taskbar-no-search", "ui", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Search", "SearchboxTaskbarMode", Dword(0), Dword(2), false, false),
- r("taskbar-no-widgets", "ui", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "TaskbarDa", Dword(0), Dword(1), false, false),
- r("taskbar-end-task", "ui", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\TaskbarDeveloperSettings", "TaskbarEndTask", Dword(1), Dword(0), false, false),
- r("classic-context-menu", "context", "sophia", r"HKCU\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32", "", Str(String::new()), Delete, false, true),
- r("onedrive-ad-explorer", "ui", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "ShowSyncProviderNotifications", Dword(0), Dword(1), false, false),
- r("seconds-in-clock", "ui", "sophia", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "ShowSecondsInSystemClock", Dword(1), Dword(0), false, false),
+ r(
+ "show-file-extensions",
+ "ui",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
+ "HideFileExt",
+ Dword(0),
+ Dword(1),
+ false,
+ false,
+ ),
+ r(
+ "show-hidden-files",
+ "ui",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
+ "Hidden",
+ Dword(1),
+ Dword(2),
+ false,
+ false,
+ ),
+ r(
+ "explorer-this-pc",
+ "ui",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
+ "LaunchTo",
+ Dword(1),
+ Dword(2),
+ false,
+ false,
+ ),
+ r(
+ "taskbar-left",
+ "ui",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
+ "TaskbarAl",
+ Dword(0),
+ Dword(1),
+ false,
+ false,
+ ),
+ r(
+ "taskbar-no-search",
+ "ui",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Search",
+ "SearchboxTaskbarMode",
+ Dword(0),
+ Dword(2),
+ false,
+ false,
+ ),
+ r(
+ "taskbar-no-widgets",
+ "ui",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
+ "TaskbarDa",
+ Dword(0),
+ Dword(1),
+ false,
+ false,
+ ),
+ r(
+ "taskbar-end-task",
+ "ui",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\TaskbarDeveloperSettings",
+ "TaskbarEndTask",
+ Dword(1),
+ Dword(0),
+ false,
+ false,
+ ),
+ r(
+ "classic-context-menu",
+ "context",
+ "sophia",
+ r"HKCU\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32",
+ "",
+ Str(String::new()),
+ Delete,
+ false,
+ true,
+ ),
+ r(
+ "onedrive-ad-explorer",
+ "ui",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
+ "ShowSyncProviderNotifications",
+ Dword(0),
+ Dword(1),
+ false,
+ false,
+ ),
+ r(
+ "seconds-in-clock",
+ "ui",
+ "sophia",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
+ "ShowSecondsInSystemClock",
+ Dword(1),
+ Dword(0),
+ false,
+ false,
+ ),
// ── Endurecimento (hardentools) ──
- r("autorun-off", "harden", "hardentools", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "NoDriveTypeAutoRun", Dword(0xFF), Delete, false, false),
- r("autoplay-off", "harden", "hardentools", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorers\AutoplayHandlers", "DisableAutoplay", Dword(1), Dword(0), false, false),
- r("wsh-off", "harden", "hardentools", r"HKCU\Software\Microsoft\Windows Script Host\Settings", "Enabled", Dword(0), Delete, false, false),
- r("office-macros-word", "harden", "hardentools", r"HKCU\Software\Microsoft\Office\16.0\Word\Security", "VBAWarnings", Dword(4), Dword(2), false, false),
- r("office-macros-excel", "harden", "hardentools", r"HKCU\Software\Microsoft\Office\16.0\Excel\Security", "VBAWarnings", Dword(4), Dword(2), false, false),
- r("office-macros-powerpoint", "harden", "hardentools", r"HKCU\Software\Microsoft\Office\16.0\PowerPoint\Security", "VBAWarnings", Dword(4), Dword(2), false, false),
- r("office-dde-word", "harden", "hardentools", r"HKCU\Software\Microsoft\Office\16.0\Word\Options", "DontUpdateLinks", Dword(1), Delete, false, false),
- r("office-dde-excel", "harden", "hardentools", r"HKCU\Software\Microsoft\Office\16.0\Excel\Options", "DontUpdateLinks", Dword(1), Delete, false, false),
- r("acrobat-js-off", "harden", "hardentools", r"HKCU\Software\Adobe\Acrobat Reader\DC\JSPrefs", "bEnableJS", Dword(0), Dword(1), false, false),
- r("defender-pua", "harden", "hardentools", r"HKLM\SOFTWARE\Policies\Microsoft\Windows Defender", "PUAProtection", Dword(1), Delete, true, false),
- r("uac-max", "harden", "hardentools", r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "ConsentPromptBehaviorAdmin", Dword(2), Dword(5), true, false),
- r("lsa-protection", "harden", "hardentools", r"HKLM\SYSTEM\CurrentControlSet\Control\Lsa", "RunAsPPL", Dword(1), Delete, true, true),
- r("safe-dll-loading", "harden", "hardentools", r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager", "SafeDllSearchMode", Dword(1), Delete, true, true),
+ r(
+ "autorun-off",
+ "harden",
+ "hardentools",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer",
+ "NoDriveTypeAutoRun",
+ Dword(0xFF),
+ Delete,
+ false,
+ false,
+ ),
+ r(
+ "autoplay-off",
+ "harden",
+ "hardentools",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorers\AutoplayHandlers",
+ "DisableAutoplay",
+ Dword(1),
+ Dword(0),
+ false,
+ false,
+ ),
+ r(
+ "wsh-off",
+ "harden",
+ "hardentools",
+ r"HKCU\Software\Microsoft\Windows Script Host\Settings",
+ "Enabled",
+ Dword(0),
+ Delete,
+ false,
+ false,
+ ),
+ r(
+ "office-macros-word",
+ "harden",
+ "hardentools",
+ r"HKCU\Software\Microsoft\Office\16.0\Word\Security",
+ "VBAWarnings",
+ Dword(4),
+ Dword(2),
+ false,
+ false,
+ ),
+ r(
+ "office-macros-excel",
+ "harden",
+ "hardentools",
+ r"HKCU\Software\Microsoft\Office\16.0\Excel\Security",
+ "VBAWarnings",
+ Dword(4),
+ Dword(2),
+ false,
+ false,
+ ),
+ r(
+ "office-macros-powerpoint",
+ "harden",
+ "hardentools",
+ r"HKCU\Software\Microsoft\Office\16.0\PowerPoint\Security",
+ "VBAWarnings",
+ Dword(4),
+ Dword(2),
+ false,
+ false,
+ ),
+ r(
+ "office-dde-word",
+ "harden",
+ "hardentools",
+ r"HKCU\Software\Microsoft\Office\16.0\Word\Options",
+ "DontUpdateLinks",
+ Dword(1),
+ Delete,
+ false,
+ false,
+ ),
+ r(
+ "office-dde-excel",
+ "harden",
+ "hardentools",
+ r"HKCU\Software\Microsoft\Office\16.0\Excel\Options",
+ "DontUpdateLinks",
+ Dword(1),
+ Delete,
+ false,
+ false,
+ ),
+ r(
+ "acrobat-js-off",
+ "harden",
+ "hardentools",
+ r"HKCU\Software\Adobe\Acrobat Reader\DC\JSPrefs",
+ "bEnableJS",
+ Dword(0),
+ Dword(1),
+ false,
+ false,
+ ),
+ r(
+ "defender-pua",
+ "harden",
+ "hardentools",
+ r"HKLM\SOFTWARE\Policies\Microsoft\Windows Defender",
+ "PUAProtection",
+ Dword(1),
+ Delete,
+ true,
+ false,
+ ),
+ r(
+ "uac-max",
+ "harden",
+ "hardentools",
+ r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System",
+ "ConsentPromptBehaviorAdmin",
+ Dword(2),
+ Dword(5),
+ true,
+ false,
+ ),
+ r(
+ "lsa-protection",
+ "harden",
+ "hardentools",
+ r"HKLM\SYSTEM\CurrentControlSet\Control\Lsa",
+ "RunAsPPL",
+ Dword(1),
+ Delete,
+ true,
+ true,
+ ),
+ r(
+ "safe-dll-loading",
+ "harden",
+ "hardentools",
+ r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager",
+ "SafeDllSearchMode",
+ Dword(1),
+ Delete,
+ true,
+ true,
+ ),
]
}
@@ -109,7 +500,9 @@ async fn reg_query(key: &str, name: &str) -> Option<RegValue> {
let ty = parts[1];
let val = parts[2..].join(" ");
return Some(match ty {
- "REG_DWORD" => RegValue::Dword(u32::from_str_radix(val.trim_start_matches("0x"), 16).unwrap_or(0)),
+ "REG_DWORD" => RegValue::Dword(
+ u32::from_str_radix(val.trim_start_matches("0x"), 16).unwrap_or(0),
+ ),
_ => RegValue::Str(val),
});
}
@@ -153,7 +546,11 @@ async fn reg_set(key: &str, name: &str, value: &RegValue) -> anyhow::Result<()>
if !out.status.success() {
let msg = String::from_utf8_lossy(&out.stderr).trim().to_string();
// apagar o que não existe não é erro
- if matches!(value, RegValue::Delete) && (msg.contains("unable to find") || msg.contains("não foi possível") || msg.is_empty()) {
+ if matches!(value, RegValue::Delete)
+ && (msg.contains("unable to find")
+ || msg.contains("não foi possível")
+ || msg.is_empty())
+ {
return Ok(());
}
return Err(anyhow!("reg falhou: {}", msg));
@@ -179,11 +576,19 @@ pub async fn status() -> TweaksStatus {
for rule in rules.iter_mut() {
rule.applied = reg_query(&rule.key, &rule.name).await.map(|v| v == rule.on);
}
- return TweaksStatus { supported: true, is_admin: is_admin().await, rules };
+ return TweaksStatus {
+ supported: true,
+ is_admin: is_admin().await,
+ rules,
+ };
}
#[cfg(not(target_os = "windows"))]
{
- TweaksStatus { supported: false, is_admin: false, rules }
+ TweaksStatus {
+ supported: false,
+ is_admin: false,
+ rules,
+ }
}
}
@@ -191,7 +596,10 @@ pub async fn status() -> TweaksStatus {
/// `<app_data>/tools/win_tweaks_backup.json` para o botão "restaurar".
#[allow(unused_mut, unused_variables)]
pub async fn apply(id: &str, enable: bool) -> anyhow::Result<Rule> {
- let mut rule = rules().into_iter().find(|r| r.id == id).ok_or_else(|| anyhow!("regra desconhecida: {}", id))?;
+ let mut rule = rules()
+ .into_iter()
+ .find(|r| r.id == id)
+ .ok_or_else(|| anyhow!("regra desconhecida: {}", id))?;
#[cfg(not(target_os = "windows"))]
{
let _ = enable;
@@ -201,12 +609,18 @@ pub async fn apply(id: &str, enable: bool) -> anyhow::Result<Rule> {
#[cfg(target_os = "windows")]
{
if rule.requires_admin && !is_admin().await {
- return Err(anyhow!("essa regra precisa do OmniGet aberto como administrador"));
+ return Err(anyhow!(
+ "essa regra precisa do OmniGet aberto como administrador"
+ ));
}
if let Some(prev) = reg_query(&rule.key, &rule.name).await {
backup_store(&rule.id, &prev);
}
- let target = if enable { rule.on.clone() } else { restore_value(&rule) };
+ let target = if enable {
+ rule.on.clone()
+ } else {
+ restore_value(&rule)
+ };
reg_set(&rule.key, &rule.name, &target).await?;
rule.applied = Some(enable);
Ok(rule)
@@ -221,7 +635,10 @@ fn backup_path() -> Option<std::path::PathBuf> {
#[cfg(target_os = "windows")]
fn backup_store(id: &str, value: &RegValue) {
let Some(p) = backup_path() else { return };
- let mut map: std::collections::BTreeMap<String, RegValue> = std::fs::read_to_string(&p).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
+ let mut map: std::collections::BTreeMap<String, RegValue> = std::fs::read_to_string(&p)
+ .ok()
+ .and_then(|t| serde_json::from_str(&t).ok())
+ .unwrap_or_default();
map.entry(id.to_string()).or_insert_with(|| value.clone());
if let Some(parent) = p.parent() {
let _ = std::fs::create_dir_all(parent);
diff --git a/src-tauri/omniget-core/src/core/tools/win_updater.rs b/src-tauri/omniget-core/src/core/tools/win_updater.rs
index a330ed0e..33877115 100644
--- a/src-tauri/omniget-core/src/core/tools/win_updater.rs
+++ b/src-tauri/omniget-core/src/core/tools/win_updater.rs
@@ -29,7 +29,10 @@ async fn have(bin: &str) -> bool {
}
async fn output(program: &str, args: &[&str]) -> anyhow::Result<String> {
- let o = crate::core::process::command(program).args(args).output().await?;
+ let o = crate::core::process::command(program)
+ .args(args)
+ .output()
+ .await?;
// winget devolve códigos != 0 quando não há nada, então não falha por status.
Ok(String::from_utf8_lossy(&o.stdout).to_string())
}
@@ -38,13 +41,18 @@ async fn output(program: &str, args: &[&str]) -> anyhow::Result<String> {
/// ("Name Id Version Available Source"). A linha de traços delimita.
pub fn parse_winget(text: &str) -> Vec<Outdated> {
let lines: Vec<&str> = text.lines().collect();
- let Some(sep) = lines.iter().position(|l| l.trim_start().starts_with("---")) else { return vec![] };
+ let Some(sep) = lines.iter().position(|l| l.trim_start().starts_with("---")) else {
+ return vec![];
+ };
if sep == 0 {
return vec![];
}
let header = lines[sep - 1];
let col = |name: &str| header.find(name);
- let (Some(id_i), Some(ver_i), Some(av_i)) = (col("Id"), col("Version"), col("Available")) else { return vec![] };
+ let (Some(id_i), Some(ver_i), Some(av_i)) = (col("Id"), col("Version"), col("Available"))
+ else {
+ return vec![];
+ };
let src_i = col("Source").unwrap_or(header.len());
let cut = |l: &str, a: usize, b: usize| -> String {
let chars: Vec<char> = l.chars().collect();
@@ -64,7 +72,13 @@ pub fn parse_winget(text: &str) -> Vec<Outdated> {
if id.is_empty() || available.is_empty() || name.contains("upgrades available") {
continue;
}
- out.push(Outdated { manager: "winget".into(), id, name, current, available });
+ out.push(Outdated {
+ manager: "winget".into(),
+ id,
+ name,
+ current,
+ available,
+ });
}
out
}
@@ -77,7 +91,13 @@ pub fn parse_choco(text: &str) -> Vec<Outdated> {
if c.len() < 3 || c[0].is_empty() {
return None;
}
- Some(Outdated { manager: "choco".into(), id: c[0].into(), name: c[0].into(), current: c[1].into(), available: c[2].into() })
+ Some(Outdated {
+ manager: "choco".into(),
+ id: c[0].into(),
+ name: c[0].into(),
+ current: c[1].into(),
+ available: c[2].into(),
+ })
})
.collect()
}
@@ -85,20 +105,36 @@ pub fn parse_choco(text: &str) -> Vec<Outdated> {
/// `scoop status`: tabela "Name Installed Version Latest Version ..."
pub fn parse_scoop(text: &str) -> Vec<Outdated> {
let lines: Vec<&str> = text.lines().collect();
- let Some(sep) = lines.iter().position(|l| l.trim_start().starts_with("----")) else { return vec![] };
+ let Some(sep) = lines
+ .iter()
+ .position(|l| l.trim_start().starts_with("----"))
+ else {
+ return vec![];
+ };
let mut out = Vec::new();
for l in lines.iter().skip(sep + 1) {
let cols: Vec<&str> = l.split_whitespace().collect();
if cols.len() < 3 {
continue;
}
- out.push(Outdated { manager: "scoop".into(), id: cols[0].into(), name: cols[0].into(), current: cols[1].into(), available: cols[2].into() });
+ out.push(Outdated {
+ manager: "scoop".into(),
+ id: cols[0].into(),
+ name: cols[0].into(),
+ current: cols[1].into(),
+ available: cols[2].into(),
+ });
}
out
}
pub async fn status() -> UpdaterStatus {
- let mut s = UpdaterStatus { winget: false, choco: false, scoop: false, items: vec![] };
+ let mut s = UpdaterStatus {
+ winget: false,
+ choco: false,
+ scoop: false,
+ items: vec![],
+ };
if !cfg!(target_os = "windows") {
return s;
}
@@ -106,7 +142,17 @@ pub async fn status() -> UpdaterStatus {
s.choco = have("choco").await;
s.scoop = have("scoop").await;
if s.winget {
- if let Ok(t) = output("winget", &["upgrade", "--include-unknown", "--accept-source-agreements", "--disable-interactivity"]).await {
+ if let Ok(t) = output(
+ "winget",
+ &[
+ "upgrade",
+ "--include-unknown",
+ "--accept-source-agreements",
+ "--disable-interactivity",
+ ],
+ )
+ .await
+ {
s.items.extend(parse_winget(&t));
}
}
@@ -133,21 +179,55 @@ pub async fn upgrade(items: &[Outdated], progress: &super::ProgressFn) -> Upgrad
let mut r = UpgradeResult::default();
let total = items.len() as u64;
for (i, it) in items.iter().enumerate() {
- super::report(progress, "updater", "progress", i as u64, Some(total), Some(it.name.clone()));
+ super::report(
+ progress,
+ "updater",
+ "progress",
+ i as u64,
+ Some(total),
+ Some(it.name.clone()),
+ );
let res = match it.manager.as_str() {
"winget" => {
crate::core::process::command("winget")
- .args(["upgrade", "--id", &it.id, "--exact", "--silent", "--accept-package-agreements", "--accept-source-agreements", "--disable-interactivity"])
+ .args([
+ "upgrade",
+ "--id",
+ &it.id,
+ "--exact",
+ "--silent",
+ "--accept-package-agreements",
+ "--accept-source-agreements",
+ "--disable-interactivity",
+ ])
+ .output()
+ .await
+ }
+ "choco" => {
+ crate::core::process::command("choco")
+ .args(["upgrade", &it.id, "-y", "--no-progress"])
+ .output()
+ .await
+ }
+ "scoop" => {
+ crate::core::process::command("scoop")
+ .args(["update", &it.id])
.output()
.await
}
- "choco" => crate::core::process::command("choco").args(["upgrade", &it.id, "-y", "--no-progress"]).output().await,
- "scoop" => crate::core::process::command("scoop").args(["update", &it.id]).output().await,
_ => Err(std::io::Error::other("gerenciador desconhecido")),
};
match res {
Ok(o) if o.status.success() => r.upgraded.push(it.name.clone()),
- Ok(o) => r.failed.push(format!("{}: {}", it.name, String::from_utf8_lossy(&o.stdout).lines().last().unwrap_or("").trim())),
+ Ok(o) => r.failed.push(format!(
+ "{}: {}",
+ it.name,
+ String::from_utf8_lossy(&o.stdout)
+ .lines()
+ .last()
+ .unwrap_or("")
+ .trim()
+ )),
Err(e) => r.failed.push(format!("{}: {}", it.name, anyhow!(e))),
}
}
diff --git a/src-tauri/omniget-core/src/core/tools/x/archive.rs b/src-tauri/omniget-core/src/core/tools/x/archive.rs
index 807d245e..27bbde06 100644
--- a/src-tauri/omniget-core/src/core/tools/x/archive.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/archive.rs
@@ -63,7 +63,11 @@ impl Source {
let p = std::path::Path::new(path);
let mut files = HashMap::new();
if p.is_dir() {
- let data = if p.join("data").is_dir() { p.join("data") } else { p.to_path_buf() };
+ let data = if p.join("data").is_dir() {
+ p.join("data")
+ } else {
+ p.to_path_buf()
+ };
for entry in std::fs::read_dir(&data)? {
let entry = entry?;
let name = entry.file_name().to_string_lossy().to_string();
@@ -96,13 +100,19 @@ impl Source {
/// `tweets.js`, `tweets-part1.js`… concatenados em ordem.
fn json(&self, base: &str) -> Vec<Value> {
- let mut names: Vec<&String> = self.files.keys().filter(|n| *n == &format!("{}.js", base) || n.starts_with(&format!("{}-part", base))).collect();
+ let mut names: Vec<&String> = self
+ .files
+ .keys()
+ .filter(|n| *n == &format!("{}.js", base) || n.starts_with(&format!("{}-part", base)))
+ .collect();
names.sort();
let mut out = Vec::new();
for n in names {
let s = &self.files[n];
let Some(i) = s.find('=') else { continue };
- if let Ok(Value::Array(a)) = serde_json::from_str::<Value>(s[i + 1..].trim().trim_end_matches(';')) {
+ if let Ok(Value::Array(a)) =
+ serde_json::from_str::<Value>(s[i + 1..].trim().trim_end_matches(';'))
+ {
out.extend(a);
}
}
@@ -111,9 +121,21 @@ impl Source {
}
fn wanted(name: &str) -> bool {
- ["account", "profile", "tweets", "tweet", "like", "follower", "following", "block", "mute", "direct-messages", "direct-message"]
- .iter()
- .any(|b| name == format!("{}.js", b) || name.starts_with(&format!("{}-part", b)))
+ [
+ "account",
+ "profile",
+ "tweets",
+ "tweet",
+ "like",
+ "follower",
+ "following",
+ "block",
+ "mute",
+ "direct-messages",
+ "direct-message",
+ ]
+ .iter()
+ .any(|b| name == format!("{}.js", b) || name.starts_with(&format!("{}-part", b)))
}
fn s(v: &Value, k: &str) -> String {
@@ -132,7 +154,10 @@ fn account_list(items: &[Value], key: &str) -> Vec<ArchiveAccount> {
items
.iter()
.filter_map(|v| v.get(key))
- .map(|a| ArchiveAccount { account_id: s(a, "accountId"), user_link: s(a, "userLink") })
+ .map(|a| ArchiveAccount {
+ account_id: s(a, "accountId"),
+ user_link: s(a, "userLink"),
+ })
.filter(|a| !a.account_id.is_empty())
.collect()
}
@@ -145,7 +170,12 @@ fn tweet_from(v: &Value, author: &XUser) -> Option<XPost> {
}
let mut text = s(t, "full_text");
let mut links = Vec::new();
- for u in t.pointer("/entities/urls").and_then(|a| a.as_array()).into_iter().flatten() {
+ for u in t
+ .pointer("/entities/urls")
+ .and_then(|a| a.as_array())
+ .into_iter()
+ .flatten()
+ {
let short = s(u, "url");
let long = s(u, "expanded_url");
if !short.is_empty() && !long.is_empty() {
@@ -154,7 +184,12 @@ fn tweet_from(v: &Value, author: &XUser) -> Option<XPost> {
}
}
let mut media = Vec::new();
- for m in t.pointer("/extended_entities/media").and_then(|a| a.as_array()).into_iter().flatten() {
+ for m in t
+ .pointer("/extended_entities/media")
+ .and_then(|a| a.as_array())
+ .into_iter()
+ .flatten()
+ {
let short = s(m, "url");
if !short.is_empty() {
text = text.replace(&short, "").trim_end().to_string();
@@ -164,24 +199,54 @@ fn tweet_from(v: &Value, author: &XUser) -> Option<XPost> {
let mut url = super::photo_orig_url(&thumb);
if kind != "photo" {
let mut best = 0u64;
- for var in m.pointer("/video_info/variants").and_then(|a| a.as_array()).into_iter().flatten() {
+ for var in m
+ .pointer("/video_info/variants")
+ .and_then(|a| a.as_array())
+ .into_iter()
+ .flatten()
+ {
if s(var, "content_type") == "video/mp4" && n(var, "bitrate") >= best {
best = n(var, "bitrate");
url = s(var, "url");
}
}
}
- media.push(XMedia { kind: if kind == "photo" { "photo".into() } else if kind == "video" { "video".into() } else { "gif".into() }, url, thumb, ..Default::default() });
+ media.push(XMedia {
+ kind: if kind == "photo" {
+ "photo".into()
+ } else if kind == "video" {
+ "video".into()
+ } else {
+ "gif".into()
+ },
+ url,
+ thumb,
+ ..Default::default()
+ });
}
let (created_at, ts) = super::parse_twitter_date(&s(t, "created_at")).unwrap_or_default();
let re_tag = regex::Regex::new(r"#([\p{L}\p{N}_]+)").unwrap();
let re_at = regex::Regex::new(r"@([A-Za-z0-9_]{1,15})").unwrap();
let is_rt = text.starts_with("RT @");
Some(XPost {
- url: format!("https://x.com/{}/status/{}", if author.handle.is_empty() { "i" } else { &author.handle }, id),
+ url: format!(
+ "https://x.com/{}/status/{}",
+ if author.handle.is_empty() {
+ "i"
+ } else {
+ &author.handle
+ },
+ id
+ ),
id,
- hashtags: re_tag.captures_iter(&text).map(|c| c[1].to_string()).collect(),
- mentions: re_at.captures_iter(&text).map(|c| c[1].to_string()).collect(),
+ hashtags: re_tag
+ .captures_iter(&text)
+ .map(|c| c[1].to_string())
+ .collect(),
+ mentions: re_at
+ .captures_iter(&text)
+ .map(|c| c[1].to_string())
+ .collect(),
text,
created_at,
timestamp: ts,
@@ -192,8 +257,15 @@ fn tweet_from(v: &Value, author: &XUser) -> Option<XPost> {
media,
reply_to_id: Some(s(t, "in_reply_to_status_id_str")).filter(|x| !x.is_empty()),
reply_to_handle: Some(s(t, "in_reply_to_screen_name")).filter(|x| !x.is_empty()),
- reposted_by: if is_rt { Some(author.handle.clone()) } else { None },
- source: regex::Regex::new(r"<[^>]+>").unwrap().replace_all(&s(t, "source"), "").to_string(),
+ reposted_by: if is_rt {
+ Some(author.handle.clone())
+ } else {
+ None
+ },
+ source: regex::Regex::new(r"<[^>]+>")
+ .unwrap()
+ .replace_all(&s(t, "source"), "")
+ .to_string(),
links,
..Default::default()
})
@@ -219,13 +291,27 @@ pub struct Loaded {
pub fn load(path: &str) -> anyhow::Result<Loaded> {
use chrono::{Datelike, TimeZone, Timelike};
let src = Source::open(path)?;
- let account = src.json("account").into_iter().next().and_then(|v| v.get("account").cloned()).unwrap_or(Value::Null);
- let profile = src.json("profile").into_iter().next().and_then(|v| v.get("profile").cloned()).unwrap_or(Value::Null);
+ let account = src
+ .json("account")
+ .into_iter()
+ .next()
+ .and_then(|v| v.get("account").cloned())
+ .unwrap_or(Value::Null);
+ let profile = src
+ .json("profile")
+ .into_iter()
+ .next()
+ .and_then(|v| v.get("profile").cloned())
+ .unwrap_or(Value::Null);
let author = XUser {
id: s(&account, "accountId"),
handle: s(&account, "username"),
name: s(&account, "accountDisplayName"),
- bio: profile.pointer("/description/bio").and_then(|b| b.as_str()).unwrap_or("").to_string(),
+ bio: profile
+ .pointer("/description/bio")
+ .and_then(|b| b.as_str())
+ .unwrap_or("")
+ .to_string(),
avatar: s(&profile, "avatarMediaUrl"),
..Default::default()
};
@@ -240,7 +326,15 @@ pub fn load(path: &str) -> anyhow::Result<Loaded> {
.json("like")
.iter()
.filter_map(|v| v.get("like"))
- .map(|l| LikeItem { tweet_id: s(l, "tweetId"), text: s(l, "fullText"), url: if s(l, "expandedUrl").is_empty() { format!("https://x.com/i/status/{}", s(l, "tweetId")) } else { s(l, "expandedUrl") } })
+ .map(|l| LikeItem {
+ tweet_id: s(l, "tweetId"),
+ text: s(l, "fullText"),
+ url: if s(l, "expandedUrl").is_empty() {
+ format!("https://x.com/i/status/{}", s(l, "tweetId"))
+ } else {
+ s(l, "expandedUrl")
+ },
+ })
.collect();
let followers = account_list(&src.json("follower"), "follower");
let following = account_list(&src.json("following"), "following");
@@ -251,12 +345,27 @@ pub fn load(path: &str) -> anyhow::Result<Loaded> {
.iter()
.chain(src.json("direct-message").iter())
.filter_map(|v| v.get("dmConversation"))
- .map(|c| c.get("messages").and_then(|m| m.as_array()).map(|a| a.len()).unwrap_or(0))
+ .map(|c| {
+ c.get("messages")
+ .and_then(|m| m.as_array())
+ .map(|a| a.len())
+ .unwrap_or(0)
+ })
.sum();
- let follower_ids: std::collections::HashSet<&str> = followers.iter().map(|a| a.account_id.as_str()).collect();
- let following_ids: std::collections::HashSet<&str> = following.iter().map(|a| a.account_id.as_str()).collect();
- let not_following_back: Vec<ArchiveAccount> = following.iter().filter(|a| !follower_ids.contains(a.account_id.as_str())).cloned().collect();
- let fans: Vec<ArchiveAccount> = followers.iter().filter(|a| !following_ids.contains(a.account_id.as_str())).cloned().collect();
+ let follower_ids: std::collections::HashSet<&str> =
+ followers.iter().map(|a| a.account_id.as_str()).collect();
+ let following_ids: std::collections::HashSet<&str> =
+ following.iter().map(|a| a.account_id.as_str()).collect();
+ let not_following_back: Vec<ArchiveAccount> = following
+ .iter()
+ .filter(|a| !follower_ids.contains(a.account_id.as_str()))
+ .cloned()
+ .collect();
+ let fans: Vec<ArchiveAccount> = followers
+ .iter()
+ .filter(|a| !following_ids.contains(a.account_id.as_str()))
+ .cloned()
+ .collect();
let mut by_year: HashMap<i32, YearCount> = HashMap::new();
let mut by_weekday = vec![0u64; 7];
let mut by_hour = vec![0u64; 24];
@@ -268,7 +377,10 @@ pub fn load(path: &str) -> anyhow::Result<Loaded> {
min_ts = min_ts.min(p.timestamp);
max_ts = max_ts.max(p.timestamp);
if let Some(dt) = chrono::Local.timestamp_opt(p.timestamp, 0).single() {
- let e = by_year.entry(dt.year()).or_insert(YearCount { year: dt.year(), ..Default::default() });
+ let e = by_year.entry(dt.year()).or_insert(YearCount {
+ year: dt.year(),
+ ..Default::default()
+ });
e.tweets += 1;
e.likes_received += p.likes;
by_weekday[dt.weekday().num_days_from_sunday() as usize] += 1;
@@ -277,7 +389,11 @@ pub fn load(path: &str) -> anyhow::Result<Loaded> {
}
let mut by_year: Vec<YearCount> = by_year.into_values().collect();
by_year.sort_by_key(|y| y.year);
- let mut top: Vec<XPost> = posts.iter().filter(|p| p.reposted_by.is_none()).cloned().collect();
+ let mut top: Vec<XPost> = posts
+ .iter()
+ .filter(|p| p.reposted_by.is_none())
+ .cloned()
+ .collect();
top.sort_by_key(|b| std::cmp::Reverse(b.likes + b.reposts * 2));
top.truncate(10);
let summary = ArchiveSummary {
@@ -295,8 +411,16 @@ pub fn load(path: &str) -> anyhow::Result<Loaded> {
blocked: blocked.len(),
muted: muted.len(),
dm_messages,
- first_tweet: if min_ts < i64::MAX { super::iso_from_timestamp(min_ts) } else { String::new() },
- last_tweet: if max_ts > i64::MIN { super::iso_from_timestamp(max_ts) } else { String::new() },
+ first_tweet: if min_ts < i64::MAX {
+ super::iso_from_timestamp(min_ts)
+ } else {
+ String::new()
+ },
+ last_tweet: if max_ts > i64::MIN {
+ super::iso_from_timestamp(max_ts)
+ } else {
+ String::new()
+ },
likes_received: posts.iter().map(|p| p.likes).sum(),
reposts_received: posts.iter().map(|p| p.reposts).sum(),
by_year,
@@ -311,7 +435,15 @@ pub fn load(path: &str) -> anyhow::Result<Loaded> {
f
},
};
- Ok(Loaded { summary, posts, likes, followers, following, blocked, muted })
+ Ok(Loaded {
+ summary,
+ posts,
+ likes,
+ followers,
+ following,
+ blocked,
+ muted,
+ })
}
pub fn open(path: &str) -> anyhow::Result<ArchiveSummary> {
@@ -323,35 +455,71 @@ pub fn export(path: &str, dest_dir: &str, what: &str, format: &str) -> anyhow::R
let l = load(path)?;
let dir = std::path::Path::new(dest_dir);
std::fs::create_dir_all(dir)?;
- let file = dir.join(format!("x-archive-{}-{}.{}", l.summary.username, what, super::export::ext_for(format)));
+ let file = dir.join(format!(
+ "x-archive-{}-{}.{}",
+ l.summary.username,
+ what,
+ super::export::ext_for(format)
+ ));
let accounts = |list: &[ArchiveAccount]| -> anyhow::Result<String> {
let content = match format {
"json" => serde_json::to_string_pretty(list)?,
"csv" => {
let mut o = String::from("account_id,url\n");
for a in list {
- o.push_str(&format!("{},{}\n", a.account_id, if a.user_link.is_empty() { format!("https://x.com/i/user/{}", a.account_id) } else { a.user_link.clone() }));
+ o.push_str(&format!(
+ "{},{}\n",
+ a.account_id,
+ if a.user_link.is_empty() {
+ format!("https://x.com/i/user/{}", a.account_id)
+ } else {
+ a.user_link.clone()
+ }
+ ));
}
o
}
- _ => list.iter().map(|a| format!("- https://x.com/i/user/{}", a.account_id)).collect::<Vec<_>>().join("\n") + "\n",
+ _ => {
+ list.iter()
+ .map(|a| format!("- https://x.com/i/user/{}", a.account_id))
+ .collect::<Vec<_>>()
+ .join("\n")
+ + "\n"
+ }
};
std::fs::write(&file, content)?;
Ok(file.to_string_lossy().to_string())
};
match what {
- "tweets" => super::export::write_posts(&l.posts, format, &file, &format!("Posts de @{}", l.summary.username)),
+ "tweets" => super::export::write_posts(
+ &l.posts,
+ format,
+ &file,
+ &format!("Posts de @{}", l.summary.username),
+ ),
"likes" => {
let content = match format {
"json" => serde_json::to_string_pretty(&l.likes)?,
"csv" => {
let mut o = String::from("tweet_id,url,text\n");
for k in &l.likes {
- o.push_str(&format!("{},{},{}\n", k.tweet_id, k.url, super::export::csv_escape(&k.text)));
+ o.push_str(&format!(
+ "{},{},{}\n",
+ k.tweet_id,
+ k.url,
+ super::export::csv_escape(&k.text)
+ ));
}
o
}
- _ => l.likes.iter().map(|k| format!("- {}\n {}", k.text.replace('\n', " "), k.url)).collect::<Vec<_>>().join("\n") + "\n",
+ _ => {
+ l.likes
+ .iter()
+ .map(|k| format!("- {}\n {}", k.text.replace('\n', " "), k.url))
+ .collect::<Vec<_>>()
+ .join("\n")
+ + "\n"
+ }
};
std::fs::write(&file, content)?;
Ok(file.to_string_lossy().to_string())
diff --git a/src-tauri/omniget-core/src/core/tools/x/bookmarks.rs b/src-tauri/omniget-core/src/core/tools/x/bookmarks.rs
index 31d18604..82013b0a 100644
--- a/src-tauri/omniget-core/src/core/tools/x/bookmarks.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/bookmarks.rs
@@ -38,9 +38,16 @@ fn folders_from(v: &Value) -> Vec<BookmarkFolder> {
fn walk(v: &Value, out: &mut Vec<BookmarkFolder>) {
match v {
Value::Object(m) => {
- if let (Some(id), Some(name)) = (m.get("id").and_then(|x| x.as_str()), m.get("name").and_then(|x| x.as_str())) {
+ if let (Some(id), Some(name)) = (
+ m.get("id").and_then(|x| x.as_str()),
+ m.get("name").and_then(|x| x.as_str()),
+ ) {
if m.contains_key("media") || m.contains_key("bookmark_count") || m.len() <= 4 {
- out.push(BookmarkFolder { id: id.to_string(), name: name.to_string(), count: 0 });
+ out.push(BookmarkFolder {
+ id: id.to_string(),
+ name: name.to_string(),
+ count: 0,
+ });
return;
}
}
@@ -70,24 +77,31 @@ fn find_key(v: &Value, key: &str) -> Option<Value> {
}
pub async fn folders(client: &XClient) -> anyhow::Result<Vec<BookmarkFolder>> {
- let v = client.gql_get("BookmarkFoldersSlice", json!({}), json!({}), None).await?;
+ let v = client
+ .gql_get("BookmarkFoldersSlice", json!({}), json!({}), None)
+ .await?;
Ok(folders_from(&v))
}
/// Lista tudo (com pastas) sem gravar nada; `max` = 0 e sem limite.
-pub async fn collect(max: usize, progress: &ProgressFn) -> anyhow::Result<(Vec<BookmarkItem>, Vec<BookmarkFolder>, bool)> {
+pub async fn collect(
+ max: usize,
+ progress: &ProgressFn,
+) -> anyhow::Result<(Vec<BookmarkItem>, Vec<BookmarkFolder>, bool)> {
let client = XClient::new()?;
client.require_login()?;
super::clear_cancel(JOB);
super::report(progress, JOB, "folders", 0, None, None);
let mut folders = folders(&client).await.unwrap_or_default();
- let mut folder_of: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();
+ let mut folder_of: std::collections::HashMap<String, Vec<String>> =
+ std::collections::HashMap::new();
for f in folders.iter_mut() {
if super::cancelled(JOB) {
break;
}
super::report(progress, JOB, "folder", 0, None, Some(f.name.clone()));
- let vars = json!({ "bookmark_collection_id": f.id, "count": 50, "includePromotedContent": false });
+ let vars =
+ json!({ "bookmark_collection_id": f.id, "count": 50, "includePromotedContent": false });
let name = f.name.clone();
let mut ids: Vec<String> = Vec::new();
let _ = client
@@ -107,25 +121,40 @@ pub async fn collect(max: usize, progress: &ProgressFn) -> anyhow::Result<(Vec<B
let vars = json!({ "count": 100, "includePromotedContent": false, "withClientEventToken": false, "withBirdwatchNotes": false, "withVoice": true, "withV2Timeline": true });
let p2 = progress.clone();
client
- .paginate("Bookmarks", vars, json!({ "graphql_timeline_v2_bookmark_timeline": true }), max, JOB, |page| {
- let got = super::parse::tweets_from(page);
- let n = got.len();
- posts.extend(got);
- super::report(&p2, JOB, "bookmarks", posts.len() as u64, None, None);
- n
- })
+ .paginate(
+ "Bookmarks",
+ vars,
+ json!({ "graphql_timeline_v2_bookmark_timeline": true }),
+ max,
+ JOB,
+ |page| {
+ let got = super::parse::tweets_from(page);
+ let n = got.len();
+ posts.extend(got);
+ super::report(&p2, JOB, "bookmarks", posts.len() as u64, None, None);
+ n
+ },
+ )
.await?;
let cancelled = super::cancelled(JOB);
let mut posts = super::dedup_posts(posts);
if max > 0 {
posts.truncate(max);
}
- let items = posts.into_iter().map(|p| BookmarkItem { folders: folder_of.get(&p.id).cloned().unwrap_or_default(), post: p }).collect();
+ let items = posts
+ .into_iter()
+ .map(|p| BookmarkItem {
+ folders: folder_of.get(&p.id).cloned().unwrap_or_default(),
+ post: p,
+ })
+ .collect();
Ok((items, folders, cancelled))
}
fn csv(items: &[BookmarkItem]) -> String {
- let mut out = String::from("id,url,created_at,author,name,text,likes,reposts,replies,views,folders,media_urls\n");
+ let mut out = String::from(
+ "id,url,created_at,author,name,text,likes,reposts,replies,views,folders,media_urls\n",
+ );
for it in items {
let p = &it.post;
let row = [
@@ -140,15 +169,30 @@ fn csv(items: &[BookmarkItem]) -> String {
p.replies.to_string(),
p.views.to_string(),
it.folders.join("; "),
- p.media.iter().map(|m| m.url.clone()).collect::<Vec<_>>().join(" "),
+ p.media
+ .iter()
+ .map(|m| m.url.clone())
+ .collect::<Vec<_>>()
+ .join(" "),
];
- out.push_str(&row.iter().map(|c| super::export::csv_escape(c)).collect::<Vec<_>>().join(","));
+ out.push_str(
+ &row.iter()
+ .map(|c| super::export::csv_escape(c))
+ .collect::<Vec<_>>()
+ .join(","),
+ );
out.push('\n');
}
out
}
-pub async fn export(dest: &str, formats: &[String], with_media: bool, max: usize, progress: ProgressFn) -> anyhow::Result<BookmarksResult> {
+pub async fn export(
+ dest: &str,
+ formats: &[String],
+ with_media: bool,
+ max: usize,
+ progress: ProgressFn,
+) -> anyhow::Result<BookmarksResult> {
let (items, folders, cancelled) = collect(max, &progress).await?;
let dir = std::path::Path::new(dest);
std::fs::create_dir_all(dir)?;
@@ -156,7 +200,11 @@ pub async fn export(dest: &str, formats: &[String], with_media: bool, max: usize
let mut files = Vec::new();
let posts: Vec<XPost> = items.iter().map(|i| i.post.clone()).collect();
for f in formats {
- let path = dir.join(format!("x-bookmarks-{}.{}", stamp, super::export::ext_for(f)));
+ let path = dir.join(format!(
+ "x-bookmarks-{}.{}",
+ stamp,
+ super::export::ext_for(f)
+ ));
let written = match f.as_str() {
"json" => {
std::fs::write(&path, serde_json::to_string_pretty(&items)?)?;
@@ -172,9 +220,25 @@ pub async fn export(dest: &str, formats: &[String], with_media: bool, max: usize
}
let mut media_files = 0;
if with_media && !cancelled {
- let r = super::media::download_posts(&posts, &dir.join("media"), true, true, JOB, &progress).await?;
+ let r =
+ super::media::download_posts(&posts, &dir.join("media"), true, true, JOB, &progress)
+ .await?;
media_files = r.files.len();
}
- super::report(&progress, JOB, "done", items.len() as u64, Some(items.len() as u64), None);
- Ok(BookmarksResult { count: items.len(), folders, files, media_files, cancelled, preview: items.into_iter().take(60).collect() })
+ super::report(
+ &progress,
+ JOB,
+ "done",
+ items.len() as u64,
+ Some(items.len() as u64),
+ None,
+ );
+ Ok(BookmarksResult {
+ count: items.len(),
+ folders,
+ files,
+ media_files,
+ cancelled,
+ preview: items.into_iter().take(60).collect(),
+ })
}
diff --git a/src-tauri/omniget-core/src/core/tools/x/client.rs b/src-tauri/omniget-core/src/core/tools/x/client.rs
index 2074d445..0317565e 100644
--- a/src-tauri/omniget-core/src/core/tools/x/client.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/client.rs
@@ -25,32 +25,56 @@ const BASE_FEATURES: &[(&str, bool)] = &[
("creator_subscriptions_quote_tweet_preview_enabled", false),
("creator_subscriptions_tweet_preview_api_enabled", true),
("freedom_of_speech_not_reach_fetch_enabled", true),
- ("graphql_is_translatable_rweb_tweet_is_translatable_enabled", true),
+ (
+ "graphql_is_translatable_rweb_tweet_is_translatable_enabled",
+ true,
+ ),
("longform_notetweets_consumption_enabled", true),
("longform_notetweets_inline_media_enabled", true),
("longform_notetweets_rich_text_read_enabled", true),
("responsive_web_edit_tweet_api_enabled", true),
("responsive_web_enhance_cards_enabled", false),
("responsive_web_graphql_exclude_directive_enabled", true),
- ("responsive_web_graphql_skip_user_profile_image_extensions_enabled", false),
- ("responsive_web_grok_community_note_auto_translation_is_enabled", false),
+ (
+ "responsive_web_graphql_skip_user_profile_image_extensions_enabled",
+ false,
+ ),
+ (
+ "responsive_web_grok_community_note_auto_translation_is_enabled",
+ false,
+ ),
("responsive_web_graphql_timeline_navigation_enabled", true),
("responsive_web_grok_imagine_annotation_enabled", false),
("responsive_web_media_download_video_enabled", false),
("responsive_web_profile_redirect_enabled", true),
- ("responsive_web_twitter_article_tweet_consumption_enabled", true),
+ (
+ "responsive_web_twitter_article_tweet_consumption_enabled",
+ true,
+ ),
("rweb_tipjar_consumption_enabled", true),
("rweb_video_timestamps_enabled", true),
("standardized_nudges_misinfo", true),
("tweet_awards_web_tipping_enabled", false),
- ("tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled", true),
- ("tweet_with_visibility_results_prefer_gql_media_interstitial_enabled", false),
+ (
+ "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled",
+ true,
+ ),
+ (
+ "tweet_with_visibility_results_prefer_gql_media_interstitial_enabled",
+ false,
+ ),
("tweetypie_unmention_optimization_enabled", true),
("verified_phone_label_enabled", false),
("view_counts_everywhere_api_enabled", true),
- ("responsive_web_grok_analyze_button_fetch_trends_enabled", false),
+ (
+ "responsive_web_grok_analyze_button_fetch_trends_enabled",
+ false,
+ ),
("premium_content_api_read_enabled", false),
- ("profile_label_improvements_pcf_label_in_post_enabled", false),
+ (
+ "profile_label_improvements_pcf_label_in_post_enabled",
+ false,
+ ),
("responsive_web_grok_share_attachment_enabled", false),
("responsive_web_grok_analyze_post_followups_enabled", false),
("responsive_web_grok_image_annotation_enabled", false),
@@ -62,8 +86,14 @@ const BASE_FEATURES: &[(&str, bool)] = &[
("highlights_tweets_tab_ui_enabled", true),
("responsive_web_twitter_article_notes_tab_enabled", true),
("subscriptions_feature_can_gift_premium", true),
- ("subscriptions_verification_info_is_identity_verified_enabled", true),
- ("subscriptions_verification_info_verified_since_enabled", true),
+ (
+ "subscriptions_verification_info_is_identity_verified_enabled",
+ true,
+ ),
+ (
+ "subscriptions_verification_info_verified_since_enabled",
+ true,
+ ),
];
/// Flags que o site manda em toda chamada (twscrape, 2026-08).
@@ -101,15 +131,19 @@ pub fn cookie_value(header: &str, name: &str) -> Option<String> {
impl XClient {
pub fn new() -> anyhow::Result<Self> {
let mut headers = HeaderMap::new();
- headers.insert(reqwest::header::USER_AGENT, HeaderValue::from_static(USER_AGENT));
+ headers.insert(
+ reqwest::header::USER_AGENT,
+ HeaderValue::from_static(USER_AGENT),
+ );
let http = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
.default_headers(headers)
.cookie_store(false)
.timeout(Duration::from_secs(90))
.build()?;
- let cookie = crate::platforms::cookie_provider::cookie_header_for_domains(&["x.com", "twitter.com"])
- .map(|c| c.trim().trim_end_matches(';').to_string())
- .filter(|c| !c.is_empty());
+ let cookie =
+ crate::platforms::cookie_provider::cookie_header_for_domains(&["x.com", "twitter.com"])
+ .map(|c| c.trim().trim_end_matches(';').to_string())
+ .filter(|c| !c.is_empty());
Ok(Self { http, cookie })
}
@@ -122,7 +156,10 @@ impl XClient {
}
pub fn authed(&self) -> bool {
- self.cookie.as_deref().map(|c| cookie_value(c, "auth_token").is_some() && cookie_value(c, "ct0").is_some()).unwrap_or(false)
+ self.cookie
+ .as_deref()
+ .map(|c| cookie_value(c, "auth_token").is_some() && cookie_value(c, "ct0").is_some())
+ .unwrap_or(false)
}
pub fn require_login(&self) -> anyhow::Result<()> {
@@ -136,8 +173,14 @@ impl XClient {
/// Id numerico do usuario logado (cookie `twid=u%3D<id>`).
pub fn user_id(&self) -> Option<String> {
let raw = cookie_value(self.cookie.as_deref()?, "twid")?;
- let dec = urlencoding::decode(&raw).map(|c| c.to_string()).unwrap_or(raw);
- let id = dec.trim().trim_start_matches("u=").trim_matches('"').to_string();
+ let dec = urlencoding::decode(&raw)
+ .map(|c| c.to_string())
+ .unwrap_or(raw);
+ let id = dec
+ .trim()
+ .trim_start_matches("u=")
+ .trim_matches('"')
+ .to_string();
(!id.is_empty() && id.chars().all(|c| c.is_ascii_digit())).then_some(id)
}
@@ -159,10 +202,17 @@ impl XClient {
.send()
.await?;
if !resp.status().is_success() {
- return Err(anyhow!("X nao entregou guest token: HTTP {}", resp.status()));
+ return Err(anyhow!(
+ "X nao entregou guest token: HTTP {}",
+ resp.status()
+ ));
}
let v: Value = resp.json().await?;
- let tok = v.get("guest_token").and_then(|t| t.as_str()).ok_or_else(|| anyhow!("guest token ausente"))?.to_string();
+ let tok = v
+ .get("guest_token")
+ .and_then(|t| t.as_str())
+ .ok_or_else(|| anyhow!("guest token ausente"))?
+ .to_string();
*g = Some((tok.clone(), Instant::now()));
Ok(tok)
}
@@ -187,7 +237,9 @@ impl XClient {
};
*slot = Some((key, gen, Instant::now()));
}
- slot.as_ref().and_then(|(_, g, _)| g.as_ref()).map(|g| g.calc(method, path))
+ slot.as_ref()
+ .and_then(|(_, g, _)| g.as_ref())
+ .map(|g| g.calc(method, path))
}
async fn headers(&self, method: &str, path: &str) -> anyhow::Result<HeaderMap> {
@@ -196,15 +248,24 @@ impl XClient {
h.insert("x-twitter-active-user", HeaderValue::from_static("yes"));
h.insert("x-twitter-client-language", HeaderValue::from_static("en"));
h.insert("Accept", HeaderValue::from_static("*/*"));
- h.insert("Accept-Language", HeaderValue::from_static("en-US,en;q=0.9"));
+ h.insert(
+ "Accept-Language",
+ HeaderValue::from_static("en-US,en;q=0.9"),
+ );
h.insert("Origin", HeaderValue::from_static("https://x.com"));
h.insert("Referer", HeaderValue::from_static("https://x.com/"));
if self.authed() {
- h.insert("Cookie", HeaderValue::from_str(self.cookie.as_deref().unwrap_or(""))?);
+ h.insert(
+ "Cookie",
+ HeaderValue::from_str(self.cookie.as_deref().unwrap_or(""))?,
+ );
if let Some(ct0) = self.ct0() {
h.insert("x-csrf-token", HeaderValue::from_str(&ct0)?);
}
- h.insert("x-twitter-auth-type", HeaderValue::from_static("OAuth2Session"));
+ h.insert(
+ "x-twitter-auth-type",
+ HeaderValue::from_static("OAuth2Session"),
+ );
if let Some(tx) = self.tx_header(method, path).await {
if let Ok(v) = HeaderValue::from_str(&tx) {
h.insert("x-client-transaction-id", v);
@@ -213,7 +274,10 @@ impl XClient {
} else {
let tok = self.guest_token(false).await?;
h.insert("x-guest-token", HeaderValue::from_str(&tok)?);
- h.insert("Cookie", HeaderValue::from_str(&format!("guest_id=v1%3A{}", tok))?);
+ h.insert(
+ "Cookie",
+ HeaderValue::from_str(&format!("guest_id=v1%3A{}", tok))?,
+ );
}
Ok(h)
}
@@ -247,11 +311,26 @@ impl XClient {
return Ok(Err(format!("auth:{}", status.as_u16())));
}
if !status.is_success() {
- return Err(anyhow!("X {}: HTTP {} {}", op, status, text.chars().take(200).collect::<String>()));
+ return Err(anyhow!(
+ "X {}: HTTP {} {}",
+ op,
+ status,
+ text.chars().take(200).collect::<String>()
+ ));
}
- let v: Value = serde_json::from_str(&text).map_err(|e| anyhow!("X {}: resposta invalida ({})", op, e))?;
- if v.get("data").map(|d| d.is_null() || d.as_object().map(|o| o.is_empty()).unwrap_or(false)).unwrap_or(true) {
- if let Some(msg) = v.get("errors").and_then(|e| e.as_array()).and_then(|a| a.first()).and_then(|e| e.get("message")).and_then(|m| m.as_str()) {
+ let v: Value = serde_json::from_str(&text)
+ .map_err(|e| anyhow!("X {}: resposta invalida ({})", op, e))?;
+ if v.get("data")
+ .map(|d| d.is_null() || d.as_object().map(|o| o.is_empty()).unwrap_or(false))
+ .unwrap_or(true)
+ {
+ if let Some(msg) = v
+ .get("errors")
+ .and_then(|e| e.as_array())
+ .and_then(|a| a.first())
+ .and_then(|e| e.get("message"))
+ .and_then(|m| m.as_str())
+ {
if msg.contains("Query not found") || msg.contains("query_id") {
return Ok(Err("not_found".into()));
}
@@ -262,10 +341,18 @@ impl XClient {
}
async fn refresh_ids(&self) -> anyhow::Result<()> {
- super::query_ids::refresh(&self.http, self.cookie.as_deref()).await.map(|_| ())
+ super::query_ids::refresh(&self.http, self.cookie.as_deref())
+ .await
+ .map(|_| ())
}
- pub async fn gql_get(&self, op: &str, variables: Value, extra_features: Value, field_toggles: Option<Value>) -> anyhow::Result<Value> {
+ pub async fn gql_get(
+ &self,
+ op: &str,
+ variables: Value,
+ extra_features: Value,
+ field_toggles: Option<Value>,
+ ) -> anyhow::Result<Value> {
let mut features = base_features();
if let (Some(base), Some(extra)) = (features.as_object_mut(), extra_features.as_object()) {
for (k, v) in extra {
@@ -275,14 +362,24 @@ impl XClient {
let mut tries = 0;
loop {
tries += 1;
- let id = super::query_ids::id_for(op).ok_or_else(|| anyhow!("operacao {} desconhecida", op))?;
+ let id = super::query_ids::id_for(op)
+ .ok_or_else(|| anyhow!("operacao {} desconhecida", op))?;
let (url, path) = self.gql_url(&id, op);
- let mut query: Vec<(&str, String)> = vec![("variables", variables.to_string()), ("features", features.to_string())];
+ let mut query: Vec<(&str, String)> = vec![
+ ("variables", variables.to_string()),
+ ("features", features.to_string()),
+ ];
if let Some(ft) = &field_toggles {
query.push(("fieldToggles", ft.to_string()));
}
let headers = self.headers("GET", &path).await?;
- let resp = self.http.get(&url).headers(headers).query(&query).send().await?;
+ let resp = self
+ .http
+ .get(&url)
+ .headers(headers)
+ .query(&query)
+ .send()
+ .await?;
match Self::check(resp, op).await? {
Ok(v) => return Ok(v),
Err(kind) if tries < 3 => {
@@ -292,7 +389,11 @@ impl XClient {
} else if !self.authed() {
self.guest_token(true).await?;
} else {
- return Err(anyhow!("X {}: HTTP {} (sessao expirada? entre de novo no X)", op, kind.trim_start_matches("auth:")));
+ return Err(anyhow!(
+ "X {}: HTTP {} (sessao expirada? entre de novo no X)",
+ op,
+ kind.trim_start_matches("auth:")
+ ));
}
}
Err(kind) => return Err(anyhow!("X {}: {}", op, kind)),
@@ -300,19 +401,31 @@ impl XClient {
}
}
- pub async fn gql_post(&self, op: &str, variables: Value, features: Option<Value>) -> anyhow::Result<Value> {
+ pub async fn gql_post(
+ &self,
+ op: &str,
+ variables: Value,
+ features: Option<Value>,
+ ) -> anyhow::Result<Value> {
self.require_login()?;
let mut tries = 0;
loop {
tries += 1;
- let id = super::query_ids::id_for(op).ok_or_else(|| anyhow!("operacao {} desconhecida", op))?;
+ let id = super::query_ids::id_for(op)
+ .ok_or_else(|| anyhow!("operacao {} desconhecida", op))?;
let (url, path) = self.gql_url(&id, op);
let mut body = json!({ "variables": variables, "queryId": id });
if let Some(f) = &features {
body["features"] = f.clone();
}
let headers = self.headers("POST", &path).await?;
- let resp = self.http.post(&url).headers(headers).json(&body).send().await?;
+ let resp = self
+ .http
+ .post(&url)
+ .headers(headers)
+ .json(&body)
+ .send()
+ .await?;
match Self::check(resp, op).await? {
Ok(v) => return Ok(v),
Err(kind) if kind == "not_found" && tries < 2 => self.refresh_ids().await?,
@@ -327,8 +440,17 @@ impl XClient {
let full = format!("/i/api/1.1/{}", path.trim_start_matches('/'));
let url = format!("https://x.com{}", full);
let mut headers = self.headers("POST", &full).await?;
- headers.insert("Content-Type", HeaderValue::from_static("application/x-www-form-urlencoded"));
- let resp = self.http.post(&url).headers(headers).form(form).send().await?;
+ headers.insert(
+ "Content-Type",
+ HeaderValue::from_static("application/x-www-form-urlencoded"),
+ );
+ let resp = self
+ .http
+ .post(&url)
+ .headers(headers)
+ .form(form)
+ .send()
+ .await?;
match Self::check(resp, path).await? {
Ok(v) => Ok(v),
Err(kind) => Err(anyhow!("X {}: {}", path, kind)),
@@ -337,24 +459,44 @@ impl XClient {
/// POST JSON cru (Grok `add_response.json`); devolve a resposta para o
/// chamador ler o stream.
- pub async fn post_json_raw(&self, url: &str, body: &Value, extra: &[(&str, &str)]) -> anyhow::Result<reqwest::Response> {
+ pub async fn post_json_raw(
+ &self,
+ url: &str,
+ body: &Value,
+ extra: &[(&str, &str)],
+ ) -> anyhow::Result<reqwest::Response> {
self.require_login()?;
- let path = url::Url::parse(url).map(|u| u.path().to_string()).unwrap_or_default();
+ let path = url::Url::parse(url)
+ .map(|u| u.path().to_string())
+ .unwrap_or_default();
let mut headers = self.headers("POST", &path).await?;
headers.insert("Content-Type", HeaderValue::from_static("application/json"));
for (k, v) in extra {
- if let (Ok(name), Ok(val)) = (reqwest::header::HeaderName::from_bytes(k.as_bytes()), HeaderValue::from_str(v)) {
+ if let (Ok(name), Ok(val)) = (
+ reqwest::header::HeaderName::from_bytes(k.as_bytes()),
+ HeaderValue::from_str(v),
+ ) {
headers.insert(name, val);
}
}
- let resp = self.http.post(url).headers(headers).json(body).send().await?;
+ let resp = self
+ .http
+ .post(url)
+ .headers(headers)
+ .json(body)
+ .send()
+ .await?;
if resp.status().as_u16() == 429 {
return Err(anyhow!("X_RATE_LIMIT:60"));
}
if !resp.status().is_success() {
let st = resp.status();
let text = resp.text().await.unwrap_or_default();
- return Err(anyhow!("X: HTTP {} {}", st, text.chars().take(300).collect::<String>()));
+ return Err(anyhow!(
+ "X: HTTP {} {}",
+ st,
+ text.chars().take(300).collect::<String>()
+ ));
}
Ok(resp)
}
@@ -362,7 +504,15 @@ impl XClient {
/// Pagina uma timeline: `on_page` recebe a resposta e devolve quantos
/// itens novos extraiu. Para no fim, no limite, em 3 paginas vazias, em
/// cursor repetido ou quando `job` for cancelado.
- pub async fn paginate<F>(&self, op: &str, mut variables: Value, extra_features: Value, limit: usize, job: &str, mut on_page: F) -> anyhow::Result<usize>
+ pub async fn paginate<F>(
+ &self,
+ op: &str,
+ mut variables: Value,
+ extra_features: Value,
+ limit: usize,
+ job: &str,
+ mut on_page: F,
+ ) -> anyhow::Result<usize>
where
F: FnMut(&Value) -> usize,
{
@@ -377,7 +527,9 @@ impl XClient {
if let Some(c) = &cursor {
variables["cursor"] = Value::String(c.clone());
}
- let page = self.gql_get(op, variables.clone(), extra_features.clone(), None).await?;
+ let page = self
+ .gql_get(op, variables.clone(), extra_features.clone(), None)
+ .await?;
let got = on_page(&page);
total += got;
let next = super::parse::bottom_cursor(&page);
@@ -390,7 +542,14 @@ impl XClient {
empty = 0;
}
match next {
- Some(c) if Some(&c) != cursor.as_ref() && empty < 3 && !stalled && (limit == 0 || total < limit) => cursor = Some(c),
+ Some(c)
+ if Some(&c) != cursor.as_ref()
+ && empty < 3
+ && !stalled
+ && (limit == 0 || total < limit) =>
+ {
+ cursor = Some(c)
+ }
_ => break,
}
tokio::time::sleep(Duration::from_millis(500)).await;
diff --git a/src-tauri/omniget-core/src/core/tools/x/export.rs b/src-tauri/omniget-core/src/core/tools/x/export.rs
index 2f484c1a..0ef06f78 100644
--- a/src-tauri/omniget-core/src/core/tools/x/export.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/export.rs
@@ -13,7 +13,10 @@ pub fn csv_escape(s: &str) -> String {
}
fn html_escape(s: &str) -> String {
- s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
+ s.replace('&', "&amp;")
+ .replace('<', "&lt;")
+ .replace('>', "&gt;")
+ .replace('"', "&quot;")
}
pub fn posts_csv(posts: &[XPost]) -> String {
@@ -38,7 +41,12 @@ pub fn posts_csv(posts: &[XPost]) -> String {
p.reply_to_id.clone().unwrap_or_default(),
p.quote.as_ref().map(|q| q.url.clone()).unwrap_or_default(),
];
- out.push_str(&row.iter().map(|c| csv_escape(c)).collect::<Vec<_>>().join(","));
+ out.push_str(
+ &row.iter()
+ .map(|c| csv_escape(c))
+ .collect::<Vec<_>>()
+ .join(","),
+ );
out.push('\n');
}
out
@@ -63,40 +71,81 @@ pub fn users_csv(users: &[XUser]) -> String {
u.follows_me.map(|b| b.to_string()).unwrap_or_default(),
u.followed_by_me.map(|b| b.to_string()).unwrap_or_default(),
];
- out.push_str(&row.iter().map(|c| csv_escape(c)).collect::<Vec<_>>().join(","));
+ out.push_str(
+ &row.iter()
+ .map(|c| csv_escape(c))
+ .collect::<Vec<_>>()
+ .join(","),
+ );
out.push('\n');
}
out
}
fn date_short(iso: &str) -> String {
- iso.get(..16).map(|s| s.replace('T', " ")).unwrap_or_else(|| iso.to_string())
+ iso.get(..16)
+ .map(|s| s.replace('T', " "))
+ .unwrap_or_else(|| iso.to_string())
}
pub fn posts_markdown(title: &str, posts: &[XPost]) -> String {
let mut out = format!("# {}\n\n", title);
if let Some(first) = posts.first() {
- out.push_str(&format!("**{}** (@{}) · {}\n\n", first.author.name, first.author.handle, first.url));
+ out.push_str(&format!(
+ "**{}** (@{}) · {}\n\n",
+ first.author.name, first.author.handle, first.url
+ ));
}
for (i, p) in posts.iter().enumerate() {
if posts.len() > 1 {
- out.push_str(&format!("### {}/{} · {}\n\n", i + 1, posts.len(), date_short(&p.created_at)));
+ out.push_str(&format!(
+ "### {}/{} · {}\n\n",
+ i + 1,
+ posts.len(),
+ date_short(&p.created_at)
+ ));
}
- if posts.len() > 1 && posts.first().map(|f| f.author.handle != p.author.handle).unwrap_or(false) {
+ if posts.len() > 1
+ && posts
+ .first()
+ .map(|f| f.author.handle != p.author.handle)
+ .unwrap_or(false)
+ {
out.push_str(&format!("_@{}_\n\n", p.author.handle));
}
out.push_str(p.text.trim());
out.push_str("\n\n");
for m in &p.media {
match m.kind.as_str() {
- "photo" => out.push_str(&format!("![{}]({})\n\n", if m.alt.is_empty() { "imagem" } else { &m.alt }, m.url)),
+ "photo" => out.push_str(&format!(
+ "![{}]({})\n\n",
+ if m.alt.is_empty() { "imagem" } else { &m.alt },
+ m.url
+ )),
_ => out.push_str(&format!("[{}]({})\n\n", m.kind, m.url)),
}
}
if let Some(q) = &p.quote {
- out.push_str(&format!("> **@{}**: {}\n> {}\n\n", q.author.handle, q.text.replace('\n', "\n> "), q.url));
+ out.push_str(&format!(
+ "> **@{}**: {}\n> {}\n\n",
+ q.author.handle,
+ q.text.replace('\n', "\n> "),
+ q.url
+ ));
}
- out.push_str(&format!("♥ {} · ↻ {} · 💬 {}{} · [{}]({})\n\n", p.likes, p.reposts, p.replies, if p.views > 0 { format!(" · 👁 {}", p.views) } else { String::new() }, p.id, p.url));
+ out.push_str(&format!(
+ "♥ {} · ↻ {} · 💬 {}{} · [{}]({})\n\n",
+ p.likes,
+ p.reposts,
+ p.replies,
+ if p.views > 0 {
+ format!(" · 👁 {}", p.views)
+ } else {
+ String::new()
+ },
+ p.id,
+ p.url
+ ));
}
out.trim_end().to_string() + "\n"
}
@@ -104,7 +153,15 @@ pub fn posts_markdown(title: &str, posts: &[XPost]) -> String {
pub fn posts_text(posts: &[XPost]) -> String {
posts
.iter()
- .map(|p| format!("@{} · {}\n{}\n{}", p.author.handle, date_short(&p.created_at), p.text.trim(), p.url))
+ .map(|p| {
+ format!(
+ "@{} · {}\n{}\n{}",
+ p.author.handle,
+ date_short(&p.created_at),
+ p.text.trim(),
+ p.url
+ )
+ })
.collect::<Vec<_>>()
.join("\n\n---\n\n")
+ "\n"
@@ -116,14 +173,30 @@ pub fn posts_html(title: &str, posts: &[XPost]) -> String {
let mut media = String::new();
for m in &p.media {
match m.kind.as_str() {
- "photo" => media.push_str(&format!("<a href=\"{0}\"><img src=\"{0}\" alt=\"{1}\" loading=\"lazy\"></a>", html_escape(&m.url), html_escape(&m.alt))),
- _ => media.push_str(&format!("<video src=\"{}\" poster=\"{}\" controls preload=\"none\"></video>", html_escape(&m.url), html_escape(&m.thumb))),
+ "photo" => media.push_str(&format!(
+ "<a href=\"{0}\"><img src=\"{0}\" alt=\"{1}\" loading=\"lazy\"></a>",
+ html_escape(&m.url),
+ html_escape(&m.alt)
+ )),
+ _ => media.push_str(&format!(
+ "<video src=\"{}\" poster=\"{}\" controls preload=\"none\"></video>",
+ html_escape(&m.url),
+ html_escape(&m.thumb)
+ )),
}
}
let quote = p
.quote
.as_ref()
- .map(|q| format!("<blockquote><b>@{}</b> {}<br><a href=\"{}\">{}</a></blockquote>", html_escape(&q.author.handle), html_escape(&q.text).replace('\n', "<br>"), html_escape(&q.url), html_escape(&q.url)))
+ .map(|q| {
+ format!(
+ "<blockquote><b>@{}</b> {}<br><a href=\"{}\">{}</a></blockquote>",
+ html_escape(&q.author.handle),
+ html_escape(&q.text).replace('\n', "<br>"),
+ html_escape(&q.url),
+ html_escape(&q.url)
+ )
+ })
.unwrap_or_default();
body.push_str(&format!(
"<article><header><img class=\"avatar\" src=\"{}\" alt=\"\"><div><b>{}</b> <span class=\"h\">@{}</span><br><time>{}</time></div></header><p>{}</p><div class=\"media\">{}</div>{}<footer>♥ {} · ↻ {} · 💬 {} · 👁 {} · <a href=\"{}\">abrir no X</a></footer></article>\n",
@@ -149,7 +222,12 @@ pub fn posts_html(title: &str, posts: &[XPost]) -> String {
}
/// Escreve `posts` em `dest` no formato pedido e devolve o caminho.
-pub fn write_posts(posts: &[XPost], format: &str, dest: &std::path::Path, title: &str) -> anyhow::Result<String> {
+pub fn write_posts(
+ posts: &[XPost],
+ format: &str,
+ dest: &std::path::Path,
+ title: &str,
+) -> anyhow::Result<String> {
let content = match format {
"json" => serde_json::to_string_pretty(posts)?,
"csv" => posts_csv(posts),
@@ -165,11 +243,22 @@ pub fn write_posts(posts: &[XPost], format: &str, dest: &std::path::Path, title:
Ok(dest.to_string_lossy().to_string())
}
-pub fn write_users(users: &[XUser], format: &str, dest: &std::path::Path) -> anyhow::Result<String> {
+pub fn write_users(
+ users: &[XUser],
+ format: &str,
+ dest: &std::path::Path,
+) -> anyhow::Result<String> {
let content = match format {
"json" => serde_json::to_string_pretty(users)?,
"csv" => users_csv(users),
- "md" | "markdown" | "txt" => users.iter().map(|u| format!("- @{} · {} · {}", u.handle, u.name, u.url())).collect::<Vec<_>>().join("\n") + "\n",
+ "md" | "markdown" | "txt" => {
+ users
+ .iter()
+ .map(|u| format!("- @{} · {} · {}", u.handle, u.name, u.url()))
+ .collect::<Vec<_>>()
+ .join("\n")
+ + "\n"
+ }
other => anyhow::bail!("formato desconhecido: {}", other),
};
if let Some(parent) = dest.parent() {
diff --git a/src-tauri/omniget-core/src/core/tools/x/follows.rs b/src-tauri/omniget-core/src/core/tools/x/follows.rs
index f355b393..b6033dce 100644
--- a/src-tauri/omniget-core/src/core/tools/x/follows.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/follows.rs
@@ -30,11 +30,18 @@ fn whitelist_path() -> std::path::PathBuf {
}
pub fn whitelist() -> Vec<String> {
- std::fs::read_to_string(whitelist_path()).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
+ std::fs::read_to_string(whitelist_path())
+ .ok()
+ .and_then(|s| serde_json::from_str(&s).ok())
+ .unwrap_or_default()
}
pub fn set_whitelist(handles: &[String]) -> anyhow::Result<Vec<String>> {
- let mut clean: Vec<String> = handles.iter().map(|h| h.trim().trim_start_matches('@').to_ascii_lowercase()).filter(|h| !h.is_empty()).collect();
+ let mut clean: Vec<String> = handles
+ .iter()
+ .map(|h| h.trim().trim_start_matches('@').to_ascii_lowercase())
+ .filter(|h| !h.is_empty())
+ .collect();
clean.sort();
clean.dedup();
std::fs::write(whitelist_path(), serde_json::to_string_pretty(&clean)?)?;
@@ -50,18 +57,26 @@ fn today() -> String {
}
pub fn unfollowed_today() -> usize {
- let log: std::collections::HashMap<String, usize> = std::fs::read_to_string(log_path()).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
+ let log: std::collections::HashMap<String, usize> = std::fs::read_to_string(log_path())
+ .ok()
+ .and_then(|s| serde_json::from_str(&s).ok())
+ .unwrap_or_default();
log.get(&today()).copied().unwrap_or(0)
}
fn bump_today() {
- let mut log: std::collections::HashMap<String, usize> = std::fs::read_to_string(log_path()).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
+ let mut log: std::collections::HashMap<String, usize> = std::fs::read_to_string(log_path())
+ .ok()
+ .and_then(|s| serde_json::from_str(&s).ok())
+ .unwrap_or_default();
*log.entry(today()).or_default() += 1;
let _ = std::fs::write(log_path(), serde_json::to_string(&log).unwrap_or_default());
}
pub async fn me(client: &XClient) -> anyhow::Result<XUser> {
- let uid = client.user_id().ok_or_else(|| anyhow!("cookie twid ausente: entre de novo no X"))?;
+ let uid = client
+ .user_id()
+ .ok_or_else(|| anyhow!("cookie twid ausente: entre de novo no X"))?;
let v = client
.gql_get(
"UserByRestId",
@@ -70,24 +85,47 @@ pub async fn me(client: &XClient) -> anyhow::Result<XUser> {
None,
)
.await?;
- v.pointer("/data/user/result").and_then(super::parse::parse_user).ok_or_else(|| anyhow!("nao consegui ler o perfil da sessao"))
+ v.pointer("/data/user/result")
+ .and_then(super::parse::parse_user)
+ .ok_or_else(|| anyhow!("nao consegui ler o perfil da sessao"))
}
-async fn list(client: &XClient, op: &str, uid: &str, limit: usize, progress: &ProgressFn, stage: &str) -> anyhow::Result<Vec<XUser>> {
+async fn list(
+ client: &XClient,
+ op: &str,
+ uid: &str,
+ limit: usize,
+ progress: &ProgressFn,
+ stage: &str,
+) -> anyhow::Result<Vec<XUser>> {
let mut users: Vec<XUser> = Vec::new();
- let extra = if op == "Followers" { json!({ "responsive_web_twitter_article_notes_tab_enabled": false }) } else { json!({}) };
+ let extra = if op == "Followers" {
+ json!({ "responsive_web_twitter_article_notes_tab_enabled": false })
+ } else {
+ json!({})
+ };
let p2 = progress.clone();
client
- .paginate(op, json!({ "userId": uid, "count": 100, "includePromotedContent": false }), extra, limit, JOB, |page| {
- let got = super::parse::users_from(page);
- let n = got.len();
- users.extend(got);
- super::report(&p2, JOB, stage, users.len() as u64, None, None);
- n
- })
+ .paginate(
+ op,
+ json!({ "userId": uid, "count": 100, "includePromotedContent": false }),
+ extra,
+ limit,
+ JOB,
+ |page| {
+ let got = super::parse::users_from(page);
+ let n = got.len();
+ users.extend(got);
+ super::report(&p2, JOB, stage, users.len() as u64, None, None);
+ n
+ },
+ )
.await?;
let mut seen = std::collections::HashSet::new();
- Ok(users.into_iter().filter(|u| seen.insert(u.id.clone())).collect())
+ Ok(users
+ .into_iter()
+ .filter(|u| seen.insert(u.id.clone()))
+ .collect())
}
pub async fn audit(limit: usize, progress: ProgressFn) -> anyhow::Result<Audit> {
@@ -97,9 +135,15 @@ pub async fn audit(limit: usize, progress: ProgressFn) -> anyhow::Result<Audit>
let me = me(&client).await?;
let limit = if limit == 0 { 10_000 } else { limit };
let following = list(&client, "Following", &me.id, limit, &progress, "following").await?;
- let followers = if super::cancelled(JOB) { Vec::new() } else { list(&client, "Followers", &me.id, limit, &progress, "followers").await? };
- let follower_ids: std::collections::HashSet<&str> = followers.iter().map(|u| u.id.as_str()).collect();
- let following_ids: std::collections::HashSet<&str> = following.iter().map(|u| u.id.as_str()).collect();
+ let followers = if super::cancelled(JOB) {
+ Vec::new()
+ } else {
+ list(&client, "Followers", &me.id, limit, &progress, "followers").await?
+ };
+ let follower_ids: std::collections::HashSet<&str> =
+ followers.iter().map(|u| u.id.as_str()).collect();
+ let following_ids: std::collections::HashSet<&str> =
+ following.iter().map(|u| u.id.as_str()).collect();
let wl = whitelist();
let not_following_back: Vec<XUser> = following
.iter()
@@ -107,9 +151,23 @@ pub async fn audit(limit: usize, progress: ProgressFn) -> anyhow::Result<Audit>
.filter(|u| !wl.contains(&u.handle.to_ascii_lowercase()))
.cloned()
.collect();
- let fans: Vec<XUser> = followers.iter().filter(|u| !following_ids.contains(u.id.as_str()) && u.followed_by_me != Some(true)).cloned().collect();
- let mutuals = following.iter().filter(|u| follower_ids.contains(u.id.as_str()) || u.follows_me == Some(true)).count();
- super::report(&progress, JOB, "done", following.len() as u64, Some(following.len() as u64), None);
+ let fans: Vec<XUser> = followers
+ .iter()
+ .filter(|u| !following_ids.contains(u.id.as_str()) && u.followed_by_me != Some(true))
+ .cloned()
+ .collect();
+ let mutuals = following
+ .iter()
+ .filter(|u| follower_ids.contains(u.id.as_str()) || u.follows_me == Some(true))
+ .count();
+ super::report(
+ &progress,
+ JOB,
+ "done",
+ following.len() as u64,
+ Some(following.len() as u64),
+ None,
+ );
Ok(Audit {
me,
following: following.len(),
@@ -131,7 +189,13 @@ pub struct UnfollowResult {
pub reason: String,
}
-pub async fn unfollow(ids: &[String], min_delay: u64, max_delay: u64, daily_cap: usize, progress: ProgressFn) -> anyhow::Result<UnfollowResult> {
+pub async fn unfollow(
+ ids: &[String],
+ min_delay: u64,
+ max_delay: u64,
+ daily_cap: usize,
+ progress: ProgressFn,
+) -> anyhow::Result<UnfollowResult> {
let client = XClient::new()?;
client.require_login()?;
super::clear_cancel(UNFOLLOW_JOB);
@@ -149,7 +213,14 @@ pub async fn unfollow(ids: &[String], min_delay: u64, max_delay: u64, daily_cap:
r.reason = "daily_cap".into();
break;
}
- super::report(&progress, UNFOLLOW_JOB, "unfollow", i as u64, Some(total), Some(id.clone()));
+ super::report(
+ &progress,
+ UNFOLLOW_JOB,
+ "unfollow",
+ i as u64,
+ Some(total),
+ Some(id.clone()),
+ );
let form = [
("include_profile_interstitial_type", "1"),
("include_blocking", "1"),
@@ -165,7 +236,10 @@ pub async fn unfollow(ids: &[String], min_delay: u64, max_delay: u64, daily_cap:
("skip_status", "1"),
("user_id", id.as_str()),
];
- match client.rest_post_form("friendships/destroy.json", &form).await {
+ match client
+ .rest_post_form("friendships/destroy.json", &form)
+ .await
+ {
Ok(_) => {
r.done.push(id.clone());
bump_today();
@@ -186,11 +260,25 @@ pub async fn unfollow(ids: &[String], min_delay: u64, max_delay: u64, daily_cap:
if super::cancelled(UNFOLLOW_JOB) {
break;
}
- super::report(&progress, UNFOLLOW_JOB, "waiting", (i + 1) as u64, Some(total), Some((wait - s).to_string()));
+ super::report(
+ &progress,
+ UNFOLLOW_JOB,
+ "waiting",
+ (i + 1) as u64,
+ Some(total),
+ Some((wait - s).to_string()),
+ );
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
}
}
}
- super::report(&progress, UNFOLLOW_JOB, "done", r.done.len() as u64, Some(total), None);
+ super::report(
+ &progress,
+ UNFOLLOW_JOB,
+ "done",
+ r.done.len() as u64,
+ Some(total),
+ None,
+ );
Ok(r)
}
diff --git a/src-tauri/omniget-core/src/core/tools/x/fx.rs b/src-tauri/omniget-core/src/core/tools/x/fx.rs
index 073e077d..d70704a6 100644
--- a/src-tauri/omniget-core/src/core/tools/x/fx.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/fx.rs
@@ -14,25 +14,40 @@ const BASE: &str = "https://api.fxtwitter.com/2";
fn client() -> anyhow::Result<reqwest::Client> {
use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT};
let mut headers = HeaderMap::new();
- headers.insert(USER_AGENT, HeaderValue::from_static("OmniGet/0.9 (+https://github.com/tonhowtf/omniget)"));
- Ok(crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .default_headers(headers)
- .timeout(std::time::Duration::from_secs(60))
- .build()?)
+ headers.insert(
+ USER_AGENT,
+ HeaderValue::from_static("OmniGet/0.9 (+https://github.com/tonhowtf/omniget)"),
+ );
+ Ok(
+ crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .default_headers(headers)
+ .timeout(std::time::Duration::from_secs(60))
+ .build()?,
+ )
}
async fn get(path: &str, query: &[(&str, String)]) -> anyhow::Result<Value> {
let client = client()?;
let url = format!("{}/{}", BASE, path.trim_start_matches('/'));
let mut req = client.get(&url);
- let q: Vec<(&str, &str)> = query.iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| (*k, v.as_str())).collect();
+ let q: Vec<(&str, &str)> = query
+ .iter()
+ .filter(|(_, v)| !v.is_empty())
+ .map(|(k, v)| (*k, v.as_str()))
+ .collect();
if !q.is_empty() {
req = req.query(&q);
}
let resp = req.send().await?;
let status = resp.status();
- let body: Value = resp.json().await.map_err(|e| anyhow!("FxTwitter: resposta invalida ({})", e))?;
- let code = body.get("code").and_then(|c| c.as_u64()).unwrap_or(status.as_u16() as u64);
+ let body: Value = resp
+ .json()
+ .await
+ .map_err(|e| anyhow!("FxTwitter: resposta invalida ({})", e))?;
+ let code = body
+ .get("code")
+ .and_then(|c| c.as_u64())
+ .unwrap_or(status.as_u16() as u64);
if code == 404 {
return Err(anyhow!("nao encontrado no X (ou o post e privado)"));
}
@@ -40,10 +55,15 @@ async fn get(path: &str, query: &[(&str, String)]) -> anyhow::Result<Value> {
return Err(anyhow!("post ou perfil privado"));
}
if code == 429 {
- return Err(anyhow!("FxTwitter: limite de requisicoes atingido, tente de novo em instantes"));
+ return Err(anyhow!(
+ "FxTwitter: limite de requisicoes atingido, tente de novo em instantes"
+ ));
}
if code >= 400 {
- let msg = body.get("message").and_then(|m| m.as_str()).unwrap_or("erro");
+ let msg = body
+ .get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("erro");
return Err(anyhow!("FxTwitter: {} ({})", msg, code));
}
Ok(body)
@@ -54,7 +74,9 @@ fn s(v: &Value, k: &str) -> String {
}
fn n(v: &Value, k: &str) -> u64 {
- v.get(k).and_then(|x| x.as_u64().or_else(|| x.as_f64().map(|f| f.max(0.0) as u64))).unwrap_or(0)
+ v.get(k)
+ .and_then(|x| x.as_u64().or_else(|| x.as_f64().map(|f| f.max(0.0) as u64)))
+ .unwrap_or(0)
}
pub fn user_from(v: &Value) -> XUser {
@@ -66,15 +88,29 @@ pub fn user_from(v: &Value) -> XUser {
banner: s(v, "banner_url"),
bio: s(v, "description"),
location: s(v, "location"),
- website: v.get("website").and_then(|w| w.get("url")).and_then(|u| u.as_str()).unwrap_or("").to_string(),
- joined: super::parse_twitter_date(&s(v, "joined")).map(|(iso, _)| iso).unwrap_or_default(),
+ website: v
+ .get("website")
+ .and_then(|w| w.get("url"))
+ .and_then(|u| u.as_str())
+ .unwrap_or("")
+ .to_string(),
+ joined: super::parse_twitter_date(&s(v, "joined"))
+ .map(|(iso, _)| iso)
+ .unwrap_or_default(),
followers: n(v, "followers"),
following: n(v, "following"),
posts: n(v, "statuses"),
likes: n(v, "likes"),
media_count: n(v, "media_count"),
- verified: v.get("verification").and_then(|x| x.get("verified")).and_then(|b| b.as_bool()).unwrap_or(false),
- protected: v.get("protected").and_then(|b| b.as_bool()).unwrap_or(false),
+ verified: v
+ .get("verification")
+ .and_then(|x| x.get("verified"))
+ .and_then(|b| b.as_bool())
+ .unwrap_or(false),
+ protected: v
+ .get("protected")
+ .and_then(|b| b.as_bool())
+ .unwrap_or(false),
followed_by_me: None,
follows_me: None,
}
@@ -82,10 +118,21 @@ pub fn user_from(v: &Value) -> XUser {
fn media_from(v: &Value) -> Vec<XMedia> {
let mut out = Vec::new();
- let Some(media) = v.get("media") else { return out };
- for p in media.get("photos").and_then(|a| a.as_array()).into_iter().flatten() {
+ let Some(media) = v.get("media") else {
+ return out;
+ };
+ for p in media
+ .get("photos")
+ .and_then(|a| a.as_array())
+ .into_iter()
+ .flatten()
+ {
out.push(XMedia {
- kind: if s(p, "type") == "gif" { "gif".into() } else { "photo".into() },
+ kind: if s(p, "type") == "gif" {
+ "gif".into()
+ } else {
+ "photo".into()
+ },
url: super::photo_orig_url(&s(p, "url")),
thumb: s(p, "url"),
width: n(p, "width") as u32,
@@ -94,11 +141,21 @@ fn media_from(v: &Value) -> Vec<XMedia> {
alt: s(p, "altText"),
});
}
- for vd in media.get("videos").and_then(|a| a.as_array()).into_iter().flatten() {
+ for vd in media
+ .get("videos")
+ .and_then(|a| a.as_array())
+ .into_iter()
+ .flatten()
+ {
// o melhor mp4 e o de maior bitrate; `url` ja costuma ser ele
let mut best = s(vd, "url");
let mut best_rate = 0u64;
- for f in vd.get("formats").and_then(|a| a.as_array()).into_iter().flatten() {
+ for f in vd
+ .get("formats")
+ .and_then(|a| a.as_array())
+ .into_iter()
+ .flatten()
+ {
if s(f, "container") == "mp4" {
let br = n(f, "bitrate");
if br > best_rate {
@@ -108,12 +165,17 @@ fn media_from(v: &Value) -> Vec<XMedia> {
}
}
out.push(XMedia {
- kind: if s(vd, "type") == "gif" { "gif".into() } else { "video".into() },
+ kind: if s(vd, "type") == "gif" {
+ "gif".into()
+ } else {
+ "video".into()
+ },
url: best,
thumb: s(vd, "thumbnail_url"),
width: n(vd, "width") as u32,
height: n(vd, "height") as u32,
- duration_ms: (vd.get("duration").and_then(|d| d.as_f64()).unwrap_or(0.0) * 1000.0) as u64,
+ duration_ms: (vd.get("duration").and_then(|d| d.as_f64()).unwrap_or(0.0) * 1000.0)
+ as u64,
alt: String::new(),
});
}
@@ -123,10 +185,21 @@ fn media_from(v: &Value) -> Vec<XMedia> {
fn extract_entities(text: &str, raw: &Value) -> (Vec<String>, Vec<String>, Vec<String>) {
let re_tag = regex::Regex::new(r"#([\p{L}\p{N}_]+)").unwrap();
let re_at = regex::Regex::new(r"@([A-Za-z0-9_]{1,15})").unwrap();
- let hashtags = re_tag.captures_iter(text).map(|c| c[1].to_string()).collect();
- let mentions = re_at.captures_iter(text).map(|c| c[1].to_string()).collect();
+ let hashtags = re_tag
+ .captures_iter(text)
+ .map(|c| c[1].to_string())
+ .collect();
+ let mentions = re_at
+ .captures_iter(text)
+ .map(|c| c[1].to_string())
+ .collect();
let mut links = Vec::new();
- for f in raw.get("facets").and_then(|a| a.as_array()).into_iter().flatten() {
+ for f in raw
+ .get("facets")
+ .and_then(|a| a.as_array())
+ .into_iter()
+ .flatten()
+ {
if s(f, "type") == "url" {
let r = s(f, "replacement");
if !r.is_empty() {
@@ -148,16 +221,25 @@ pub fn post_from(v: &Value) -> Option<XPost> {
let text = s(v, "text");
let raw = v.get("raw_text").cloned().unwrap_or(Value::Null);
let (hashtags, mentions, links) = extract_entities(&text, &raw);
- let ts = v.get("created_timestamp").and_then(|t| t.as_i64()).unwrap_or(0);
+ let ts = v
+ .get("created_timestamp")
+ .and_then(|t| t.as_i64())
+ .unwrap_or(0);
let created_at = if ts > 0 {
super::iso_from_timestamp(ts)
} else {
- super::parse_twitter_date(&s(v, "created_at")).map(|(iso, _)| iso).unwrap_or_default()
+ super::parse_twitter_date(&s(v, "created_at"))
+ .map(|(iso, _)| iso)
+ .unwrap_or_default()
};
let replying = v.get("replying_to").filter(|r| r.is_object());
Some(XPost {
id: id.clone(),
- url: if s(v, "url").is_empty() { format!("https://x.com/i/status/{}", id) } else { s(v, "url") },
+ url: if s(v, "url").is_empty() {
+ format!("https://x.com/i/status/{}", id)
+ } else {
+ s(v, "url")
+ },
text,
created_at,
timestamp: ts,
@@ -172,9 +254,14 @@ pub fn post_from(v: &Value) -> Option<XPost> {
media: media_from(v),
quote: v.get("quote").and_then(post_from).map(Box::new),
reply_to_id: replying.map(|r| s(r, "status")).filter(|x| !x.is_empty()),
- reply_to_handle: replying.map(|r| s(r, "screen_name")).filter(|x| !x.is_empty()),
+ reply_to_handle: replying
+ .map(|r| s(r, "screen_name"))
+ .filter(|x| !x.is_empty()),
conversation_id: None,
- reposted_by: v.get("reposted_by").filter(|r| r.is_object()).map(|r| s(r, "screen_name")),
+ reposted_by: v
+ .get("reposted_by")
+ .filter(|r| r.is_object())
+ .map(|r| s(r, "screen_name")),
source: s(v, "source"),
hashtags,
mentions,
@@ -190,7 +277,12 @@ pub struct Page<T> {
fn bottom_cursor(v: &Value) -> Option<String> {
v.get("cursor")
- .and_then(|c| c.get("bottom").and_then(|b| b.as_str()).map(|x| x.to_string()).or_else(|| c.as_str().map(|x| x.to_string())))
+ .and_then(|c| {
+ c.get("bottom")
+ .and_then(|b| b.as_str())
+ .map(|x| x.to_string())
+ .or_else(|| c.as_str().map(|x| x.to_string()))
+ })
.filter(|c| !c.is_empty())
}
@@ -202,32 +294,54 @@ fn results_page(v: &Value) -> Page<XPost> {
.flatten()
.filter_map(post_from)
.collect();
- Page { items, cursor: bottom_cursor(v) }
+ Page {
+ items,
+ cursor: bottom_cursor(v),
+ }
}
pub async fn status(id: &str) -> anyhow::Result<XPost> {
let v = get(&format!("status/{}", id), &[]).await?;
- v.get("status").and_then(post_from).ok_or_else(|| anyhow!("post indisponivel"))
+ v.get("status")
+ .and_then(post_from)
+ .ok_or_else(|| anyhow!("post indisponivel"))
}
/// Thread do autor (o proprio FxTwitter monta a sequencia). Devolve o post
/// focal e a lista completa (vazia quando nao e thread).
pub async fn thread(id: &str) -> anyhow::Result<(XPost, Vec<XPost>, bool)> {
let v = get(&format!("thread/{}", id), &[]).await?;
- let focal = v.get("status").and_then(post_from).ok_or_else(|| anyhow!("post indisponivel"))?;
+ let focal = v
+ .get("status")
+ .and_then(post_from)
+ .ok_or_else(|| anyhow!("post indisponivel"))?;
let (posts, truncated) = match v.get("thread") {
Some(t) if t.is_object() => (
- t.get("statuses").and_then(|a| a.as_array()).into_iter().flatten().filter_map(post_from).collect(),
- t.get("truncated").and_then(|b| b.as_bool()).unwrap_or(false),
+ t.get("statuses")
+ .and_then(|a| a.as_array())
+ .into_iter()
+ .flatten()
+ .filter_map(post_from)
+ .collect(),
+ t.get("truncated")
+ .and_then(|b| b.as_bool())
+ .unwrap_or(false),
+ ),
+ Some(t) if t.is_array() => (
+ t.as_array().unwrap().iter().filter_map(post_from).collect(),
+ false,
),
- Some(t) if t.is_array() => (t.as_array().unwrap().iter().filter_map(post_from).collect(), false),
_ => (Vec::new(), false),
};
Ok((focal, posts, truncated))
}
pub async fn conversation(id: &str, cursor: Option<&str>) -> anyhow::Result<Page<XPost>> {
- let v = get(&format!("conversation/{}", id), &[("cursor", cursor.unwrap_or("").to_string())]).await?;
+ let v = get(
+ &format!("conversation/{}", id),
+ &[("cursor", cursor.unwrap_or("").to_string())],
+ )
+ .await?;
let items = v
.get("replies")
.and_then(|a| a.as_array())
@@ -235,21 +349,37 @@ pub async fn conversation(id: &str, cursor: Option<&str>) -> anyhow::Result<Page
.flatten()
.filter_map(post_from)
.collect();
- Ok(Page { items, cursor: bottom_cursor(&v) })
+ Ok(Page {
+ items,
+ cursor: bottom_cursor(&v),
+ })
}
pub async fn profile(handle: &str) -> anyhow::Result<XUser> {
let v = get(&format!("profile/{}", handle), &[]).await?;
- v.get("user").map(user_from).ok_or_else(|| anyhow!("perfil indisponivel"))
+ v.get("user")
+ .map(user_from)
+ .ok_or_else(|| anyhow!("perfil indisponivel"))
}
-pub async fn profile_statuses(handle: &str, cursor: Option<&str>, with_replies: bool) -> anyhow::Result<Page<XPost>> {
+pub async fn profile_statuses(
+ handle: &str,
+ cursor: Option<&str>,
+ with_replies: bool,
+) -> anyhow::Result<Page<XPost>> {
let v = get(
&format!("profile/{}/statuses", handle),
&[
("cursor", cursor.unwrap_or("").to_string()),
("count", "100".to_string()),
- ("with_replies", if with_replies { "true".to_string() } else { String::new() }),
+ (
+ "with_replies",
+ if with_replies {
+ "true".to_string()
+ } else {
+ String::new()
+ },
+ ),
],
)
.await?;
@@ -257,21 +387,50 @@ pub async fn profile_statuses(handle: &str, cursor: Option<&str>, with_replies:
}
pub async fn profile_media(handle: &str, cursor: Option<&str>) -> anyhow::Result<Page<XPost>> {
- let v = get(&format!("profile/{}/media", handle), &[("cursor", cursor.unwrap_or("").to_string()), ("count", "100".to_string())]).await?;
+ let v = get(
+ &format!("profile/{}/media", handle),
+ &[
+ ("cursor", cursor.unwrap_or("").to_string()),
+ ("count", "100".to_string()),
+ ],
+ )
+ .await?;
Ok(results_page(&v))
}
-pub async fn profile_relationship(handle: &str, which: &str, cursor: Option<&str>) -> anyhow::Result<Page<XUser>> {
- let v = get(&format!("profile/{}/{}", handle, which), &[("cursor", cursor.unwrap_or("").to_string())]).await?;
- let items = v.get("results").and_then(|a| a.as_array()).into_iter().flatten().map(user_from).collect();
- Ok(Page { items, cursor: bottom_cursor(&v) })
+pub async fn profile_relationship(
+ handle: &str,
+ which: &str,
+ cursor: Option<&str>,
+) -> anyhow::Result<Page<XUser>> {
+ let v = get(
+ &format!("profile/{}/{}", handle, which),
+ &[("cursor", cursor.unwrap_or("").to_string())],
+ )
+ .await?;
+ let items = v
+ .get("results")
+ .and_then(|a| a.as_array())
+ .into_iter()
+ .flatten()
+ .map(user_from)
+ .collect();
+ Ok(Page {
+ items,
+ cursor: bottom_cursor(&v),
+ })
}
/// `feed`: "latest" | "top" (o que a busca do X chama de Latest/Top).
pub async fn search(q: &str, feed: &str, cursor: Option<&str>) -> anyhow::Result<Page<XPost>> {
let v = get(
"search",
- &[("q", q.to_string()), ("feed", feed.to_string()), ("count", "50".to_string()), ("cursor", cursor.unwrap_or("").to_string())],
+ &[
+ ("q", q.to_string()),
+ ("feed", feed.to_string()),
+ ("count", "50".to_string()),
+ ("cursor", cursor.unwrap_or("").to_string()),
+ ],
)
.await?;
Ok(results_page(&v))
@@ -290,6 +449,10 @@ pub async fn trends() -> anyhow::Result<Vec<Trend>> {
.and_then(|a| a.as_array())
.into_iter()
.flatten()
- .map(|t| Trend { name: s(t, "name"), context: s(t, "context"), rank: t.get("rank").and_then(|r| r.as_u64()) })
+ .map(|t| Trend {
+ name: s(t, "name"),
+ context: s(t, "context"),
+ rank: t.get("rank").and_then(|r| r.as_u64()),
+ })
.collect())
}
diff --git a/src-tauri/omniget-core/src/core/tools/x/grok.rs b/src-tauri/omniget-core/src/core/tools/x/grok.rs
index 98c36836..8b4f20d3 100644
--- a/src-tauri/omniget-core/src/core/tools/x/grok.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/grok.rs
@@ -36,7 +36,10 @@ fn path() -> std::path::PathBuf {
}
pub fn config() -> GrokConfig {
- let mut c: GrokConfig = std::fs::read_to_string(path()).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
+ let mut c: GrokConfig = std::fs::read_to_string(path())
+ .ok()
+ .and_then(|s| serde_json::from_str(&s).ok())
+ .unwrap_or_default();
if c.xai_model.is_empty() {
c.xai_model = DEFAULT_XAI_MODEL.into();
}
@@ -48,11 +51,19 @@ pub fn config() -> GrokConfig {
pub fn view() -> GrokConfigView {
let c = config();
- GrokConfigView { has_xai_key: !c.xai_key.is_empty(), xai_model: c.xai_model, x_model: c.x_model }
+ GrokConfigView {
+ has_xai_key: !c.xai_key.is_empty(),
+ xai_model: c.xai_model,
+ x_model: c.x_model,
+ }
}
/// `xai_key`: `None` mantem, `Some("")` apaga.
-pub fn set(xai_key: Option<String>, xai_model: Option<String>, x_model: Option<String>) -> anyhow::Result<GrokConfigView> {
+pub fn set(
+ xai_key: Option<String>,
+ xai_model: Option<String>,
+ x_model: Option<String>,
+) -> anyhow::Result<GrokConfigView> {
let mut c = config();
if let Some(k) = xai_key {
c.xai_key = k.trim().to_string();
@@ -129,11 +140,21 @@ async fn ask_xai(cfg: &GrokConfig, req: GrokRequest) -> anyhow::Result<GrokAnswe
if cfg.xai_key.is_empty() {
anyhow::bail!("GROK_NO_KEY");
}
- let model = if req.model.trim().is_empty() { cfg.xai_model.clone() } else { req.model.trim().to_string() };
+ let model = if req.model.trim().is_empty() {
+ cfg.xai_model.clone()
+ } else {
+ req.model.trim().to_string()
+ };
let mut tools = Vec::new();
if req.x_search {
let mut t = json!({ "type": "x_search" });
- let handles: Vec<String> = req.handles.iter().map(|h| h.trim().trim_start_matches('@').to_string()).filter(|h| !h.is_empty()).take(20).collect();
+ let handles: Vec<String> = req
+ .handles
+ .iter()
+ .map(|h| h.trim().trim_start_matches('@').to_string())
+ .filter(|h| !h.is_empty())
+ .take(20)
+ .collect();
if !handles.is_empty() {
t["allowed_x_handles"] = json!(handles);
}
@@ -155,52 +176,120 @@ async fn ask_xai(cfg: &GrokConfig, req: GrokRequest) -> anyhow::Result<GrokAnswe
if !tools.is_empty() {
body["tools"] = json!(tools);
}
- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder()).timeout(std::time::Duration::from_secs(180)).build()?;
- let resp = client.post("https://api.x.ai/v1/responses").bearer_auth(&cfg.xai_key).json(&body).send().await?;
+ let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .timeout(std::time::Duration::from_secs(180))
+ .build()?;
+ let resp = client
+ .post("https://api.x.ai/v1/responses")
+ .bearer_auth(&cfg.xai_key)
+ .json(&body)
+ .send()
+ .await?;
let status = resp.status();
- let v: Value = resp.json().await.map_err(|e| anyhow!("xAI: resposta invalida ({})", e))?;
+ let v: Value = resp
+ .json()
+ .await
+ .map_err(|e| anyhow!("xAI: resposta invalida ({})", e))?;
if !status.is_success() {
- let msg = v.pointer("/error/message").or_else(|| v.get("error")).and_then(|m| m.as_str()).unwrap_or("erro").to_string();
+ let msg = v
+ .pointer("/error/message")
+ .or_else(|| v.get("error"))
+ .and_then(|m| m.as_str())
+ .unwrap_or("erro")
+ .to_string();
return Err(anyhow!("xAI HTTP {}: {}", status, msg));
}
let mut text = String::new();
let mut citations: Vec<Citation> = Vec::new();
- for item in v.get("output").and_then(|o| o.as_array()).into_iter().flatten() {
+ for item in v
+ .get("output")
+ .and_then(|o| o.as_array())
+ .into_iter()
+ .flatten()
+ {
if item.get("type").and_then(|t| t.as_str()) != Some("message") {
continue;
}
- for c in item.get("content").and_then(|c| c.as_array()).into_iter().flatten() {
+ for c in item
+ .get("content")
+ .and_then(|c| c.as_array())
+ .into_iter()
+ .flatten()
+ {
if c.get("type").and_then(|t| t.as_str()) == Some("output_text") {
text.push_str(c.get("text").and_then(|t| t.as_str()).unwrap_or(""));
- for a in c.get("annotations").and_then(|a| a.as_array()).into_iter().flatten() {
+ for a in c
+ .get("annotations")
+ .and_then(|a| a.as_array())
+ .into_iter()
+ .flatten()
+ {
if let Some(url) = a.get("url").and_then(|u| u.as_str()) {
- citations.push(Citation { url: url.to_string(), title: a.get("title").and_then(|t| t.as_str()).unwrap_or("").to_string() });
+ citations.push(Citation {
+ url: url.to_string(),
+ title: a
+ .get("title")
+ .and_then(|t| t.as_str())
+ .unwrap_or("")
+ .to_string(),
+ });
}
}
}
}
}
if text.is_empty() {
- text = v.get("output_text").and_then(|t| t.as_str()).unwrap_or("").to_string();
+ text = v
+ .get("output_text")
+ .and_then(|t| t.as_str())
+ .unwrap_or("")
+ .to_string();
}
- for c in v.get("citations").and_then(|c| c.as_array()).into_iter().flatten() {
+ for c in v
+ .get("citations")
+ .and_then(|c| c.as_array())
+ .into_iter()
+ .flatten()
+ {
if let Some(url) = c.as_str() {
if !citations.iter().any(|x| x.url == url) {
- citations.push(Citation { url: url.to_string(), title: String::new() });
+ citations.push(Citation {
+ url: url.to_string(),
+ title: String::new(),
+ });
}
}
}
- let input_tokens = v.pointer("/usage/input_tokens").and_then(|t| t.as_u64()).unwrap_or(0);
- let output_tokens = v.pointer("/usage/output_tokens").and_then(|t| t.as_u64()).unwrap_or(0);
+ let input_tokens = v
+ .pointer("/usage/input_tokens")
+ .and_then(|t| t.as_u64())
+ .unwrap_or(0);
+ let output_tokens = v
+ .pointer("/usage/output_tokens")
+ .and_then(|t| t.as_u64())
+ .unwrap_or(0);
crate::core::tools::usage::record("grok", "xai", &model, input_tokens, output_tokens, None);
- Ok(GrokAnswer { text, citations, model, backend: "xai".into(), input_tokens, output_tokens })
+ Ok(GrokAnswer {
+ text,
+ citations,
+ model,
+ backend: "xai".into(),
+ input_tokens,
+ output_tokens,
+ })
}
async fn ask_x(cfg: &GrokConfig, req: GrokRequest) -> anyhow::Result<GrokAnswer> {
let client = super::client::XClient::new()?;
client.require_login()?;
- let model = if req.model.trim().is_empty() { cfg.x_model.clone() } else { req.model.trim().to_string() };
- let conv = client.gql_post("CreateGrokConversation", json!({}), None).await?;
+ let model = if req.model.trim().is_empty() {
+ cfg.x_model.clone()
+ } else {
+ req.model.trim().to_string()
+ };
+ let conv = client
+ .gql_post("CreateGrokConversation", json!({}), None)
+ .await?;
let conversation_id = conv
.pointer("/data/create_grok_conversation/conversation_id")
.and_then(|c| c.as_str())
@@ -226,11 +315,21 @@ async fn ask_x(cfg: &GrokConfig, req: GrokRequest) -> anyhow::Result<GrokAnswer>
"isReasoning": false
});
let uuid = uuid::Uuid::new_v4().simple().to_string();
- let extra = [("x-client-uuid", uuid.as_str()), ("Referer", "https://x.com/i/grok")];
- let resp = match client.post_json_raw("https://api.x.com/2/grok/add_response.json", &body, &extra).await {
+ let extra = [
+ ("x-client-uuid", uuid.as_str()),
+ ("Referer", "https://x.com/i/grok"),
+ ];
+ let resp = match client
+ .post_json_raw("https://api.x.com/2/grok/add_response.json", &body, &extra)
+ .await
+ {
Ok(r) => r,
Err(first) => client
- .post_json_raw("https://x.com/i/api/2/grok/add_response.json", &body, &extra)
+ .post_json_raw(
+ "https://x.com/i/api/2/grok/add_response.json",
+ &body,
+ &extra,
+ )
.await
.map_err(|e| anyhow!("{} / {}", first, e))?,
};
@@ -238,10 +337,16 @@ async fn ask_x(cfg: &GrokConfig, req: GrokRequest) -> anyhow::Result<GrokAnswer>
let mut text = String::new();
let mut citations: Vec<Citation> = Vec::new();
for line in raw.lines() {
- let Ok(v) = serde_json::from_str::<Value>(line.trim()) else { continue };
+ let Ok(v) = serde_json::from_str::<Value>(line.trim()) else {
+ continue;
+ };
let Some(r) = v.get("result") else { continue };
if let Some(m) = r.get("message").and_then(|m| m.as_str()) {
- if r.get("sender").and_then(|s| s.as_str()).map(|s| s != "USER").unwrap_or(true) {
+ if r.get("sender")
+ .and_then(|s| s.as_str())
+ .map(|s| s != "USER")
+ .unwrap_or(true)
+ {
text.push_str(m);
}
}
@@ -252,7 +357,14 @@ async fn ask_x(cfg: &GrokConfig, req: GrokRequest) -> anyhow::Result<GrokAnswer>
for w in r.get(key).and_then(|a| a.as_array()).into_iter().flatten() {
if let Some(url) = w.get("url").and_then(|u| u.as_str()) {
if !citations.iter().any(|c| c.url == url) {
- citations.push(Citation { url: url.to_string(), title: w.get("title").and_then(|t| t.as_str()).unwrap_or("").to_string() });
+ citations.push(Citation {
+ url: url.to_string(),
+ title: w
+ .get("title")
+ .and_then(|t| t.as_str())
+ .unwrap_or("")
+ .to_string(),
+ });
}
}
}
@@ -264,7 +376,17 @@ async fn ask_x(cfg: &GrokConfig, req: GrokRequest) -> anyhow::Result<GrokAnswer>
}
}
if text.trim().is_empty() {
- return Err(anyhow!("Grok nao respondeu (modelo `{}` pode nao existir mais; troque nas opcoes)", model));
+ return Err(anyhow!(
+ "Grok nao respondeu (modelo `{}` pode nao existir mais; troque nas opcoes)",
+ model
+ ));
}
- Ok(GrokAnswer { text, citations, model, backend: "x".into(), input_tokens: 0, output_tokens: 0 })
+ Ok(GrokAnswer {
+ text,
+ citations,
+ model,
+ backend: "x".into(),
+ input_tokens: 0,
+ output_tokens: 0,
+ })
}
diff --git a/src-tauri/omniget-core/src/core/tools/x/media.rs b/src-tauri/omniget-core/src/core/tools/x/media.rs
index 1ed67866..e3261fa1 100644
--- a/src-tauri/omniget-core/src/core/tools/x/media.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/media.rs
@@ -19,24 +19,68 @@ pub struct MediaResult {
}
fn ext_of(url: &str, kind: &str) -> String {
- if let Some(fmt) = url.split("format=").nth(1).and_then(|s| s.split('&').next()) {
+ if let Some(fmt) = url
+ .split("format=")
+ .nth(1)
+ .and_then(|s| s.split('&').next())
+ {
return fmt.to_string();
}
let path = url.split('?').next().unwrap_or(url);
- path.rsplit('.').next().filter(|e| e.len() <= 4).map(|e| e.to_string()).unwrap_or_else(|| if kind == "photo" { "jpg".into() } else { "mp4".into() })
+ path.rsplit('.')
+ .next()
+ .filter(|e| e.len() <= 4)
+ .map(|e| e.to_string())
+ .unwrap_or_else(|| {
+ if kind == "photo" {
+ "jpg".into()
+ } else {
+ "mp4".into()
+ }
+ })
}
pub fn file_name(post: &XPost, index: usize, url: &str, kind: &str) -> String {
- let date = post.created_at.get(..10).unwrap_or("0000-00-00").replace('-', "");
- format!("{}_{}_{}_{}.{}", date, post.author.handle, post.id, index + 1, ext_of(url, kind))
+ let date = post
+ .created_at
+ .get(..10)
+ .unwrap_or("0000-00-00")
+ .replace('-', "");
+ format!(
+ "{}_{}_{}_{}.{}",
+ date,
+ post.author.handle,
+ post.id,
+ index + 1,
+ ext_of(url, kind)
+ )
}
/// Baixa a midia de `posts` para `dest`. `job` e o id de progresso/cancelamento.
-pub async fn download_posts(posts: &[XPost], dest: &std::path::Path, photos: bool, videos: bool, job: &str, progress: &ProgressFn) -> anyhow::Result<MediaResult> {
+pub async fn download_posts(
+ posts: &[XPost],
+ dest: &std::path::Path,
+ photos: bool,
+ videos: bool,
+ job: &str,
+ progress: &ProgressFn,
+) -> anyhow::Result<MediaResult> {
std::fs::create_dir_all(dest)?;
let client = super::super::client()?;
- let mut result = MediaResult { dest: dest.to_string_lossy().to_string(), posts: posts.len(), ..Default::default() };
- let total: usize = posts.iter().map(|p| p.media.iter().filter(|m| (photos && m.kind == "photo") || (videos && m.kind != "photo")).count()).sum();
+ let mut result = MediaResult {
+ dest: dest.to_string_lossy().to_string(),
+ posts: posts.len(),
+ ..Default::default()
+ };
+ let total: usize = posts
+ .iter()
+ .map(|p| {
+ p.media
+ .iter()
+ .filter(|m| (photos && m.kind == "photo") || (videos && m.kind != "photo"))
+ .count()
+ })
+ .sum();
let mut done = 0usize;
for post in posts {
for (i, m) in post.media.iter().enumerate() {
@@ -56,7 +100,14 @@ pub async fn download_posts(posts: &[XPost], dest: &std::path::Path, photos: boo
done += 1;
continue;
}
- super::report(progress, job, "download", done as u64, Some(total as u64), Some(name.clone()));
+ super::report(
+ progress,
+ job,
+ "download",
+ done as u64,
+ Some(total as u64),
+ Some(name.clone()),
+ );
match fetch_to(&client, &m.url, &path).await {
Ok(()) => result.files.push(path.to_string_lossy().to_string()),
Err(e) => {
@@ -72,8 +123,16 @@ pub async fn download_posts(posts: &[XPost], dest: &std::path::Path, photos: boo
Ok(result)
}
-async fn fetch_to(client: &reqwest::Client, url: &str, path: &std::path::Path) -> anyhow::Result<()> {
- let resp = client.get(url).header("Referer", "https://x.com/").send().await?;
+async fn fetch_to(
+ client: &reqwest::Client,
+ url: &str,
+ path: &std::path::Path,
+) -> anyhow::Result<()> {
+ let resp = client
+ .get(url)
+ .header("Referer", "https://x.com/")
+ .send()
+ .await?;
if !resp.status().is_success() {
return Err(anyhow!("HTTP {}", resp.status()));
}
@@ -85,8 +144,16 @@ async fn fetch_to(client: &reqwest::Client, url: &str, path: &std::path::Path) -
}
/// Todas as midias publicas de um perfil (aba Midia), ate `limit` posts.
-pub async fn download_profile(input: &str, dest: &str, limit: usize, photos: bool, videos: bool, progress: ProgressFn) -> anyhow::Result<MediaResult> {
- let handle = super::handle_from(input).ok_or_else(|| anyhow!("nao reconheci um perfil do X em: {}", input))?;
+pub async fn download_profile(
+ input: &str,
+ dest: &str,
+ limit: usize,
+ photos: bool,
+ videos: bool,
+ progress: ProgressFn,
+) -> anyhow::Result<MediaResult> {
+ let handle = super::handle_from(input)
+ .ok_or_else(|| anyhow!("nao reconheci um perfil do X em: {}", input))?;
let job = format!("x-media:{}", handle.to_ascii_lowercase());
super::clear_cancel(&job);
let mut posts: Vec<XPost> = Vec::new();
diff --git a/src-tauri/omniget-core/src/core/tools/x/mod.rs b/src-tauri/omniget-core/src/core/tools/x/mod.rs
index 6c681491..2566b637 100644
--- a/src-tauri/omniget-core/src/core/tools/x/mod.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/mod.rs
@@ -162,9 +162,22 @@ pub fn handle_from(input: &str) -> Option<String> {
if re.is_match(s) {
return Some(s.to_string());
}
- let re_url = regex::Regex::new(r"(?:x\.com|twitter\.com)/(?:#!/)?@?([A-Za-z0-9_]{1,15})(?:[/?#]|$)").ok()?;
+ let re_url =
+ regex::Regex::new(r"(?:x\.com|twitter\.com)/(?:#!/)?@?([A-Za-z0-9_]{1,15})(?:[/?#]|$)")
+ .ok()?;
let h = re_url.captures(s).map(|c| c[1].to_string())?;
- let reserved = ["i", "home", "explore", "search", "settings", "messages", "notifications", "hashtag", "intent", "compose"];
+ let reserved = [
+ "i",
+ "home",
+ "explore",
+ "search",
+ "settings",
+ "messages",
+ "notifications",
+ "hashtag",
+ "intent",
+ "compose",
+ ];
if reserved.contains(&h.to_ascii_lowercase().as_str()) {
return None;
}
@@ -173,7 +186,9 @@ pub fn handle_from(input: &str) -> Option<String> {
/// Pasta de dados da categoria: `<app_data>/tools/x`.
pub fn x_dir() -> std::path::PathBuf {
- let d = super::tools_dir().unwrap_or_else(std::env::temp_dir).join("x");
+ let d = super::tools_dir()
+ .unwrap_or_else(std::env::temp_dir)
+ .join("x");
let _ = std::fs::create_dir_all(&d);
d
}
@@ -225,7 +240,10 @@ pub fn photo_orig_url(url: &str) -> String {
pub fn dedup_posts(posts: Vec<XPost>) -> Vec<XPost> {
let mut seen = HashSet::new();
- posts.into_iter().filter(|p| seen.insert(p.id.clone())).collect()
+ posts
+ .into_iter()
+ .filter(|p| seen.insert(p.id.clone()))
+ .collect()
}
#[cfg(test)]
@@ -234,18 +252,33 @@ mod tests {
#[test]
fn parses_ids_and_handles() {
- assert_eq!(post_id_from("https://x.com/jack/status/20").as_deref(), Some("20"));
- assert_eq!(post_id_from("https://twitter.com/i/web/status/123456?s=20").as_deref(), Some("123456"));
+ assert_eq!(
+ post_id_from("https://x.com/jack/status/20").as_deref(),
+ Some("20")
+ );
+ assert_eq!(
+ post_id_from("https://twitter.com/i/web/status/123456?s=20").as_deref(),
+ Some("123456")
+ );
assert_eq!(post_id_from("20").as_deref(), Some("20"));
assert_eq!(handle_from("@NASA").as_deref(), Some("NASA"));
- assert_eq!(handle_from("https://x.com/nasa/media").as_deref(), Some("nasa"));
+ assert_eq!(
+ handle_from("https://x.com/nasa/media").as_deref(),
+ Some("nasa")
+ );
assert_eq!(handle_from("https://x.com/i/bookmarks"), None);
}
#[test]
fn orig_photo_url() {
- assert_eq!(photo_orig_url("https://pbs.twimg.com/media/abc.jpg"), "https://pbs.twimg.com/media/abc?format=jpg&name=orig");
- assert_eq!(photo_orig_url("https://pbs.twimg.com/media/abc.jpg?name=orig"), "https://pbs.twimg.com/media/abc.jpg?name=orig");
+ assert_eq!(
+ photo_orig_url("https://pbs.twimg.com/media/abc.jpg"),
+ "https://pbs.twimg.com/media/abc?format=jpg&name=orig"
+ );
+ assert_eq!(
+ photo_orig_url("https://pbs.twimg.com/media/abc.jpg?name=orig"),
+ "https://pbs.twimg.com/media/abc.jpg?name=orig"
+ );
}
#[test]
diff --git a/src-tauri/omniget-core/src/core/tools/x/parse.rs b/src-tauri/omniget-core/src/core/tools/x/parse.rs
index de3ec286..17427da3 100644
--- a/src-tauri/omniget-core/src/core/tools/x/parse.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/parse.rs
@@ -28,18 +28,30 @@ pub fn parse_user(result: &Value) -> Option<XUser> {
let core = result.get("core").cloned().unwrap_or(Value::Null);
let handle = {
let h = s(&core, "screen_name");
- if h.is_empty() { s(&legacy, "screen_name") } else { h }
+ if h.is_empty() {
+ s(&legacy, "screen_name")
+ } else {
+ h
+ }
};
if handle.is_empty() {
return None;
}
let name = {
let x = s(&core, "name");
- if x.is_empty() { s(&legacy, "name") } else { x }
+ if x.is_empty() {
+ s(&legacy, "name")
+ } else {
+ x
+ }
};
let created = {
let x = s(&core, "created_at");
- if x.is_empty() { s(&legacy, "created_at") } else { x }
+ if x.is_empty() {
+ s(&legacy, "created_at")
+ } else {
+ x
+ }
};
let avatar = result
.get("avatar")
@@ -47,8 +59,14 @@ pub fn parse_user(result: &Value) -> Option<XUser> {
.and_then(|u| u.as_str())
.map(|u| u.to_string())
.unwrap_or_else(|| s(&legacy, "profile_image_url_https"));
- let rel = result.get("relationship_perspectives").cloned().unwrap_or(Value::Null);
- let counts = result.get("relationship_counts").cloned().unwrap_or(Value::Null);
+ let rel = result
+ .get("relationship_perspectives")
+ .cloned()
+ .unwrap_or(Value::Null);
+ let counts = result
+ .get("relationship_counts")
+ .cloned()
+ .unwrap_or(Value::Null);
let tweet_counts = result.get("tweet_counts").cloned().unwrap_or(Value::Null);
let bio = result.get("profile_bio").cloned().unwrap_or(Value::Null);
let website = bio
@@ -64,26 +82,58 @@ pub fn parse_user(result: &Value) -> Option<XUser> {
handle,
name,
avatar: avatar.replace("_normal.", "_400x400."),
- banner: result.get("banner").map(|b| s(b, "image_url")).filter(|b| !b.is_empty()).unwrap_or_else(|| s(&legacy, "profile_banner_url")),
+ banner: result
+ .get("banner")
+ .map(|b| s(b, "image_url"))
+ .filter(|b| !b.is_empty())
+ .unwrap_or_else(|| s(&legacy, "profile_banner_url")),
bio: {
let b = s(&bio, "description");
- if b.is_empty() { s(&legacy, "description") } else { b }
+ if b.is_empty() {
+ s(&legacy, "description")
+ } else {
+ b
+ }
},
location: {
- let l = result.get("location").map(|l| s(l, "location")).unwrap_or_default();
- if l.is_empty() { s(&legacy, "location") } else { l }
+ let l = result
+ .get("location")
+ .map(|l| s(l, "location"))
+ .unwrap_or_default();
+ if l.is_empty() {
+ s(&legacy, "location")
+ } else {
+ l
+ }
},
website,
- joined: super::parse_twitter_date(&created).map(|(iso, _)| iso).unwrap_or_default(),
+ joined: super::parse_twitter_date(&created)
+ .map(|(iso, _)| iso)
+ .unwrap_or_default(),
followers: pick(n(&counts, "followers"), n(&legacy, "followers_count")),
following: pick(n(&counts, "following"), n(&legacy, "friends_count")),
posts: pick(n(&tweet_counts, "tweets"), n(&legacy, "statuses_count")),
- likes: pick(result.get("action_counts").map(|a| n(a, "favorites_count")).unwrap_or(0), n(&legacy, "favourites_count")),
+ likes: pick(
+ result
+ .get("action_counts")
+ .map(|a| n(a, "favorites_count"))
+ .unwrap_or(0),
+ n(&legacy, "favourites_count"),
+ ),
media_count: pick(n(&tweet_counts, "media_tweets"), n(&legacy, "media_count")),
verified: b(result, "is_blue_verified").unwrap_or(false)
- || result.get("verification").and_then(|v| v.get("verified")).and_then(|x| x.as_bool()).unwrap_or(false)
+ || result
+ .get("verification")
+ .and_then(|v| v.get("verified"))
+ .and_then(|x| x.as_bool())
+ .unwrap_or(false)
|| b(&legacy, "verified").unwrap_or(false),
- protected: result.get("privacy").and_then(|p| p.get("protected")).and_then(|x| x.as_bool()).or_else(|| b(&legacy, "protected")).unwrap_or(false),
+ protected: result
+ .get("privacy")
+ .and_then(|p| p.get("protected"))
+ .and_then(|x| x.as_bool())
+ .or_else(|| b(&legacy, "protected"))
+ .unwrap_or(false),
followed_by_me: b(&rel, "following").or_else(|| b(&legacy, "following")),
follows_me: b(&rel, "followed_by").or_else(|| b(&legacy, "followed_by")),
})
@@ -105,12 +155,25 @@ fn media_from_legacy(legacy: &Value) -> Vec<XMedia> {
let alt = s(m, "ext_alt_text");
let thumb = s(m, "media_url_https");
match kind.as_str() {
- "photo" => out.push(XMedia { kind: "photo".into(), url: super::photo_orig_url(&thumb), thumb, width: w, height: h, duration_ms: 0, alt }),
+ "photo" => out.push(XMedia {
+ kind: "photo".into(),
+ url: super::photo_orig_url(&thumb),
+ thumb,
+ width: w,
+ height: h,
+ duration_ms: 0,
+ alt,
+ }),
"video" | "animated_gif" => {
let info = m.get("video_info").cloned().unwrap_or(Value::Null);
let mut best = String::new();
let mut best_rate = 0u64;
- for v in info.get("variants").and_then(|a| a.as_array()).into_iter().flatten() {
+ for v in info
+ .get("variants")
+ .and_then(|a| a.as_array())
+ .into_iter()
+ .flatten()
+ {
if s(v, "content_type") == "video/mp4" {
let br = n(v, "bitrate");
if br >= best_rate {
@@ -123,7 +186,11 @@ fn media_from_legacy(legacy: &Value) -> Vec<XMedia> {
continue;
}
out.push(XMedia {
- kind: if kind == "video" { "video".into() } else { "gif".into() },
+ kind: if kind == "video" {
+ "video".into()
+ } else {
+ "gif".into()
+ },
url: best,
thumb,
width: w,
@@ -145,22 +212,42 @@ pub fn parse_tweet(result: &Value) -> Option<XPost> {
if typename == "TweetTombstone" || typename == "TweetUnavailable" {
return None;
}
- let tweet = if typename == "TweetWithVisibilityResults" { result.get("tweet")? } else { result };
+ let tweet = if typename == "TweetWithVisibilityResults" {
+ result.get("tweet")?
+ } else {
+ result
+ };
let legacy = tweet.get("legacy")?;
- if let Some(rt) = legacy.get("retweeted_status_result").and_then(|r| r.get("result")) {
+ if let Some(rt) = legacy
+ .get("retweeted_status_result")
+ .and_then(|r| r.get("result"))
+ {
let mut inner = parse_tweet(rt)?;
- let by = tweet.get("core").and_then(|c| c.get("user_results")).and_then(|u| u.get("result")).and_then(parse_user);
+ let by = tweet
+ .get("core")
+ .and_then(|c| c.get("user_results"))
+ .and_then(|u| u.get("result"))
+ .and_then(parse_user);
inner.reposted_by = by.map(|u| u.handle);
return Some(inner);
}
let id = {
let x = s(tweet, "rest_id");
- if x.is_empty() { s(legacy, "id_str") } else { x }
+ if x.is_empty() {
+ s(legacy, "id_str")
+ } else {
+ x
+ }
};
if id.is_empty() {
return None;
}
- let author = tweet.get("core").and_then(|c| c.get("user_results")).and_then(|u| u.get("result")).and_then(parse_user).unwrap_or_default();
+ let author = tweet
+ .get("core")
+ .and_then(|c| c.get("user_results"))
+ .and_then(|u| u.get("result"))
+ .and_then(parse_user)
+ .unwrap_or_default();
let mut text = tweet
.get("note_tweet")
.and_then(|nt| nt.get("note_tweet_results"))
@@ -169,7 +256,13 @@ pub fn parse_tweet(result: &Value) -> Option<XPost> {
.filter(|t| !t.is_empty())
.unwrap_or_else(|| s(legacy, "full_text"));
let mut links = Vec::new();
- for u in legacy.get("entities").and_then(|e| e.get("urls")).and_then(|a| a.as_array()).into_iter().flatten() {
+ for u in legacy
+ .get("entities")
+ .and_then(|e| e.get("urls"))
+ .and_then(|a| a.as_array())
+ .into_iter()
+ .flatten()
+ {
let short = s(u, "url");
let long = s(u, "expanded_url");
if !short.is_empty() && !long.is_empty() {
@@ -178,7 +271,13 @@ pub fn parse_tweet(result: &Value) -> Option<XPost> {
}
}
// remove o t.co da midia no fim do texto
- for m in legacy.get("extended_entities").and_then(|e| e.get("media")).and_then(|a| a.as_array()).into_iter().flatten() {
+ for m in legacy
+ .get("extended_entities")
+ .and_then(|e| e.get("media"))
+ .and_then(|a| a.as_array())
+ .into_iter()
+ .flatten()
+ {
let short = s(m, "url");
if !short.is_empty() {
text = text.replace(&short, "").trim_end().to_string();
@@ -189,12 +288,29 @@ pub fn parse_tweet(result: &Value) -> Option<XPost> {
let views = tweet.get("views").map(|v| n(v, "count")).unwrap_or(0);
let re_tag = regex::Regex::new(r"#([\p{L}\p{N}_]+)").unwrap();
let re_at = regex::Regex::new(r"@([A-Za-z0-9_]{1,15})").unwrap();
- let source = regex::Regex::new(r"<[^>]+>").unwrap().replace_all(&s(tweet, "source"), "").to_string();
+ let source = regex::Regex::new(r"<[^>]+>")
+ .unwrap()
+ .replace_all(&s(tweet, "source"), "")
+ .to_string();
Some(XPost {
- url: format!("https://x.com/{}/status/{}", if author.handle.is_empty() { "i" } else { &author.handle }, id),
+ url: format!(
+ "https://x.com/{}/status/{}",
+ if author.handle.is_empty() {
+ "i"
+ } else {
+ &author.handle
+ },
+ id
+ ),
id,
- hashtags: re_tag.captures_iter(&text).map(|c| c[1].to_string()).collect(),
- mentions: re_at.captures_iter(&text).map(|c| c[1].to_string()).collect(),
+ hashtags: re_tag
+ .captures_iter(&text)
+ .map(|c| c[1].to_string())
+ .collect(),
+ mentions: re_at
+ .captures_iter(&text)
+ .map(|c| c[1].to_string())
+ .collect(),
text,
created_at,
timestamp: ts,
@@ -207,7 +323,11 @@ pub fn parse_tweet(result: &Value) -> Option<XPost> {
bookmarks: n(legacy, "bookmark_count"),
lang: s(legacy, "lang"),
media: media_from_legacy(legacy),
- quote: tweet.get("quoted_status_result").and_then(|q| q.get("result")).and_then(parse_tweet).map(Box::new),
+ quote: tweet
+ .get("quoted_status_result")
+ .and_then(|q| q.get("result"))
+ .and_then(parse_tweet)
+ .map(Box::new),
reply_to_id: Some(s(legacy, "in_reply_to_status_id_str")).filter(|x| !x.is_empty()),
reply_to_handle: Some(s(legacy, "in_reply_to_screen_name")).filter(|x| !x.is_empty()),
conversation_id: Some(s(legacy, "conversation_id_str")).filter(|x| !x.is_empty()),
@@ -218,7 +338,11 @@ pub fn parse_tweet(result: &Value) -> Option<XPost> {
}
fn html_unescape(t: &str) -> String {
- t.replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&#39;", "'")
+ t.replace("&amp;", "&")
+ .replace("&lt;", "<")
+ .replace("&gt;", ">")
+ .replace("&quot;", "\"")
+ .replace("&#39;", "'")
}
/// Todos os `itemContent` de uma resposta de timeline, na ordem do documento
@@ -250,7 +374,11 @@ fn item_contents(v: &Value) -> Vec<Value> {
pub fn tweets_from(v: &Value) -> Vec<XPost> {
let mut out: Vec<XPost> = item_contents(v)
.iter()
- .filter_map(|ic| ic.get("tweet_results").and_then(|t| t.get("result")).and_then(parse_tweet))
+ .filter_map(|ic| {
+ ic.get("tweet_results")
+ .and_then(|t| t.get("result"))
+ .and_then(parse_tweet)
+ })
.collect();
if out.is_empty() {
// respostas de um unico post (`data.tweetResult.result`)
@@ -265,7 +393,11 @@ pub fn users_from(v: &Value) -> Vec<XUser> {
let mut seen = std::collections::HashSet::new();
let mut out: Vec<XUser> = item_contents(v)
.iter()
- .filter_map(|ic| ic.get("user_results").and_then(|u| u.get("result")).and_then(parse_user))
+ .filter_map(|ic| {
+ ic.get("user_results")
+ .and_then(|u| u.get("result"))
+ .and_then(parse_user)
+ })
.filter(|u| seen.insert(u.id.clone()))
.collect();
if out.is_empty() {
@@ -311,7 +443,10 @@ pub fn entry_ids(v: &Value) -> Vec<String> {
match v {
Value::Object(map) => {
if let Some(id) = map.get("entryId").and_then(|x| x.as_str()) {
- if !id.starts_with("cursor-") && !id.starts_with("who-to-follow") && !id.starts_with("messageprompt") {
+ if !id.starts_with("cursor-")
+ && !id.starts_with("who-to-follow")
+ && !id.starts_with("messageprompt")
+ {
out.push(id.to_string());
}
}
diff --git a/src-tauri/omniget-core/src/core/tools/x/profile.rs b/src-tauri/omniget-core/src/core/tools/x/profile.rs
index 9361bdfd..f2da88be 100644
--- a/src-tauri/omniget-core/src/core/tools/x/profile.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/profile.rs
@@ -50,8 +50,13 @@ pub struct ProfileReport {
pub utc_offset_minutes: i32,
}
-pub async fn analyze(input: &str, limit: usize, with_replies: bool) -> anyhow::Result<ProfileReport> {
- let handle = super::handle_from(input).ok_or_else(|| anyhow!("nao reconheci um perfil do X em: {}", input))?;
+pub async fn analyze(
+ input: &str,
+ limit: usize,
+ with_replies: bool,
+) -> anyhow::Result<ProfileReport> {
+ let handle = super::handle_from(input)
+ .ok_or_else(|| anyhow!("nao reconheci um perfil do X em: {}", input))?;
let user = super::fx::profile(&handle).await?;
let mut posts: Vec<XPost> = Vec::new();
let mut cursor: Option<String> = None;
@@ -87,7 +92,8 @@ pub fn report(user: XUser, posts: Vec<XPost>) -> ProfileReport {
let median_likes = if likes_sorted.is_empty() {
0.0
} else if likes_sorted.len().is_multiple_of(2) {
- (likes_sorted[likes_sorted.len() / 2 - 1] + likes_sorted[likes_sorted.len() / 2]) as f64 / 2.0
+ (likes_sorted[likes_sorted.len() / 2 - 1] + likes_sorted[likes_sorted.len() / 2]) as f64
+ / 2.0
} else {
likes_sorted[likes_sorted.len() / 2] as f64
};
@@ -111,14 +117,32 @@ pub fn report(user: XUser, posts: Vec<XPost>) -> ProfileReport {
}
}
let slots = |v: &[(u64, f64)]| -> Vec<Slot> {
- v.iter().enumerate().map(|(i, (c, l))| Slot { key: i as u32, posts: *c, avg_likes: if *c > 0 { l / *c as f64 } else { 0.0 } }).collect()
+ v.iter()
+ .enumerate()
+ .map(|(i, (c, l))| Slot {
+ key: i as u32,
+ posts: *c,
+ avg_likes: if *c > 0 { l / *c as f64 } else { 0.0 },
+ })
+ .collect()
};
let best = |v: &[Slot]| -> Option<u32> {
- v.iter().filter(|s| s.posts >= 2).max_by(|a, b| a.avg_likes.partial_cmp(&b.avg_likes).unwrap_or(std::cmp::Ordering::Equal)).map(|s| s.key)
+ v.iter()
+ .filter(|s| s.posts >= 2)
+ .max_by(|a, b| {
+ a.avg_likes
+ .partial_cmp(&b.avg_likes)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ })
+ .map(|s| s.key)
};
let by_hour = slots(&by_hour);
let by_weekday = slots(&by_wd);
- let days = if min_ts < max_ts { (max_ts - min_ts) as f64 / 86400.0 } else { 0.0 };
+ let days = if min_ts < max_ts {
+ (max_ts - min_ts) as f64 / 86400.0
+ } else {
+ 0.0
+ };
let mut tags: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
let mut ats: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
for p in &own {
@@ -132,7 +156,10 @@ pub fn report(user: XUser, posts: Vec<XPost>) -> ProfileReport {
}
}
let top = |m: std::collections::HashMap<String, u64>| -> Vec<TagCount> {
- let mut v: Vec<TagCount> = m.into_iter().map(|(tag, count)| TagCount { tag, count }).collect();
+ let mut v: Vec<TagCount> = m
+ .into_iter()
+ .map(|(tag, count)| TagCount { tag, count })
+ .collect();
v.sort_by(|a, b| b.count.cmp(&a.count).then(a.tag.cmp(&b.tag)));
v.truncate(10);
v
@@ -143,18 +170,36 @@ pub fn report(user: XUser, posts: Vec<XPost>) -> ProfileReport {
let share = |f: &dyn Fn(&XPost) -> bool| own.iter().filter(|p| f(p)).count() as f64 / n * 100.0;
ProfileReport {
sampled: own.len(),
- since: if min_ts < i64::MAX { super::iso_from_timestamp(min_ts) } else { String::new() },
- until: if max_ts > i64::MIN { super::iso_from_timestamp(max_ts) } else { String::new() },
+ since: if min_ts < i64::MAX {
+ super::iso_from_timestamp(min_ts)
+ } else {
+ String::new()
+ },
+ until: if max_ts > i64::MIN {
+ super::iso_from_timestamp(max_ts)
+ } else {
+ String::new()
+ },
days_spanned: days,
- posts_per_day: if days > 0.0 { own.len() as f64 / days } else { 0.0 },
+ posts_per_day: if days > 0.0 {
+ own.len() as f64 / days
+ } else {
+ 0.0
+ },
avg_likes,
median_likes,
avg_reposts,
avg_replies,
avg_views,
- engagement_rate: if user.followers > 0 { (avg_likes + avg_reposts + avg_replies) / user.followers as f64 * 100.0 } else { 0.0 },
+ engagement_rate: if user.followers > 0 {
+ (avg_likes + avg_reposts + avg_replies) / user.followers as f64 * 100.0
+ } else {
+ 0.0
+ },
reply_share: share(&|p| p.is_reply()),
- repost_share: posts.iter().filter(|p| p.reposted_by.is_some()).count() as f64 / posts.len().max(1) as f64 * 100.0,
+ repost_share: posts.iter().filter(|p| p.reposted_by.is_some()).count() as f64
+ / posts.len().max(1) as f64
+ * 100.0,
media_share: share(&|p| !p.media.is_empty()),
link_share: share(&|p| !p.links.is_empty()),
best_hour: best(&by_hour),
diff --git a/src-tauri/omniget-core/src/core/tools/x/query_ids.rs b/src-tauri/omniget-core/src/core/tools/x/query_ids.rs
index 5cc642b6..054dce75 100644
--- a/src-tauri/omniget-core/src/core/tools/x/query_ids.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/query_ids.rs
@@ -78,7 +78,10 @@ pub fn id_for(op: &str) -> Option<String> {
if let Some(id) = c.ids.get(op) {
return Some(id.clone());
}
- TABLE.iter().find(|(name, _)| *name == op).map(|(_, id)| id.to_string())
+ TABLE
+ .iter()
+ .find(|(name, _)| *name == op)
+ .map(|(_, id)| id.to_string())
}
/// Idade do cache em segundos (`None` = nunca raspado).
@@ -96,7 +99,8 @@ fn script_urls(html: &str) -> Vec<String> {
// build atual (x-web / Vite) e legada (responsive-web) linkadas direto
for re in [
regex::Regex::new(r"https://[\w.-]+/x-web/[\w./-]+\.js").unwrap(),
- regex::Regex::new(r"https://[\w.-]+/responsive-web/client-web(?:-legacy)?/[\w./~-]+\.js").unwrap(),
+ regex::Regex::new(r"https://[\w.-]+/responsive-web/client-web(?:-legacy)?/[\w./~-]+\.js")
+ .unwrap(),
] {
for m in re.find_iter(html) {
urls.push(m.as_str().to_string());
@@ -116,23 +120,48 @@ fn script_urls(html: &str) -> Vec<String> {
names.insert(c[1].to_string(), c[2].to_string());
}
}
- let wanted = ["Bookmark", "Grok", "LoggedInMain", "HoverCard", "UserProfile", "UserHandler", "TweetActivity", "TweetEditHistory", "HomeTimeline", "Follow", "Search", "Explore", "Lists"];
+ let wanted = [
+ "Bookmark",
+ "Grok",
+ "LoggedInMain",
+ "HoverCard",
+ "UserProfile",
+ "UserHandler",
+ "TweetActivity",
+ "TweetEditHistory",
+ "HomeTimeline",
+ "Follow",
+ "Search",
+ "Explore",
+ "Lists",
+ ];
for (id, hash) in &hashes {
let name = names.get(id).cloned().unwrap_or_else(|| id.clone());
if name.starts_with("i18n/") || name.starts_with("ondemand.countries") || name == "vendor" {
continue;
}
if wanted.iter().any(|w| name.contains(w)) {
- urls.push(format!("https://abs.twimg.com/responsive-web/client-web/{}.{}a.js", name, hash));
+ urls.push(format!(
+ "https://abs.twimg.com/responsive-web/client-web/{}.{}a.js",
+ name, hash
+ ));
}
}
let mut seen = std::collections::HashSet::new();
- urls.into_iter().filter(|u| !u.contains("/i18n/") && seen.insert(u.clone())).collect()
+ urls.into_iter()
+ .filter(|u| !u.contains("/i18n/") && seen.insert(u.clone()))
+ .collect()
}
pub fn extract_ops(js: &str) -> Vec<(String, String)> {
- let re = regex::Regex::new(r#"queryId:\s*"([A-Za-z0-9_-]+)"[^}]{0,300}?operationName:\s*"([A-Za-z0-9_]+)""#).unwrap();
- let re2 = regex::Regex::new(r#"operationName:\s*"([A-Za-z0-9_]+)"[^}]{0,300}?queryId:\s*"([A-Za-z0-9_-]+)""#).unwrap();
+ let re = regex::Regex::new(
+ r#"queryId:\s*"([A-Za-z0-9_-]+)"[^}]{0,300}?operationName:\s*"([A-Za-z0-9_]+)""#,
+ )
+ .unwrap();
+ let re2 = regex::Regex::new(
+ r#"operationName:\s*"([A-Za-z0-9_]+)"[^}]{0,300}?queryId:\s*"([A-Za-z0-9_-]+)""#,
+ )
+ .unwrap();
let mut out = Vec::new();
for c in re.captures_iter(js) {
out.push((c[2].to_string(), c[1].to_string()));
@@ -147,7 +176,11 @@ pub fn extract_ops(js: &str) -> Vec<(String, String)> {
/// bundles e atualiza o cache. Devolve quantas operacoes conhece agora.
pub async fn refresh(http: &reqwest::Client, cookie: Option<&str>) -> anyhow::Result<usize> {
let mut html = String::new();
- for page in ["https://x.com/home", "https://x.com/i/flow/login", "https://x.com/"] {
+ for page in [
+ "https://x.com/home",
+ "https://x.com/i/flow/login",
+ "https://x.com/",
+ ] {
let mut req = http.get(page);
if let Some(c) = cookie {
req = req.header("Cookie", c);
@@ -155,7 +188,11 @@ pub async fn refresh(http: &reqwest::Client, cookie: Option<&str>) -> anyhow::Re
if let Ok(resp) = req.send().await {
if let Ok(text) = resp.text().await {
if text.contains("document.location = \"") {
- if let Some(next) = text.split("document.location = \"").nth(1).and_then(|s| s.split('"').next()) {
+ if let Some(next) = text
+ .split("document.location = \"")
+ .nth(1)
+ .and_then(|s| s.split('"').next())
+ {
if let Ok(r2) = http.get(next).send().await {
if let Ok(t2) = r2.text().await {
html.push_str(&t2);
@@ -214,8 +251,14 @@ mod tests {
fn extracts_ops_from_bundle() {
let js = r#"e.exports={queryId:"XMOz5h24KAZ86qKffKTLdQ",operationName:"TweetDetail",operationType:"query",metadata:{}};x={operationName:"Bookmarks",queryId:"iblrFnKr6PZUR-dWpfXG6g"}"#;
let ops = extract_ops(js);
- assert!(ops.contains(&("TweetDetail".to_string(), "XMOz5h24KAZ86qKffKTLdQ".to_string())));
- assert!(ops.contains(&("Bookmarks".to_string(), "iblrFnKr6PZUR-dWpfXG6g".to_string())));
+ assert!(ops.contains(&(
+ "TweetDetail".to_string(),
+ "XMOz5h24KAZ86qKffKTLdQ".to_string()
+ )));
+ assert!(ops.contains(&(
+ "Bookmarks".to_string(),
+ "iblrFnKr6PZUR-dWpfXG6g".to_string()
+ )));
}
#[test]
@@ -223,7 +266,9 @@ mod tests {
let html = r#"<script src="https://abs.twimg.com/responsive-web/client-web/main.abcdef1a.js"></script>p.u=e=>""+({1:"bundle.Bookmarks",2:"vendor"}[e]||e)+"."+({1:"0123abc",2:"deadbee"})[e]+"a.js""#;
let urls = script_urls(html);
assert!(urls.iter().any(|u| u.contains("main.abcdef1a.js")));
- assert!(urls.iter().any(|u| u.ends_with("bundle.Bookmarks.0123abca.js")));
+ assert!(urls
+ .iter()
+ .any(|u| u.ends_with("bundle.Bookmarks.0123abca.js")));
assert!(!urls.iter().any(|u| u.contains("vendor")));
}
}
diff --git a/src-tauri/omniget-core/src/core/tools/x/search.rs b/src-tauri/omniget-core/src/core/tools/x/search.rs
index 42eecd52..6332e43a 100644
--- a/src-tauri/omniget-core/src/core/tools/x/search.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/search.rs
@@ -23,7 +23,11 @@ pub async fn search(query: &str, feed: &str, cursor: Option<&str>) -> anyhow::Re
}
let feed = if feed == "top" { "top" } else { "latest" };
match super::fx::search(q, feed, cursor).await {
- Ok(page) => Ok(SearchPage { posts: page.items, cursor: page.cursor, source: "fxtwitter".into() }),
+ Ok(page) => Ok(SearchPage {
+ posts: page.items,
+ cursor: page.cursor,
+ source: "fxtwitter".into(),
+ }),
Err(fx_err) => {
let client = super::client::XClient::new()?;
if !client.authed() {
@@ -39,8 +43,19 @@ pub async fn search(query: &str, feed: &str, cursor: Option<&str>) -> anyhow::Re
if let Some(c) = cursor {
vars["cursor"] = json!(c);
}
- let v = client.gql_get("SearchTimeline", vars, json!({}), Some(json!({"withArticleRichContentState": false}))).await?;
- Ok(SearchPage { posts: super::parse::tweets_from(&v), cursor: super::parse::bottom_cursor(&v), source: "graphql".into() })
+ let v = client
+ .gql_get(
+ "SearchTimeline",
+ vars,
+ json!({}),
+ Some(json!({"withArticleRichContentState": false})),
+ )
+ .await?;
+ Ok(SearchPage {
+ posts: super::parse::tweets_from(&v),
+ cursor: super::parse::bottom_cursor(&v),
+ source: "graphql".into(),
+ })
}
}
}
diff --git a/src-tauri/omniget-core/src/core/tools/x/thread.rs b/src-tauri/omniget-core/src/core/tools/x/thread.rs
index 98cb2227..fbdf1259 100644
--- a/src-tauri/omniget-core/src/core/tools/x/thread.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/thread.rs
@@ -32,15 +32,27 @@ impl Thread {
}
pub async fn unroll(input: &str) -> anyhow::Result<Thread> {
- let id = super::post_id_from(input).ok_or_else(|| anyhow!("nao reconheci um post do X em: {}", input))?;
+ let id = super::post_id_from(input)
+ .ok_or_else(|| anyhow!("nao reconheci um post do X em: {}", input))?;
match super::fx::thread(&id).await {
Ok((focal, posts, truncated)) => {
- let posts = if posts.is_empty() { vec![focal.clone()] } else { posts };
- Ok(Thread { focal, posts, truncated, source: "fxtwitter".into() })
+ let posts = if posts.is_empty() {
+ vec![focal.clone()]
+ } else {
+ posts
+ };
+ Ok(Thread {
+ focal,
+ posts,
+ truncated,
+ source: "fxtwitter".into(),
+ })
}
Err(fx_err) => {
tracing::info!("[x] fxtwitter falhou ({}), tentando GraphQL", fx_err);
- unroll_graphql(&id).await.map_err(|e| anyhow!("{} / {}", fx_err, e))
+ unroll_graphql(&id)
+ .await
+ .map_err(|e| anyhow!("{} / {}", fx_err, e))
}
}
}
@@ -76,12 +88,24 @@ async fn unroll_graphql(id: &str) -> anyhow::Result<Thread> {
cursor = next;
}
let all = super::dedup_posts(all);
- let focal = all.iter().find(|p| p.id == id).cloned().ok_or_else(|| anyhow!("post indisponivel"))?;
+ let focal = all
+ .iter()
+ .find(|p| p.id == id)
+ .cloned()
+ .ok_or_else(|| anyhow!("post indisponivel"))?;
let author = focal.author.handle.to_ascii_lowercase();
- let mut by_id: std::collections::HashMap<String, XPost> = all.iter().filter(|p| p.author.handle.to_ascii_lowercase() == author).map(|p| (p.id.clone(), p.clone())).collect();
+ let mut by_id: std::collections::HashMap<String, XPost> = all
+ .iter()
+ .filter(|p| p.author.handle.to_ascii_lowercase() == author)
+ .map(|p| (p.id.clone(), p.clone()))
+ .collect();
// sobe ate a raiz
let mut root = focal.clone();
- while let Some(parent) = root.reply_to_id.clone().and_then(|pid| by_id.get(&pid).cloned()) {
+ while let Some(parent) = root
+ .reply_to_id
+ .clone()
+ .and_then(|pid| by_id.get(&pid).cloned())
+ {
root = parent;
}
// desce pela cadeia de respostas do autor
@@ -89,7 +113,11 @@ async fn unroll_graphql(id: &str) -> anyhow::Result<Thread> {
by_id.remove(&root.id);
loop {
let last = chain.last().unwrap().id.clone();
- let next = by_id.values().filter(|p| p.reply_to_id.as_deref() == Some(last.as_str())).min_by_key(|p| p.timestamp).cloned();
+ let next = by_id
+ .values()
+ .filter(|p| p.reply_to_id.as_deref() == Some(last.as_str()))
+ .min_by_key(|p| p.timestamp)
+ .cloned();
match next {
Some(p) => {
by_id.remove(&p.id);
@@ -101,7 +129,12 @@ async fn unroll_graphql(id: &str) -> anyhow::Result<Thread> {
if !chain.iter().any(|p| p.id == focal.id) {
chain = vec![focal.clone()];
}
- Ok(Thread { focal, posts: chain, truncated: false, source: "graphql".into() })
+ Ok(Thread {
+ focal,
+ posts: chain,
+ truncated: false,
+ source: "graphql".into(),
+ })
}
fn find_show_more(v: &serde_json::Value) -> Option<String> {
diff --git a/src-tauri/omniget-core/src/core/tools/x/txid.rs b/src-tauri/omniget-core/src/core/tools/x/txid.rs
index fd914bab..649e32e9 100644
--- a/src-tauri/omniget-core/src/core/tools/x/txid.rs
+++ b/src-tauri/omniget-core/src/core/tools/x/txid.rs
@@ -62,7 +62,10 @@ impl Cubic {
}
fn interpolate(from: &[f64], to: &[f64], f: f64) -> Vec<f64> {
- from.iter().zip(to).map(|(a, b)| a * (1.0 - f) + b * f).collect()
+ from.iter()
+ .zip(to)
+ .map(|(a, b)| a * (1.0 - f) + b * f)
+ .collect()
}
fn rotation_matrix(deg: f64) -> [f64; 4] {
@@ -120,10 +123,16 @@ fn calc_anim_key(frames: &[f64], target_time: f64) -> String {
.map(|(i, x)| solve(*x, if i % 2 == 1 { -1.0 } else { 0.0 }, 1.0, false))
.collect();
let val = Cubic { curves }.get_value(target_time);
- let color: Vec<f64> = interpolate(&from_color, &to_color, val).into_iter().map(|c| c.clamp(0.0, 255.0)).collect();
+ let color: Vec<f64> = interpolate(&from_color, &to_color, val)
+ .into_iter()
+ .map(|c| c.clamp(0.0, 255.0))
+ .collect();
let rotation = interpolate(&[0.0], &[to_rotation], val);
let matrix = rotation_matrix(rotation[0]);
- let mut parts: Vec<String> = color[..3].iter().map(|c| format!("{:x}", c.round() as i64)).collect();
+ let mut parts: Vec<String> = color[..3]
+ .iter()
+ .map(|c| format!("{:x}", c.round() as i64))
+ .collect();
for value in matrix {
let mut rounded = (value * 100.0).round() / 100.0;
if rounded < 0.0 {
@@ -143,7 +152,11 @@ fn calc_anim_key(frames: &[f64], target_time: f64) -> String {
parts.join("").replace(['.', '-'], "")
}
-async fn page_text(http: &reqwest::Client, url: &str, cookie: Option<&str>) -> anyhow::Result<String> {
+async fn page_text(
+ http: &reqwest::Client,
+ url: &str,
+ cookie: Option<&str>,
+) -> anyhow::Result<String> {
let mut req = http.get(url);
if let Some(c) = cookie {
req = req.header("Cookie", c);
@@ -152,7 +165,12 @@ async fn page_text(http: &reqwest::Client, url: &str, cookie: Option<&str>) -> a
if !text.contains(">document.location =") {
return Ok(text);
}
- let next = text.split("document.location = \"").nth(1).and_then(|s| s.split('"').next()).unwrap_or("").to_string();
+ let next = text
+ .split("document.location = \"")
+ .nth(1)
+ .and_then(|s| s.split('"').next())
+ .unwrap_or("")
+ .to_string();
let mut req = http.get(&next);
if let Some(c) = cookie {
req = req.header("Cookie", c);
@@ -162,7 +180,10 @@ async fn page_text(http: &reqwest::Client, url: &str, cookie: Option<&str>) -> a
return Ok(text);
}
let re = regex::Regex::new(r#"<input[^>]*name="([^"]+)"[^>]*value="([^"]*)""#).unwrap();
- let form: Vec<(String, String)> = re.captures_iter(&text).map(|c| (c[1].to_string(), c[2].to_string())).collect();
+ let form: Vec<(String, String)> = re
+ .captures_iter(&text)
+ .map(|c| (c[1].to_string(), c[2].to_string()))
+ .collect();
let mut req = http.post("https://x.com/x/migrate").form(&form);
if let Some(c) = cookie {
req = req.header("Cookie", c);
@@ -171,8 +192,12 @@ async fn page_text(http: &reqwest::Client, url: &str, cookie: Option<&str>) -> a
}
fn verification_bytes(html: &str) -> anyhow::Result<Vec<u8>> {
- let re1 = regex::Regex::new(r#"<meta[^>]*name="twitter-site-verification"[^>]*content="([^"]+)""#).unwrap();
- let re2 = regex::Regex::new(r#"<meta[^>]*content="([^"]+)"[^>]*name="twitter-site-verification""#).unwrap();
+ let re1 =
+ regex::Regex::new(r#"<meta[^>]*name="twitter-site-verification"[^>]*content="([^"]+)""#)
+ .unwrap();
+ let re2 =
+ regex::Regex::new(r#"<meta[^>]*content="([^"]+)"[^>]*name="twitter-site-verification""#)
+ .unwrap();
let content = re1
.captures(html)
.or_else(|| re2.captures(html))
@@ -182,14 +207,21 @@ fn verification_bytes(html: &str) -> anyhow::Result<Vec<u8>> {
}
fn anim_frames(html: &str, vk: &[u8]) -> anyhow::Result<Vec<Vec<f64>>> {
- let re_svg = regex::Regex::new(r#"(?s)<svg[^>]*id="loading-x-anim-\d+"[^>]*>(.*?)</svg>"#).unwrap();
+ let re_svg =
+ regex::Regex::new(r#"(?s)<svg[^>]*id="loading-x-anim-\d+"[^>]*>(.*?)</svg>"#).unwrap();
let re_g = regex::Regex::new(r#"(?s)<g[^>]*>(.*?)</g>"#).unwrap();
let re_path = regex::Regex::new(r#"<path[^>]*\sd="([^"]+)""#).unwrap();
let mut ds: Vec<String> = Vec::new();
for svg in re_svg.captures_iter(html) {
let inner = &svg[1];
- let g = re_g.captures(inner).map(|c| c[1].to_string()).unwrap_or_else(|| inner.to_string());
- let paths: Vec<String> = re_path.captures_iter(&g).map(|c| c[1].trim().to_string()).collect();
+ let g = re_g
+ .captures(inner)
+ .map(|c| c[1].to_string())
+ .unwrap_or_else(|| inner.to_string());
+ let paths: Vec<String> = re_path
+ .captures_iter(&g)
+ .map(|c| c[1].trim().to_string())
+ .collect();
if let Some(d) = paths.get(1) {
ds.push(d.clone());
}
@@ -203,7 +235,11 @@ fn anim_frames(html: &str, vk: &[u8]) -> anyhow::Result<Vec<Vec<f64>>> {
let re_num = regex::Regex::new(r"[^\d]+").unwrap();
let mut rows = Vec::new();
for part in body.split('C') {
- let nums: Vec<f64> = re_num.replace_all(part, " ").split_whitespace().filter_map(|x| x.parse().ok()).collect();
+ let nums: Vec<f64> = re_num
+ .replace_all(part, " ")
+ .split_whitespace()
+ .filter_map(|x| x.parse().ok())
+ .collect();
rows.push(nums);
}
Ok(rows)
@@ -213,14 +249,17 @@ fn script_urls(html: &str) -> Vec<String> {
let mut urls = Vec::new();
for re in [
regex::Regex::new(r"https://[\w.-]+/x-web/[\w./-]+\.js").unwrap(),
- regex::Regex::new(r"https://[\w.-]+/responsive-web/client-web(?:-legacy)?/[\w./~-]+\.js").unwrap(),
+ regex::Regex::new(r"https://[\w.-]+/responsive-web/client-web(?:-legacy)?/[\w./~-]+\.js")
+ .unwrap(),
] {
for m in re.find_iter(html) {
urls.push(m.as_str().to_string());
}
}
let mut seen = std::collections::HashSet::new();
- urls.into_iter().filter(|u| seen.insert(u.clone())).collect()
+ urls.into_iter()
+ .filter(|u| seen.insert(u.clone()))
+ .collect()
}
fn indices_re() -> regex::Regex {
@@ -231,16 +270,32 @@ fn join_url(base: &str, rel: &str) -> String {
if rel.starts_with("http") {
return rel.to_string();
}
- url::Url::parse(base).ok().and_then(|b| b.join(rel).ok()).map(|u| u.to_string()).unwrap_or_else(|| rel.to_string())
+ url::Url::parse(base)
+ .ok()
+ .and_then(|b| b.join(rel).ok())
+ .map(|u| u.to_string())
+ .unwrap_or_else(|| rel.to_string())
}
-async fn indices(http: &reqwest::Client, html: &str, cookie: Option<&str>) -> anyhow::Result<Vec<usize>> {
+async fn indices(
+ http: &reqwest::Client,
+ html: &str,
+ cookie: Option<&str>,
+) -> anyhow::Result<Vec<usize>> {
let scripts = script_urls(html);
- let x_web: Vec<String> = scripts.iter().filter(|u| u.contains("/x-web/")).cloned().collect();
+ let x_web: Vec<String> = scripts
+ .iter()
+ .filter(|u| u.contains("/x-web/"))
+ .cloned()
+ .collect();
if x_web.iter().any(|u| u.contains("entry-client-logged-out")) {
anyhow::bail!("o X serviu a versao deslogada da pagina");
}
- let pool = if x_web.is_empty() { scripts.clone() } else { x_web };
+ let pool = if x_web.is_empty() {
+ scripts.clone()
+ } else {
+ x_web
+ };
let re = indices_re();
let mut url = pool.iter().find(|u| re.is_match(u)).cloned();
if url.is_none() {
@@ -265,7 +320,10 @@ async fn indices(http: &reqwest::Client, html: &str, cookie: Option<&str>) -> an
let url = url.ok_or_else(|| anyhow::anyhow!("chunk de assinatura do X nao encontrado"))?;
let text = page_text(http, &url, cookie).await?;
let re_idx = regex::Regex::new(r"\(\w\[(\d{1,2})\],\s*16\)").unwrap();
- let items: Vec<usize> = re_idx.captures_iter(&text).filter_map(|c| c[1].parse().ok()).collect();
+ let items: Vec<usize> = re_idx
+ .captures_iter(&text)
+ .filter_map(|c| c[1].parse().ok())
+ .collect();
if items.is_empty() {
anyhow::bail!("indices de assinatura nao encontrados");
}
@@ -286,19 +344,30 @@ impl TxIdGen {
}
let frame_time = ((frame_time as f64 / 10.0 + 0.5).floor() * 10.0) as i64;
let frame_idx = (vk.get(idx[0]).copied().unwrap_or(0) % 16) as usize;
- let row = rows.get(frame_idx).ok_or_else(|| anyhow::anyhow!("frame da animacao fora do intervalo"))?;
+ let row = rows
+ .get(frame_idx)
+ .ok_or_else(|| anyhow::anyhow!("frame da animacao fora do intervalo"))?;
if row.len() < 11 {
anyhow::bail!("frame da animacao incompleto");
}
let anim_key = calc_anim_key(row, frame_time as f64 / 4096.0);
- Ok(Self { vk_bytes: vk, anim_key })
+ Ok(Self {
+ vk_bytes: vk,
+ anim_key,
+ })
}
pub fn calc(&self, method: &str, path: &str) -> String {
let now_ms = chrono::Utc::now().timestamp_millis();
let ts = ((now_ms - 1_682_924_400_000) as f64 / 1000.0).floor() as i64;
let ts_bytes: Vec<u8> = (0..4).map(|i| ((ts >> (i * 8)) & 0xff) as u8).collect();
- let payload = format!("{}!{}!{}obfiowerehiring{}", method.to_uppercase(), path, ts, self.anim_key);
+ let payload = format!(
+ "{}!{}!{}obfiowerehiring{}",
+ method.to_uppercase(),
+ path,
+ ts,
+ self.anim_key
+ );
let hash = Sha256::digest(payload.as_bytes());
let mut pld: Vec<u8> = Vec::new();
pld.extend_from_slice(&self.vk_bytes);
@@ -308,7 +377,10 @@ impl TxIdGen {
let num: u8 = rand::random();
let mut out = vec![num];
out.extend(pld.iter().map(|x| x ^ num));
- base64::engine::general_purpose::STANDARD.encode(&out).trim_end_matches('=').to_string()
+ base64::engine::general_purpose::STANDARD
+ .encode(&out)
+ .trim_end_matches('=')
+ .to_string()
}
}
@@ -326,7 +398,9 @@ mod tests {
#[test]
fn anim_key_is_deterministic() {
- let frames: Vec<f64> = vec![10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 128.0, 10.0, 20.0, 30.0, 40.0];
+ let frames: Vec<f64> = vec![
+ 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 128.0, 10.0, 20.0, 30.0, 40.0,
+ ];
let a = calc_anim_key(&frames, 0.3);
let b = calc_anim_key(&frames, 0.3);
assert_eq!(a, b);
@@ -335,7 +409,10 @@ mod tests {
#[test]
fn calc_produces_base64() {
- let g = TxIdGen { vk_bytes: vec![1, 2, 3, 4, 5, 6, 7, 8], anim_key: "abc".into() };
+ let g = TxIdGen {
+ vk_bytes: vec![1, 2, 3, 4, 5, 6, 7, 8],
+ anim_key: "abc".into(),
+ };
let id = g.calc("GET", "/i/api/graphql/x/y");
assert!(id.len() > 20 && !id.ends_with('='));
}
diff --git a/src-tauri/omniget-core/src/core/ytdlp.rs b/src-tauri/omniget-core/src/core/ytdlp.rs
index 4b087ce0..82128ad4 100644
--- a/src-tauri/omniget-core/src/core/ytdlp.rs
+++ b/src-tauri/omniget-core/src/core/ytdlp.rs
@@ -369,7 +369,11 @@ pub(crate) const PROGRESS_TEMPLATE: &str = "download:%(progress._percent_str)s|e
/// instrumentação que a tela precisa (`--newline`, `--progress`, template,
/// `--print after_move:…`, `--no-quiet`), um `-o` quando falta e a URL no
/// fim. Nada mais é alterado: o usuário pediu para rodar *aquele* comando.
-pub(crate) fn prepare_override_args(argv: Vec<String>, url: &str, output_dir: &Path) -> Vec<String> {
+pub(crate) fn prepare_override_args(
+ argv: Vec<String>,
+ url: &str,
+ output_dir: &Path,
+) -> Vec<String> {
let mut args = argv;
if let Some(first) = args.first() {
let name = Path::new(first)
@@ -1226,7 +1230,10 @@ pub async fn acquire_ytdlp_slot(what: &str) -> tokio::sync::OwnedSemaphorePermit
let dl_id = log_hook::current_download_id();
tracing::info!("[yt-dlp] waiting for a slot ({})", what);
if let Some(id) = dl_id {
- log_hook::emit_log(id, &format!("[omniget] waiting for a yt-dlp slot ({})", what));
+ log_hook::emit_log(
+ id,
+ &format!("[omniget] waiting for a yt-dlp slot ({})", what),
+ );
}
let permit = sem
.acquire_owned()
@@ -1237,7 +1244,10 @@ pub async fn acquire_ytdlp_slot(what: &str) -> tokio::sync::OwnedSemaphorePermit
if let Some(id) = dl_id {
log_hook::emit_log(
id,
- &format!("[omniget] yt-dlp slot acquired after {:.1}s", waited.as_secs_f64()),
+ &format!(
+ "[omniget] yt-dlp slot acquired after {:.1}s",
+ waited.as_secs_f64()
+ ),
);
}
permit
@@ -1545,7 +1555,10 @@ fn probe_python(candidate: &Path) -> Option<PathBuf> {
return None;
}
let exe = lines.next().map(str::trim).filter(|s| !s.is_empty());
- Some(exe.map(PathBuf::from).unwrap_or_else(|| candidate.to_path_buf()))
+ Some(
+ exe.map(PathBuf::from)
+ .unwrap_or_else(|| candidate.to_path_buf()),
+ )
}
/// Um Python ≥ 3.10 da máquina, se houver, para rodar o zipapp do yt-dlp.
@@ -1572,9 +1585,9 @@ fn python_cached() -> Option<PathBuf> {
let found = python_candidates().iter().find_map(|c| probe_python(c));
match &found {
Some(p) => tracing::info!("[yt-dlp] python for zipapp: {}", p.display()),
- None => tracing::info!(
- "[yt-dlp] no python >= 3.10 found; using the onefile binary"
- ),
+ None => {
+ tracing::info!("[yt-dlp] no python >= 3.10 found; using the onefile binary")
+ }
}
found
})
@@ -1819,8 +1832,8 @@ async fn download_ytdlp_binary() -> anyhow::Result<PathBuf> {
const YTDLP_ZIPAPP_ASSET: &str = "yt-dlp";
async fn download_ytdlp_zipapp() -> anyhow::Result<PathBuf> {
- let target = managed_ytdlp_zipapp_path()
- .ok_or_else(|| anyhow!("Could not determine data directory"))?;
+ let target =
+ managed_ytdlp_zipapp_path().ok_or_else(|| anyhow!("Could not determine data directory"))?;
download_ytdlp_asset(YTDLP_ZIPAPP_ASSET, target).await
}
@@ -3856,7 +3869,6 @@ pub async fn download_video(
Err(translate_ytdlp_error(&last_error))
}
-
/// Lê o stdout do yt-dlp e converte em `ProgressUpdate`. Extraído do laço de
/// tentativas para o caminho "comando editado pelo usuário" usar o mesmo
/// parser — a tela não pode se comportar diferente só porque o comando veio
@@ -3872,178 +3884,177 @@ fn spawn_stdout_reader(
boot_slot: Option<BootSlot>,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
- let mut boot_slot = boot_slot;
- let mut phase = 0u32;
- let mut last_raw_percent: Option<f64> = None;
- let mut max_reported = 0.0f64;
- let mut first_line_logged = false;
- let mut first_progress_logged = false;
- let mut authoritative_capture = false;
- let mut last_send = std::time::Instant::now();
- let throttle = std::time::Duration::from_millis(250);
- let mut last_stream_id: Option<String> = None;
- // Bytes reais: o `dl:` do template é do stream atual; somando os
- // streams já terminados a tela mostra "123 MB" de verdade em vez
- // de zero até o merge (o total continua desconhecido em bv+ba
- // porque o tamanho do áudio só aparece quando ele começa).
- let mut prev_streams_bytes: u64 = 0;
- let mut current_stream_bytes: u64 = 0;
- let mut planned_count: usize = 0;
- while let Ok(Some(line)) = lines.next_line().await {
- // Primeira linha: o Python já está de pé, o bootstrap acabou.
- if let Some(slot) = boot_slot.take() {
- release_boot_slot(&slot);
- }
- if let Some(id) = log_id {
- log_hook::emit_log(id, &line);
- }
- if let Some(plan) = parse_planned_formats(&line) {
- planned_count = plan.len();
- let _ = progress_tx
- .send(ProgressUpdate {
- percent: max_reported,
- planned_formats: Some(plan),
- ..Default::default()
- })
- .await;
- continue;
+ let mut boot_slot = boot_slot;
+ let mut phase = 0u32;
+ let mut last_raw_percent: Option<f64> = None;
+ let mut max_reported = 0.0f64;
+ let mut first_line_logged = false;
+ let mut first_progress_logged = false;
+ let mut authoritative_capture = false;
+ let mut last_send = std::time::Instant::now();
+ let throttle = std::time::Duration::from_millis(250);
+ let mut last_stream_id: Option<String> = None;
+ // Bytes reais: o `dl:` do template é do stream atual; somando os
+ // streams já terminados a tela mostra "123 MB" de verdade em vez
+ // de zero até o merge (o total continua desconhecido em bv+ba
+ // porque o tamanho do áudio só aparece quando ele começa).
+ let mut prev_streams_bytes: u64 = 0;
+ let mut current_stream_bytes: u64 = 0;
+ let mut planned_count: usize = 0;
+ while let Ok(Some(line)) = lines.next_line().await {
+ // Primeira linha: o Python já está de pé, o bootstrap acabou.
+ if let Some(slot) = boot_slot.take() {
+ release_boot_slot(&slot);
+ }
+ if let Some(id) = log_id {
+ log_hook::emit_log(id, &line);
+ }
+ if let Some(plan) = parse_planned_formats(&line) {
+ planned_count = plan.len();
+ let _ = progress_tx
+ .send(ProgressUpdate {
+ percent: max_reported,
+ planned_formats: Some(plan),
+ ..Default::default()
+ })
+ .await;
+ continue;
+ }
+ if let Some(pp) = postprocess_phase(&line) {
+ let p = max_reported.clamp(98.0, 99.0);
+ let _ = progress_tx.send(ProgressUpdate::phase(pp, p)).await;
+ max_reported = max_reported.max(p);
+ last_send = std::time::Instant::now();
+ continue;
+ }
+ if !first_line_logged {
+ first_line_logged = true;
+ tracing::debug!(
+ "[perf] download_video first_byte_time: {:?}",
+ _timer_start.elapsed()
+ );
+ }
+ if let Some(rest) = line.strip_prefix("OMNIGET_FILEPATH:") {
+ let final_path = rest.trim();
+ if !final_path.is_empty() && final_path != "NA" {
+ authoritative_capture = true;
+ let mut guard = captured_path_writer.lock().unwrap();
+ *guard = Some(PathBuf::from(final_path));
}
- if let Some(pp) = postprocess_phase(&line) {
- let p = max_reported.clamp(98.0, 99.0);
- let _ = progress_tx.send(ProgressUpdate::phase(pp, p)).await;
- max_reported = max_reported.max(p);
- last_send = std::time::Instant::now();
- continue;
+ continue;
+ }
+ if let Some(dest) = parse_destination_line(&line) {
+ let dest_path = PathBuf::from(&dest);
+ let ext = dest_path
+ .extension()
+ .and_then(|e| e.to_str())
+ .unwrap_or("")
+ .to_lowercase();
+ let is_subtitle =
+ matches!(ext.as_str(), "vtt" | "srt" | "ass" | "ssa" | "sub" | "lrc");
+ if !is_subtitle && !authoritative_capture {
+ phase += 1;
+ let mut guard = captured_path_writer.lock().unwrap();
+ *guard = Some(dest_path);
}
- if !first_line_logged {
- first_line_logged = true;
+ }
+ if line.contains("[Merger]")
+ || line.contains("[FixupM3u8]")
+ || line.contains("[VideoConvertor]")
+ || (line.contains("[ffmpeg]") && line.to_lowercase().contains("merg"))
+ {
+ let merging_progress = max_reported.clamp(95.0, 98.0).max(max_reported);
+ let _ = progress_tx
+ .send(ProgressUpdate::phase("merging", merging_progress))
+ .await;
+ max_reported = max_reported.max(merging_progress);
+ last_send = std::time::Instant::now();
+ continue;
+ }
+ if let Some(pct) = parse_progress_line(&line) {
+ if !first_progress_logged && pct > 0.0 {
+ first_progress_logged = true;
tracing::debug!(
- "[perf] download_video first_byte_time: {:?}",
+ "[perf] download_video: first_progress > 0% at {:?}",
_timer_start.elapsed()
);
}
- if let Some(rest) = line.strip_prefix("OMNIGET_FILEPATH:") {
- let final_path = rest.trim();
- if !final_path.is_empty() && final_path != "NA" {
- authoritative_capture = true;
- let mut guard = captured_path_writer.lock().unwrap();
- *guard = Some(PathBuf::from(final_path));
- }
- continue;
+ let eta = parse_eta_line(&line);
+ let speed = parse_speed_line(&line);
+ if let (Some(id), Some(e)) = (log_id, eta) {
+ record_eta(id, e);
}
- if let Some(dest) = parse_destination_line(&line) {
- let dest_path = PathBuf::from(&dest);
- let ext = dest_path
- .extension()
- .and_then(|e| e.to_str())
- .unwrap_or("")
- .to_lowercase();
- let is_subtitle =
- matches!(ext.as_str(), "vtt" | "srt" | "ass" | "ssa" | "sub" | "lrc");
- if !is_subtitle && !authoritative_capture {
- phase += 1;
- let mut guard = captured_path_writer.lock().unwrap();
- *guard = Some(dest_path);
- }
+ let stream = parse_stream_info(&line);
+ let fragment = parse_fragment_progress(&line);
+ let stream_id = stream.as_ref().map(|s| s.format_id.clone());
+ let stream_changed = stream_id.is_some() && stream_id != last_stream_id;
+ if stream_changed {
+ last_stream_id = stream_id;
+ prev_streams_bytes += current_stream_bytes;
+ current_stream_bytes = 0;
}
- if line.contains("[Merger]")
- || line.contains("[FixupM3u8]")
- || line.contains("[VideoConvertor]")
- || (line.contains("[ffmpeg]") && line.to_lowercase().contains("merg"))
- {
- let merging_progress = max_reported.clamp(95.0, 98.0).max(max_reported);
- let _ = progress_tx
- .send(ProgressUpdate::phase("merging", merging_progress))
- .await;
- max_reported = max_reported.max(merging_progress);
- last_send = std::time::Instant::now();
- continue;
+ if let Some(dl) = parse_downloaded_bytes_line(&line) {
+ current_stream_bytes = current_stream_bytes.max(dl);
}
- if let Some(pct) = parse_progress_line(&line) {
- if !first_progress_logged && pct > 0.0 {
- first_progress_logged = true;
- tracing::debug!(
- "[perf] download_video: first_progress > 0% at {:?}",
- _timer_start.elapsed()
- );
- }
- let eta = parse_eta_line(&line);
- let speed = parse_speed_line(&line);
- if let (Some(id), Some(e)) = (log_id, eta) {
- record_eta(id, e);
- }
- let stream = parse_stream_info(&line);
- let fragment = parse_fragment_progress(&line);
- let stream_id = stream.as_ref().map(|s| s.format_id.clone());
- let stream_changed = stream_id.is_some() && stream_id != last_stream_id;
- if stream_changed {
- last_stream_id = stream_id;
- prev_streams_bytes += current_stream_bytes;
- current_stream_bytes = 0;
- }
- if let Some(dl) = parse_downloaded_bytes_line(&line) {
- current_stream_bytes = current_stream_bytes.max(dl);
- }
- let overall_bytes = Some(prev_streams_bytes + current_stream_bytes);
- let single_total = if planned_count <= 1 {
- parse_total_bytes_line(&line)
- } else {
- None
- };
- let attach = |mut u: ProgressUpdate| {
- u.stream = stream.clone();
- u.fragment_index = fragment.map(|f| f.0);
- u.fragment_count = fragment.map(|f| f.1);
- u
- };
- if is_audio_only {
- if stream_changed || pct >= 99.0 || last_send.elapsed() >= throttle {
- let dl = parse_downloaded_bytes_line(&line);
- let tot = parse_total_bytes_line(&line);
- let _ = progress_tx
- .send(attach(ProgressUpdate::rich(pct, dl, tot, speed, eta)))
- .await;
- last_send = std::time::Instant::now();
- }
- } else {
- let adjusted = adjusted_multi_stream_progress(
- &mut phase,
- &mut last_raw_percent,
- max_reported,
- pct,
- );
- if stream_changed
- || (adjusted > max_reported
- && (adjusted >= 99.0 || last_send.elapsed() >= throttle))
- {
- max_reported = max_reported.max(adjusted);
- let _ = progress_tx
- .send(attach(ProgressUpdate::rich(
- max_reported,
- overall_bytes,
- single_total,
- speed,
- eta,
- )))
- .await;
- last_send = std::time::Instant::now();
- }
+ let overall_bytes = Some(prev_streams_bytes + current_stream_bytes);
+ let single_total = if planned_count <= 1 {
+ parse_total_bytes_line(&line)
+ } else {
+ None
+ };
+ let attach = |mut u: ProgressUpdate| {
+ u.stream = stream.clone();
+ u.fragment_index = fragment.map(|f| f.0);
+ u.fragment_count = fragment.map(|f| f.1);
+ u
+ };
+ if is_audio_only {
+ if stream_changed || pct >= 99.0 || last_send.elapsed() >= throttle {
+ let dl = parse_downloaded_bytes_line(&line);
+ let tot = parse_total_bytes_line(&line);
+ let _ = progress_tx
+ .send(attach(ProgressUpdate::rich(pct, dl, tot, speed, eta)))
+ .await;
+ last_send = std::time::Instant::now();
}
- } else if line.trim_start().starts_with("download:") || line.contains("[download]")
- {
- let dl = parse_downloaded_bytes_line(&line)
- .or_else(|| parse_default_download_line(&line).map(|(d, _)| d as u64));
- let speed = parse_speed_line(&line)
- .or_else(|| parse_default_download_line(&line).map(|(_, s)| s));
- if (dl.is_some() || speed.is_some()) && last_send.elapsed() >= throttle {
+ } else {
+ let adjusted = adjusted_multi_stream_progress(
+ &mut phase,
+ &mut last_raw_percent,
+ max_reported,
+ pct,
+ );
+ if stream_changed
+ || (adjusted > max_reported
+ && (adjusted >= 99.0 || last_send.elapsed() >= throttle))
+ {
+ max_reported = max_reported.max(adjusted);
let _ = progress_tx
- .send(ProgressUpdate::rich(0.0, dl, None, speed, None))
+ .send(attach(ProgressUpdate::rich(
+ max_reported,
+ overall_bytes,
+ single_total,
+ speed,
+ eta,
+ )))
.await;
last_send = std::time::Instant::now();
}
}
+ } else if line.trim_start().starts_with("download:") || line.contains("[download]") {
+ let dl = parse_downloaded_bytes_line(&line)
+ .or_else(|| parse_default_download_line(&line).map(|(d, _)| d as u64));
+ let speed = parse_speed_line(&line)
+ .or_else(|| parse_default_download_line(&line).map(|(_, s)| s));
+ if (dl.is_some() || speed.is_some()) && last_send.elapsed() >= throttle {
+ let _ = progress_tx
+ .send(ProgressUpdate::rich(0.0, dl, None, speed, None))
+ .await;
+ last_send = std::time::Instant::now();
+ }
}
- })
+ }
+ })
}
/// Roda o comando editado pelo usuário como está. Uma tentativa só: quem edita
@@ -4944,13 +4955,21 @@ mod tests {
assert!(is_terminal_ytdlp_error(
"error: fragment 1 not found, unable to continue"
));
- assert!(is_terminal_ytdlp_error("error: the downloaded file is empty"));
- assert!(is_terminal_ytdlp_error("error: [youtube] abc: video unavailable"));
+ assert!(is_terminal_ytdlp_error(
+ "error: the downloaded file is empty"
+ ));
+ assert!(is_terminal_ytdlp_error(
+ "error: [youtube] abc: video unavailable"
+ ));
assert!(is_terminal_ytdlp_error(
"error: unable to download webpage: http error 404: not found"
));
- assert!(!is_terminal_ytdlp_error("error: http error 429: too many requests"));
- assert!(!is_terminal_ytdlp_error("error: requested format is not available"));
+ assert!(!is_terminal_ytdlp_error(
+ "error: http error 429: too many requests"
+ ));
+ assert!(!is_terminal_ytdlp_error(
+ "error: requested format is not available"
+ ));
assert!(!is_terminal_ytdlp_error("error: connection reset by peer"));
}
@@ -5021,7 +5040,9 @@ mod tests {
assert_eq!(super::parse_progress_line(line), Some(42.0));
assert_eq!(super::parse_speed_line(line), Some(4_500_000.0));
// O template real precisa conter cada chave que o parser procura.
- for key in ["fi:", "fc:", "fid:", "h:", "vc:", "ac:", "ext:", "fsz:", "note:"] {
+ for key in [
+ "fi:", "fc:", "fid:", "h:", "vc:", "ac:", "ext:", "fsz:", "note:",
+ ] {
assert!(PROGRESS_TEMPLATE.contains(&format!("|{key}")), "{key}");
}
}
@@ -5049,7 +5070,10 @@ mod tests {
#[test]
fn linha_sem_formato_nao_vira_stream() {
- assert!(parse_stream_info("download: 1.0%|eta:NA|spd:NA|dl:0|tot:NA|est:NA|fi:NA|fc:NA").is_none());
+ assert!(
+ parse_stream_info("download: 1.0%|eta:NA|spd:NA|dl:0|tot:NA|est:NA|fi:NA|fc:NA")
+ .is_none()
+ );
assert_eq!(parse_fragment_progress("download: 1%|fi:NA|fc:NA"), None);
assert_eq!(parse_fragment_progress("download: 1%|fi:0|fc:0"), None);
}
@@ -5065,10 +5089,22 @@ mod tests {
Some(vec!["18".to_string()])
);
assert_eq!(parse_planned_formats("[download] Destination: x.mp4"), None);
- assert_eq!(postprocess_phase("[Metadata] Adding metadata to \"x.mp4\""), Some("postprocessing"));
- assert_eq!(postprocess_phase("[ExtractAudio] Destination: x.m4a"), Some("extracting_audio"));
- assert_eq!(postprocess_phase("[EmbedSubtitle] Embedding subtitles"), Some("embedding_subtitles"));
- assert_eq!(postprocess_phase("[Merger] Merging formats into \"x.mp4\""), None);
+ assert_eq!(
+ postprocess_phase("[Metadata] Adding metadata to \"x.mp4\""),
+ Some("postprocessing")
+ );
+ assert_eq!(
+ postprocess_phase("[ExtractAudio] Destination: x.m4a"),
+ Some("extracting_audio")
+ );
+ assert_eq!(
+ postprocess_phase("[EmbedSubtitle] Embedding subtitles"),
+ Some("embedding_subtitles")
+ );
+ assert_eq!(
+ postprocess_phase("[Merger] Merging formats into \"x.mp4\""),
+ None
+ );
assert_eq!(postprocess_phase("[download] 10%"), None);
}
@@ -5086,9 +5122,15 @@ mod tests {
assert!(args.contains(&"--progress".to_string()));
assert!(args.contains(&"--no-quiet".to_string()));
assert!(args.contains(&PROGRESS_TEMPLATE.to_string()));
- assert!(args.iter().any(|a| a.starts_with("after_move:OMNIGET_FILEPATH")));
+ assert!(args
+ .iter()
+ .any(|a| a.starts_with("after_move:OMNIGET_FILEPATH")));
assert!(args.contains(&"-o".to_string()), "sem -o, recebe o padrão");
- assert_eq!(args.iter().filter(|a| *a == url).count(), 1, "URL fica uma vez, no lugar do usuário");
+ assert_eq!(
+ args.iter().filter(|a| *a == url).count(),
+ 1,
+ "URL fica uma vez, no lugar do usuário"
+ );
// Com -P próprio, não recebe -o.
let argv2: Vec<String> = ["-P", "/x", "--output=%(id)s.%(ext)s"]
.iter()
@@ -5096,7 +5138,11 @@ mod tests {
.collect();
let args2 = prepare_override_args(argv2, url, out);
assert!(!args2.contains(&"-o".to_string()));
- assert_eq!(args2.last().map(String::as_str), Some(url), "URL entra no fim quando falta");
+ assert_eq!(
+ args2.last().map(String::as_str),
+ Some(url),
+ "URL entra no fim quando falta"
+ );
}
#[test]
@@ -5104,19 +5150,31 @@ mod tests {
use super::newer_release_available as newer;
// nightly local mais novo que o stable publicado: nunca rebaixar
assert!(!newer(Some((2026, 8, 30)), Some((2026, 8, 19))));
- assert!(!newer(Some((2026, 8, 19)), Some((2026, 8, 19))), "mesma versão não re-baixa");
+ assert!(
+ !newer(Some((2026, 8, 19)), Some((2026, 8, 19))),
+ "mesma versão não re-baixa"
+ );
assert!(newer(Some((2026, 8, 19)), Some((2026, 9, 2))));
// sem informação, não mexe
assert!(!newer(None, Some((2026, 9, 2))));
assert!(!newer(Some((2026, 8, 19)), None));
- assert_eq!(super::parse_ytdlp_version("2026.09.04.232832"), Some((2026, 9, 4)));
+ assert_eq!(
+ super::parse_ytdlp_version("2026.09.04.232832"),
+ Some((2026, 9, 4))
+ );
}
#[test]
fn host_do_tuner_junta_as_variantes_do_youtube() {
- assert_eq!(tuner_host_key("https://www.youtube.com/watch?v=x"), "youtube");
+ assert_eq!(
+ tuner_host_key("https://www.youtube.com/watch?v=x"),
+ "youtube"
+ );
assert_eq!(tuner_host_key("https://youtu.be/x"), "youtube");
- assert_eq!(tuner_host_key("https://rr1---sn-x.googlevideo.com/videoplayback"), "youtube");
+ assert_eq!(
+ tuner_host_key("https://rr1---sn-x.googlevideo.com/videoplayback"),
+ "youtube"
+ );
assert_eq!(tuner_host_key("https://www.vimeo.com/1"), "vimeo.com");
assert_eq!(tuner_host_key("nope"), "unknown");
}
@@ -5814,7 +5872,10 @@ mod e2e {
);
assert!(cmd.display.contains("formats=dashy"), "{}", cmd.display);
assert!(cmd.display.contains("--ignore-config"));
- let planned: Vec<_> = updates.iter().filter_map(|u| u.planned_formats.clone()).collect();
+ let planned: Vec<_> = updates
+ .iter()
+ .filter_map(|u| u.planned_formats.clone())
+ .collect();
let streams: Vec<_> = updates
.iter()
.filter_map(|u| u.stream.clone())
@@ -5826,13 +5887,24 @@ mod e2e {
println!("--- streams seen (dedup): {:?}", uniq);
println!(
"--- phases: {:?}",
- updates.iter().filter_map(|u| u.phase.clone()).collect::<Vec<_>>()
+ updates
+ .iter()
+ .filter_map(|u| u.phase.clone())
+ .collect::<Vec<_>>()
+ );
+ println!(
+ "--- fragments max: {:?}",
+ updates.iter().filter_map(|u| u.fragment_count).max()
+ );
+ println!(
+ "--- bytes max: {:?}",
+ updates.iter().filter_map(|u| u.downloaded_bytes).max()
);
- println!("--- fragments max: {:?}", updates.iter().filter_map(|u| u.fragment_count).max());
- println!("--- bytes max: {:?}", updates.iter().filter_map(|u| u.downloaded_bytes).max());
println!(
"--- result: {:?}",
- result.as_ref().map(|r| (r.file_path.clone(), r.file_size_bytes))
+ result
+ .as_ref()
+ .map(|r| (r.file_path.clone(), r.file_size_bytes))
);
assert!(result.is_ok(), "{:?}", result.err());
assert!(!planned.is_empty(), "planned formats parsed");
diff --git a/src-tauri/omniget-core/src/platforms/direct_file.rs b/src-tauri/omniget-core/src/platforms/direct_file.rs
index cca880ea..b545b7c9 100644
--- a/src-tauri/omniget-core/src/platforms/direct_file.rs
+++ b/src-tauri/omniget-core/src/platforms/direct_file.rs
@@ -125,9 +125,8 @@ pub fn probe_says_direct_file(
content_length.unwrap_or(0) >= DIRECT_FILE_MIN_BYTES
}
-fn direct_probe_cache() -> &'static std::sync::Mutex<
- std::collections::HashMap<String, (std::time::Instant, bool)>,
-> {
+fn direct_probe_cache(
+) -> &'static std::sync::Mutex<std::collections::HashMap<String, (std::time::Instant, bool)>> {
static CACHE: std::sync::OnceLock<
std::sync::Mutex<std::collections::HashMap<String, (std::time::Instant, bool)>>,
> = std::sync::OnceLock::new();
@@ -150,8 +149,7 @@ pub async fn looks_like_direct_file(url: &str) -> bool {
}
}
}
- let hit = match tokio::time::timeout(std::time::Duration::from_secs(5), probe_file(url)).await
- {
+ let hit = match tokio::time::timeout(std::time::Duration::from_secs(5), probe_file(url)).await {
Ok(Some(p)) => probe_says_direct_file(
p.content_type.as_deref(),
p.content_length,
@@ -292,8 +290,12 @@ mod tests {
#[test]
fn unknown_extension_is_the_only_case_worth_probing() {
- assert!(has_unknown_extension("https://nbg1-speed.hetzner.com/100MB.xyz"));
- assert!(has_unknown_extension("https://example.com/files/blob.abc123"));
+ assert!(has_unknown_extension(
+ "https://nbg1-speed.hetzner.com/100MB.xyz"
+ ));
+ assert!(has_unknown_extension(
+ "https://example.com/files/blob.abc123"
+ ));
// página, mídia e arquivo conhecido já se decidem sozinhos
assert!(!has_unknown_extension("https://example.com/index.html"));
assert!(!has_unknown_extension("https://example.com/video.mp4"));
@@ -316,8 +318,16 @@ mod tests {
Some(10),
Some("x.bin")
));
- assert!(!probe_says_direct_file(Some("text/html; charset=utf-8"), Some(50_000_000), None));
- assert!(!probe_says_direct_file(Some("application/octet-stream"), Some(1000), None));
+ assert!(!probe_says_direct_file(
+ Some("text/html; charset=utf-8"),
+ Some(50_000_000),
+ None
+ ));
+ assert!(!probe_says_direct_file(
+ Some("application/octet-stream"),
+ Some(1000),
+ None
+ ));
assert!(!probe_says_direct_file(None, None, None));
}
}
diff --git a/src-tauri/omniget-core/tests/bench_engine.rs b/src-tauri/omniget-core/tests/bench_engine.rs
index 8f060abb..5ee9dc70 100644
--- a/src-tauri/omniget-core/tests/bench_engine.rs
+++ b/src-tauri/omniget-core/tests/bench_engine.rs
@@ -91,7 +91,10 @@ async fn bench_engine() {
println!("|---|---|---|---|");
if mode == "small" {
- let n: u64 = std::env::var("BENCH_SMALL_N").ok().and_then(|v| v.parse().ok()).unwrap_or(40);
+ let n: u64 = std::env::var("BENCH_SMALL_N")
+ .ok()
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(40);
// sequencial
let t = Instant::now();
let mut total = 0u64;
@@ -128,14 +131,19 @@ async fn bench_engine() {
if mode == "stress" {
for par in env_list("BENCH_PARALLEL", "2,4,8") {
- let segs: usize = std::env::var("BENCH_STRESS_SEGMENTS").ok().and_then(|v| v.parse().ok()).unwrap_or(8);
+ let segs: usize = std::env::var("BENCH_STRESS_SEGMENTS")
+ .ok()
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(8);
let t = Instant::now();
let mut handles = Vec::new();
for i in 0..par {
let c = client.clone();
let u = url.clone();
let o = dir.join(format!("stress{i}.bin"));
- handles.push(tokio::spawn(async move { run_fetcher(&c, &u, o, segs, 4).await.0 }));
+ handles.push(tokio::spawn(async move {
+ run_fetcher(&c, &u, o, segs, 4).await.0
+ }));
}
let mut total = 0u64;
for h in handles {
@@ -179,7 +187,15 @@ async fn bench_engine() {
let secs = t.elapsed().as_secs_f64();
match r {
Ok(res) => {
- println!("| yt-dlp generic (http) | http-chunk-size {} | {secs:.2}s | {:.1} |", if chunk == "0" { "padrão do app (10M)" } else { chunk }, mib_s(res.file_size_bytes, secs));
+ println!(
+ "| yt-dlp generic (http) | http-chunk-size {} | {secs:.2}s | {:.1} |",
+ if chunk == "0" {
+ "padrão do app (10M)"
+ } else {
+ chunk
+ },
+ mib_s(res.file_size_bytes, secs)
+ );
let _ = std::fs::remove_file(res.file_path);
}
Err(e) => println!("| yt-dlp generic | chunk {chunk} | erro | {e} |"),
@@ -196,7 +212,10 @@ async fn bench_engine() {
for &mb in &sizes {
for &s in &segments {
let (bytes, secs) = run_fetcher(&client, &url, dir.join("b.bin"), s as usize, mb).await;
- println!("| HttpFetcher | {s} segmentos · {mb} MiB/segmento | {secs:.2}s | {:.1} |", mib_s(bytes, secs));
+ println!(
+ "| HttpFetcher | {s} segmentos · {mb} MiB/segmento | {secs:.2}s | {:.1} |",
+ mib_s(bytes, secs)
+ );
}
}
// baseline: reqwest stream único sem o fetcher
@@ -208,11 +227,16 @@ async fn bench_engine() {
let mut n = 0u64;
while let Some(c) = stream.next().await {
let c = c.unwrap();
- tokio::io::AsyncWriteExt::write_all(&mut f, &c).await.unwrap();
+ tokio::io::AsyncWriteExt::write_all(&mut f, &c)
+ .await
+ .unwrap();
n += c.len() as u64;
}
let secs = t.elapsed().as_secs_f64();
- println!("| reqwest cru (1 conexão, sem fetcher) | baseline | {secs:.2}s | {:.1} |", mib_s(n, secs));
+ println!(
+ "| reqwest cru (1 conexão, sem fetcher) | baseline | {secs:.2}s | {:.1} |",
+ mib_s(n, secs)
+ );
}
let _ = std::fs::remove_dir_all(&dir);
}
diff --git a/src-tauri/omniget-core/tests/instagram_live.rs b/src-tauri/omniget-core/tests/instagram_live.rs
index 3105b32f..0051c503 100644
--- a/src-tauri/omniget-core/tests/instagram_live.rs
+++ b/src-tauri/omniget-core/tests/instagram_live.rs
@@ -25,46 +25,94 @@ async fn ig_live_read_only() {
let p = noop_progress();
let me = profile::whoami(&client).await.expect("whoami");
- println!("logado como @{} ({} seguidores)", me.username, me.follower_count);
+ println!(
+ "logado como @{} ({} seguidores)",
+ me.username, me.follower_count
+ );
let target = std::env::var("OMNIGET_IG_TARGET").unwrap_or_else(|_| "instagram".into());
- let user = profile::resolve_user(&client, &target).await.expect("resolve_user");
- println!("@{} pk={} posts={} privado={}", user.username, user.pk, user.media_count, user.is_private);
+ let user = profile::resolve_user(&client, &target)
+ .await
+ .expect("resolve_user");
+ println!(
+ "@{} pk={} posts={} privado={}",
+ user.username, user.pk, user.media_count, user.is_private
+ );
- let posts = profile::user_posts(&client, &user.username, 15, &flag, &p, "t").await.expect("user_posts (graphql)");
- println!("posts: {} (primeiro {} · {} arquivos)", posts.len(), posts.first().map(|x| x.code.as_str()).unwrap_or("-"), posts.first().map(|x| x.files.len()).unwrap_or(0));
+ let posts = profile::user_posts(&client, &user.username, 15, &flag, &p, "t")
+ .await
+ .expect("user_posts (graphql)");
+ println!(
+ "posts: {} (primeiro {} · {} arquivos)",
+ posts.len(),
+ posts.first().map(|x| x.code.as_str()).unwrap_or("-"),
+ posts.first().map(|x| x.files.len()).unwrap_or(0)
+ );
assert!(posts.len() > 12, "paginação do GraphQL devia passar de 12");
- let reels = profile::user_reels(&client, &user.pk, 5, &flag, &p, "t").await.expect("user_reels");
+ let reels = profile::user_reels(&client, &user.pk, 5, &flag, &p, "t")
+ .await
+ .expect("user_reels");
println!("reels: {}", reels.len());
- let tagged = profile::user_tagged(&client, &user.pk, 5, &flag, &p, "t").await.expect("user_tagged");
+ let tagged = profile::user_tagged(&client, &user.pk, 5, &flag, &p, "t")
+ .await
+ .expect("user_tagged");
println!("marcados: {}", tagged.len());
- let hls = profile::highlights(&client, &user.pk).await.expect("highlights");
+ let hls = profile::highlights(&client, &user.pk)
+ .await
+ .expect("highlights");
println!("highlights: {}", hls.len());
if let Some(h) = hls.first() {
- let items = profile::highlight_items(&client, &h.id).await.expect("highlight_items");
+ let items = profile::highlight_items(&client, &h.id)
+ .await
+ .expect("highlight_items");
println!(" '{}' com {} itens", h.title, items.len());
}
- let stories = profile::stories_of(&client, &user.pk).await.expect("stories_of");
+ let stories = profile::stories_of(&client, &user.pk)
+ .await
+ .expect("stories_of");
println!("stories ativos: {}", stories.len());
if let Some(post) = posts.first() {
- let item = media::post_info(&client, &post.code).await.expect("post_info");
- println!("post_info ok: {} likes, {} comentarios", item.like_count, item.comment_count);
- let comments = social::comments(&client, &item.pk, 30, &flag, &p, "t").await.expect("comments");
+ let item = media::post_info(&client, &post.code)
+ .await
+ .expect("post_info");
+ println!(
+ "post_info ok: {} likes, {} comentarios",
+ item.like_count, item.comment_count
+ );
+ let comments = social::comments(&client, &item.pk, 30, &flag, &p, "t")
+ .await
+ .expect("comments");
let (likes, likers) = social::likers(&client, &item.pk).await.expect("likers");
- println!("comentarios: {} · likers: {} de {}", comments.len(), likers.len(), likes);
+ println!(
+ "comentarios: {} · likers: {} de {}",
+ comments.len(),
+ likers.len(),
+ likes
+ );
}
- let following = follow::following(&client, &me.pk, 60, &flag, &p, "t").await.expect("following");
- let followers = follow::followers(&client, &me.pk, 60, &flag, &p, "t").await.expect("followers");
+ let following = follow::following(&client, &me.pk, 60, &flag, &p, "t")
+ .await
+ .expect("following");
+ let followers = follow::followers(&client, &me.pk, 60, &flag, &p, "t")
+ .await
+ .expect("followers");
let a = follow::analyze(followers, following, &Default::default());
- println!("seguidores {} · seguindo {} · nao seguem de volta (amostra) {}", a.followers_count, a.following_count, a.not_following_back.len());
+ println!(
+ "seguidores {} · seguindo {} · nao seguem de volta (amostra) {}",
+ a.followers_count,
+ a.following_count,
+ a.not_following_back.len()
+ );
let tag = social::tag_info(&client, "sunset").await.expect("tag_info");
println!("#sunset: {} posts", tag.media_count);
- let tag_media = social::tag_media(&client, "sunset", "recent", 10, &flag, &p, "t").await.unwrap_or_default();
+ let tag_media = social::tag_media(&client, "sunset", "recent", 10, &flag, &p, "t")
+ .await
+ .unwrap_or_default();
println!("#sunset recentes: {}", tag_media.len());
}
diff --git a/src-tauri/src/commands/auth_webview.rs b/src-tauri/src/commands/auth_webview.rs
index e772aff7..99980b15 100644
--- a/src-tauri/src/commands/auth_webview.rs
+++ b/src-tauri/src/commands/auth_webview.rs
@@ -440,10 +440,7 @@ async fn extract_cookies_native_or_empty(
}
}
-async fn extract_cookies_js(
- window: &tauri::WebviewWindow,
- default_domain: &str,
-) -> JsExtraction {
+async fn extract_cookies_js(window: &tauri::WebviewWindow, default_domain: &str) -> JsExtraction {
let js = r#"
(function() {
try {
@@ -1154,7 +1151,9 @@ mod tests {
assert!(!has_any_cookie(&[cookie("oidc.abc123")], &targets));
assert!(!target_matches("*", "anything"));
assert!(wants_storage(&targets));
- assert!(!wants_storage(&parse_cookie_targets("access_token|dj_session_id")));
+ assert!(!wants_storage(&parse_cookie_targets(
+ "access_token|dj_session_id"
+ )));
}
#[test]
diff --git a/src-tauri/src/commands/league/champ_select.rs b/src-tauri/src/commands/league/champ_select.rs
index b4960f29..961be1aa 100644
--- a/src-tauri/src/commands/league/champ_select.rs
+++ b/src-tauri/src/commands/league/champ_select.rs
@@ -1,5 +1,5 @@
-use serde_json::Value;
use rand::RngExt;
+use serde_json::Value;
use std::collections::HashSet;
/// Bans wait longer than picks by default in most rulesets, and a ban sent on the
@@ -119,13 +119,19 @@ pub fn local_pick_action(session: &Value, cell: i64) -> Option<(i64, bool)> {
let groups = session.get("actions")?.as_array()?;
for group in groups {
for action in group.as_array().map(|a| a.as_slice()).unwrap_or(&[]) {
- let actor = action.get("actorCellId").and_then(Value::as_i64).unwrap_or(-2);
+ let actor = action
+ .get("actorCellId")
+ .and_then(Value::as_i64)
+ .unwrap_or(-2);
let kind = action.get("type").and_then(Value::as_str).unwrap_or("");
if actor != cell || kind != "pick" {
continue;
}
let id = action.get("id").and_then(Value::as_i64)?;
- let completed = action.get("completed").and_then(Value::as_bool).unwrap_or(false);
+ let completed = action
+ .get("completed")
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
return Some((id, completed));
}
}
diff --git a/src-tauri/src/commands/league/coach.rs b/src-tauri/src/commands/league/coach.rs
index 7a09aaf5..7b0ae3ae 100644
--- a/src-tauri/src/commands/league/coach.rs
+++ b/src-tauri/src/commands/league/coach.rs
@@ -57,7 +57,10 @@ pub fn opgg_result(envelope: &Value) -> Result<Value, String> {
.get("message")
.and_then(Value::as_str)
.unwrap_or("unknown error");
- return Err(format!("op.gg: {}", message.lines().next().unwrap_or(message)));
+ return Err(format!(
+ "op.gg: {}",
+ message.lines().next().unwrap_or(message)
+ ));
}
let text = envelope
.get("result")
@@ -71,7 +74,9 @@ pub fn opgg_result(envelope: &Value) -> Result<Value, String> {
}
pub async fn opgg_call(tool: &str, args: Value) -> Result<Value, String> {
- let http = HTTP.clone().ok_or_else(|| "http client init failed".to_string())?;
+ let http = HTTP
+ .clone()
+ .ok_or_else(|| "http client init failed".to_string())?;
for attempt in 0..2 {
let session = {
let cached = OPGG_SESSION.lock().await.clone();
@@ -222,7 +227,13 @@ fn system_prompt(style: &str, language: &str) -> String {
/// A participant trimmed to what a coach reads, from the match detail shape.
pub fn compact_participant(p: &Value, minutes: f64) -> Value {
let f = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(0.0);
- let per_min = |v: f64| if minutes > 0.0 { (v / minutes * 10.0).round() / 10.0 } else { 0.0 };
+ let per_min = |v: f64| {
+ if minutes > 0.0 {
+ (v / minutes * 10.0).round() / 10.0
+ } else {
+ 0.0
+ }
+ };
json!({
"player": p.get("gameName").and_then(Value::as_str).unwrap_or(""),
"championId": p.get("championId"),
@@ -296,13 +307,24 @@ fn prompt_json(value: &Value, cap: usize) -> String {
/// Post-game review of one match.
#[tauri::command]
-pub async fn league_coach_review(game_id: i64, style: Option<String>, language: Option<String>) -> Result<String, String> {
+pub async fn league_coach_review(
+ game_id: i64,
+ style: Option<String>,
+ language: Option<String>,
+) -> Result<String, String> {
ensure_enabled()?;
let client = get_client().await?;
let detail = super::league_match_detail(game_id).await?;
let me = lcu_get_raw(&client, "/lol-summoner/v1/current-summoner").await?;
- let my_puuid = me.get("puuid").and_then(Value::as_str).unwrap_or("").to_string();
- let duration = detail.get("gameDuration").and_then(Value::as_f64).unwrap_or(0.0);
+ let my_puuid = me
+ .get("puuid")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let duration = detail
+ .get("gameDuration")
+ .and_then(Value::as_f64)
+ .unwrap_or(0.0);
let minutes = duration / 60.0;
let champions = champion_summary(&client).await;
let participants: Vec<&Value> = detail
@@ -351,9 +373,12 @@ pub async fn league_coach_review(game_id: i64, style: Option<String>, language:
pub fn trend_rows(games: &[Value], puuid: &str, champions: &Value) -> Value {
let mut rows: Vec<Value> = Vec::new();
let mut wins = 0usize;
- let mut by_champion: std::collections::HashMap<String, (usize, usize)> = std::collections::HashMap::new();
- let mut by_role: std::collections::HashMap<String, (usize, usize)> = std::collections::HashMap::new();
- let (mut k, mut d, mut a, mut cs, mut vision, mut minutes) = (0f64, 0f64, 0f64, 0f64, 0f64, 0f64);
+ let mut by_champion: std::collections::HashMap<String, (usize, usize)> =
+ std::collections::HashMap::new();
+ let mut by_role: std::collections::HashMap<String, (usize, usize)> =
+ std::collections::HashMap::new();
+ let (mut k, mut d, mut a, mut cs, mut vision, mut minutes) =
+ (0f64, 0f64, 0f64, 0f64, 0f64, 0f64);
for game in games {
let participants = match game.get("participants").and_then(Value::as_array) {
Some(p) => p,
@@ -365,11 +390,20 @@ pub fn trend_rows(games: &[Value], puuid: &str, champions: &Value) -> Value {
let identities = game.get("participantIdentities").and_then(Value::as_array);
let pid = identities.and_then(|ids| {
ids.iter()
- .find(|i| i.get("player").and_then(|p| p.get("puuid")).and_then(Value::as_str) == Some(puuid))
+ .find(|i| {
+ i.get("player")
+ .and_then(|p| p.get("puuid"))
+ .and_then(Value::as_str)
+ == Some(puuid)
+ })
.and_then(|i| i.get("participantId").and_then(Value::as_i64))
});
- pid.and_then(|pid| participants.iter().find(|p| p.get("participantId").and_then(Value::as_i64) == Some(pid)))
- .or_else(|| participants.first())
+ pid.and_then(|pid| {
+ participants
+ .iter()
+ .find(|p| p.get("participantId").and_then(Value::as_i64) == Some(pid))
+ })
+ .or_else(|| participants.first())
};
let me = match me {
Some(m) => m,
@@ -378,9 +412,15 @@ pub fn trend_rows(games: &[Value], puuid: &str, champions: &Value) -> Value {
let stats = me.get("stats").cloned().unwrap_or(Value::Null);
let f = |key: &str| stats.get(key).and_then(Value::as_f64).unwrap_or(0.0);
let win = stats.get("win").and_then(Value::as_bool).unwrap_or(false);
- let duration = game.get("gameDuration").and_then(Value::as_f64).unwrap_or(0.0);
+ let duration = game
+ .get("gameDuration")
+ .and_then(Value::as_f64)
+ .unwrap_or(0.0);
let mins = duration / 60.0;
- let champ = champion_name(champions, me.get("championId").and_then(Value::as_i64).unwrap_or(0));
+ let champ = champion_name(
+ champions,
+ me.get("championId").and_then(Value::as_i64).unwrap_or(0),
+ );
let role = me
.get("timeline")
.and_then(|t| t.get("teamPosition").or_else(|| t.get("lane")))
@@ -448,15 +488,26 @@ pub fn trend_rows(games: &[Value], puuid: &str, champions: &Value) -> Value {
/// Trends over the last N games of the current player.
#[tauri::command]
-pub async fn league_coach_trends(count: Option<u32>, style: Option<String>, language: Option<String>) -> Result<String, String> {
+pub async fn league_coach_trends(
+ count: Option<u32>,
+ style: Option<String>,
+ language: Option<String>,
+) -> Result<String, String> {
ensure_enabled()?;
let client = get_client().await?;
let count = count.unwrap_or(20).clamp(5, 40);
let me = lcu_get_raw(&client, "/lol-summoner/v1/current-summoner").await?;
- let puuid = me.get("puuid").and_then(Value::as_str).unwrap_or("").to_string();
+ let puuid = me
+ .get("puuid")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
let history = lcu_get_raw(
&client,
- &format!("/lol-match-history/v1/products/lol/current-summoner/matches?begIndex=0&endIndex={}", count.saturating_sub(1)),
+ &format!(
+ "/lol-match-history/v1/products/lol/current-summoner/matches?begIndex=0&endIndex={}",
+ count.saturating_sub(1)
+ ),
)
.await?;
let games: Vec<Value> = history
@@ -492,7 +543,10 @@ async fn live_context(client: &LcuClient, champions: &Value) -> Value {
let mut context = json!({ "phase": phase });
if phase == "ChampSelect" {
if let Ok(session) = lcu_get_raw(client, "/lol-champ-select/v1/session").await {
- let cell = session.get("localPlayerCellId").and_then(Value::as_i64).unwrap_or(-1);
+ let cell = session
+ .get("localPlayerCellId")
+ .and_then(Value::as_i64)
+ .unwrap_or(-1);
let team = |key: &str| -> Vec<Value> {
session
.get(key)
@@ -513,9 +567,20 @@ async fn live_context(client: &LcuClient, champions: &Value) -> Value {
};
let allies = team("myTeam");
let enemies = team("theirTeam");
- let me = allies.iter().find(|m| m.get("me") == Some(&json!(true))).cloned();
- let my_champ = me.as_ref().and_then(|m| m.get("champion").and_then(Value::as_str)).unwrap_or("?").to_string();
- let my_pos = me.as_ref().and_then(|m| m.get("position").and_then(Value::as_str)).unwrap_or("").to_string();
+ let me = allies
+ .iter()
+ .find(|m| m.get("me") == Some(&json!(true)))
+ .cloned();
+ let my_champ = me
+ .as_ref()
+ .and_then(|m| m.get("champion").and_then(Value::as_str))
+ .unwrap_or("?")
+ .to_string();
+ let my_pos = me
+ .as_ref()
+ .and_then(|m| m.get("position").and_then(Value::as_str))
+ .unwrap_or("")
+ .to_string();
context["allies"] = json!(allies);
context["enemies"] = json!(enemies);
if my_champ != "?" {
@@ -528,9 +593,16 @@ async fn live_context(client: &LcuClient, champions: &Value) -> Value {
// in the same position; enemies do not expose positions, so the
// first enemy champion is offered when the position is a lane.
if position != "all" {
- if let Some(enemy) = enemies.iter().find_map(|e| e.get("champion").and_then(Value::as_str)).filter(|c| *c != "?") {
- if let Some(guide) = opgg_matchup(&champ_key, &opgg_champion_name(enemy), position).await {
- context["opggMatchupSample"] = json!({ "opponent": enemy, "guide": guide });
+ if let Some(enemy) = enemies
+ .iter()
+ .find_map(|e| e.get("champion").and_then(Value::as_str))
+ .filter(|c| *c != "?")
+ {
+ if let Some(guide) =
+ opgg_matchup(&champ_key, &opgg_champion_name(enemy), position).await
+ {
+ context["opggMatchupSample"] =
+ json!({ "opponent": enemy, "guide": guide });
}
}
}
@@ -562,7 +634,11 @@ async fn live_context(client: &LcuClient, champions: &Value) -> Value {
/// Free question, answered against whatever the client is doing right now.
#[tauri::command]
-pub async fn league_coach_ask(question: String, style: Option<String>, language: Option<String>) -> Result<String, String> {
+pub async fn league_coach_ask(
+ question: String,
+ style: Option<String>,
+ language: Option<String>,
+) -> Result<String, String> {
ensure_enabled()?;
let question = question.trim().to_string();
if question.is_empty() {
@@ -575,10 +651,24 @@ pub async fn league_coach_ask(question: String, style: Option<String>, language:
let champions = champion_summary(&client).await;
let mut context = live_context(&client, &champions).await;
// Outside a game the last few results give the model something to anchor on.
- if context.get("phase").and_then(Value::as_str).map(|p| p != "ChampSelect" && p != "InProgress").unwrap_or(true) {
+ if context
+ .get("phase")
+ .and_then(Value::as_str)
+ .map(|p| p != "ChampSelect" && p != "InProgress")
+ .unwrap_or(true)
+ {
if let Ok(me) = lcu_get_raw(&client, "/lol-summoner/v1/current-summoner").await {
- let puuid = me.get("puuid").and_then(Value::as_str).unwrap_or("").to_string();
- if let Ok(history) = lcu_get_raw(&client, "/lol-match-history/v1/products/lol/current-summoner/matches?begIndex=0&endIndex=7").await {
+ let puuid = me
+ .get("puuid")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ if let Ok(history) = lcu_get_raw(
+ &client,
+ "/lol-match-history/v1/products/lol/current-summoner/matches?begIndex=0&endIndex=7",
+ )
+ .await
+ {
let games: Vec<Value> = history
.get("games")
.and_then(|g| g.get("games"))
diff --git a/src-tauri/src/commands/league/mod.rs b/src-tauri/src/commands/league/mod.rs
index 1f1871dd..3dbd9a08 100644
--- a/src-tauri/src/commands/league/mod.rs
+++ b/src-tauri/src/commands/league/mod.rs
@@ -1743,7 +1743,11 @@ pub async fn league_player_history(
let local_games = local
.as_ref()
.ok()
- .and_then(|h| h.get("games").and_then(|g| g.get("games")).and_then(Value::as_array))
+ .and_then(|h| {
+ h.get("games")
+ .and_then(|g| g.get("games"))
+ .and_then(Value::as_array)
+ })
.map(|a| a.len())
.unwrap_or(0);
if local_games > 0 {
@@ -1752,7 +1756,9 @@ pub async fn league_player_history(
// Nothing locally: the backend may still have it.
let count = (end - beg + 1).clamp(1, 50) as u32;
match sgp::match_history_local(&client, &puuid, beg as u32, count).await {
- Ok(games) if !games.is_empty() => Ok(json!({ "games": { "games": games }, "source": "sgp" })),
+ Ok(games) if !games.is_empty() => {
+ Ok(json!({ "games": { "games": games }, "source": "sgp" }))
+ }
_ => local,
}
}
diff --git a/src-tauri/src/commands/league/profile.rs b/src-tauri/src/commands/league/profile.rs
index 8301c2c7..2bda4c92 100644
--- a/src-tauri/src/commands/league/profile.rs
+++ b/src-tauri/src/commands/league/profile.rs
@@ -3,8 +3,8 @@
//! payloads mirror what league_profile_tool and league-tools send (both MIT).
use super::{ensure_enabled, get_client, lcu_get_raw, lcu_send, LcuClient};
-use serde_json::{json, Value};
use rand::RngExt;
+use serde_json::{json, Value};
const QUEUES: [&str; 3] = ["RANKED_SOLO_5x5", "RANKED_FLEX_SR", "RANKED_TFT"];
const TIERS: [&str; 11] = [
@@ -65,7 +65,11 @@ pub fn summary_preferences(summary: &Value) -> (Vec<i64>, String, String) {
.unwrap_or_default();
let banner = summary
.get("bannerAccent")
- .and_then(|b| b.as_str().map(str::to_string).or_else(|| b.as_i64().map(|n| n.to_string())))
+ .and_then(|b| {
+ b.as_str()
+ .map(str::to_string)
+ .or_else(|| b.as_i64().map(|n| n.to_string()))
+ })
.filter(|b| b != "-1" && !b.is_empty())
.unwrap_or_else(|| "1".to_string());
(tokens, title, banner)
@@ -77,13 +81,19 @@ pub async fn league_profile_state() -> Result<Value, String> {
ensure_enabled()?;
let client = get_client().await?;
let me = chat_me(&client).await?;
- let summary = lcu_get_raw(&client, "/lol-challenges/v1/summary-player-data/local-player")
- .await
- .unwrap_or(Value::Null);
+ let summary = lcu_get_raw(
+ &client,
+ "/lol-challenges/v1/summary-player-data/local-player",
+ )
+ .await
+ .unwrap_or(Value::Null);
let (tokens, title, banner) = summary_preferences(&summary);
- let profile = lcu_get_raw(&client, "/lol-summoner/v1/current-summoner/summoner-profile")
- .await
- .unwrap_or(Value::Null);
+ let profile = lcu_get_raw(
+ &client,
+ "/lol-summoner/v1/current-summoner/summoner-profile",
+ )
+ .await
+ .unwrap_or(Value::Null);
let regalia = lcu_get_raw(&client, "/lol-regalia/v2/current-summoner/regalia")
.await
.unwrap_or(Value::Null);
@@ -132,7 +142,11 @@ pub async fn league_profile_state() -> Result<Value, String> {
/// Rank shown on the chat hovercard and social cards. Only the `lol` block is
/// patched, so presence data the client keeps there survives.
#[tauri::command]
-pub async fn league_set_chat_rank(queue: String, tier: String, division: String) -> Result<Value, String> {
+pub async fn league_set_chat_rank(
+ queue: String,
+ tier: String,
+ division: String,
+) -> Result<Value, String> {
ensure_enabled()?;
if !QUEUES.contains(&queue.as_str()) {
return Err("invalid queue".to_string());
@@ -145,7 +159,11 @@ pub async fn league_set_chat_rank(queue: String, tier: String, division: String)
return Err("invalid division".to_string());
}
let client = get_client().await?;
- let tier_value = if tier == "UNRANKED" { "" } else { tier.as_str() };
+ let tier_value = if tier == "UNRANKED" {
+ ""
+ } else {
+ tier.as_str()
+ };
lcu_send(
&client,
reqwest::Method::PUT,
@@ -246,7 +264,10 @@ pub async fn league_challenges() -> Result<Value, String> {
.iter()
.filter_map(|c| {
let id = c.get("id").and_then(Value::as_i64)?;
- let level = c.get("currentLevel").and_then(Value::as_str).unwrap_or("NONE");
+ let level = c
+ .get("currentLevel")
+ .and_then(Value::as_str)
+ .unwrap_or("NONE");
if id <= 0 || level == "NONE" {
return None;
}
@@ -305,9 +326,12 @@ pub async fn league_set_challenge_prefs(
) -> Result<Value, String> {
ensure_enabled()?;
let client = get_client().await?;
- let summary = lcu_get_raw(&client, "/lol-challenges/v1/summary-player-data/local-player")
- .await
- .unwrap_or(Value::Null);
+ let summary = lcu_get_raw(
+ &client,
+ "/lol-challenges/v1/summary-player-data/local-player",
+ )
+ .await
+ .unwrap_or(Value::Null);
let (current_tokens, current_title, current_banner) = summary_preferences(&summary);
let ids = challenge_ids.unwrap_or(current_tokens);
if ids.len() > 3 || ids.iter().any(|id| *id < 0) {
@@ -479,7 +503,10 @@ pub async fn league_random_champion(class: Option<String>) -> Result<Value, Stri
/// Hovers (or locks) a champion in the local player's open pick action.
#[tauri::command]
-pub async fn league_declare_champion(champion_id: i64, lock: Option<bool>) -> Result<Value, String> {
+pub async fn league_declare_champion(
+ champion_id: i64,
+ lock: Option<bool>,
+) -> Result<Value, String> {
ensure_enabled()?;
if champion_id <= 0 {
return Err("invalid champion".to_string());
@@ -522,9 +549,18 @@ mod tests {
"title": { "itemId": 77 },
"bannerAccent": "5"
});
- assert_eq!(summary_preferences(&summary), (vec![1, 2, 3], "77".to_string(), "5".to_string()));
+ assert_eq!(
+ summary_preferences(&summary),
+ (vec![1, 2, 3], "77".to_string(), "5".to_string())
+ );
let empty = json!({ "title": { "itemId": -1 }, "bannerAccent": "-1" });
- assert_eq!(summary_preferences(&empty), (vec![], String::new(), "1".to_string()));
- assert_eq!(summary_preferences(&Value::Null), (vec![], String::new(), "1".to_string()));
+ assert_eq!(
+ summary_preferences(&empty),
+ (vec![], String::new(), "1".to_string())
+ );
+ assert_eq!(
+ summary_preferences(&Value::Null),
+ (vec![], String::new(), "1".to_string())
+ );
}
}
diff --git a/src-tauri/src/commands/league/sgp.rs b/src-tauri/src/commands/league/sgp.rs
index 2a87d42b..0a657739 100644
--- a/src-tauri/src/commands/league/sgp.rs
+++ b/src-tauri/src/commands/league/sgp.rs
@@ -25,22 +25,102 @@ pub struct Server {
}
const SERVERS: &[Server] = &[
- Server { id: "BR1", match_history: "https://usw2-red.pp.sgp.pvp.net", common: "https://br-red.lol.sgp.pvp.net", region_path: None },
- Server { id: "NA1", match_history: "https://usw2-red.pp.sgp.pvp.net", common: "https://na-red.lol.sgp.pvp.net", region_path: None },
- Server { id: "LA1", match_history: "https://usw2-red.pp.sgp.pvp.net", common: "https://lan-red.lol.sgp.pvp.net", region_path: None },
- Server { id: "LA2", match_history: "https://usw2-red.pp.sgp.pvp.net", common: "https://las-red.lol.sgp.pvp.net", region_path: None },
- Server { id: "PBE", match_history: "https://usw2-red.pp.sgp.pvp.net", common: "https://pbe-red.lol.sgp.pvp.net", region_path: Some("PBE1") },
- Server { id: "EUW", match_history: "https://euc1-red.pp.sgp.pvp.net", common: "https://euw-red.lol.sgp.pvp.net", region_path: Some("EUW1") },
- Server { id: "RU", match_history: "https://euc1-red.pp.sgp.pvp.net", common: "https://ru-red.lol.sgp.pvp.net", region_path: None },
- Server { id: "TR1", match_history: "https://euc1-red.pp.sgp.pvp.net", common: "https://tr-red.lol.sgp.pvp.net", region_path: None },
- Server { id: "JP", match_history: "https://apne1-red.pp.sgp.pvp.net", common: "https://jp-red.lol.sgp.pvp.net", region_path: Some("JP1") },
- Server { id: "KR", match_history: "https://apne1-red.pp.sgp.pvp.net", common: "https://kr-red.lol.sgp.pvp.net", region_path: None },
- Server { id: "OC1", match_history: "https://apse1-red.pp.sgp.pvp.net", common: "https://oce-red.lol.sgp.pvp.net", region_path: None },
- Server { id: "TW2", match_history: "https://apse1-red.pp.sgp.pvp.net", common: "https://tw2-red.lol.sgp.pvp.net", region_path: None },
- Server { id: "SG2", match_history: "https://apse1-red.pp.sgp.pvp.net", common: "https://sg2-red.lol.sgp.pvp.net", region_path: None },
- Server { id: "PH2", match_history: "https://apse1-red.pp.sgp.pvp.net", common: "https://ph2-red.lol.sgp.pvp.net", region_path: None },
- Server { id: "VN2", match_history: "https://apse1-red.pp.sgp.pvp.net", common: "https://vn2-red.lol.sgp.pvp.net", region_path: None },
- Server { id: "TH2", match_history: "https://apse1-red.pp.sgp.pvp.net", common: "https://th2-red.lol.sgp.pvp.net", region_path: None },
+ Server {
+ id: "BR1",
+ match_history: "https://usw2-red.pp.sgp.pvp.net",
+ common: "https://br-red.lol.sgp.pvp.net",
+ region_path: None,
+ },
+ Server {
+ id: "NA1",
+ match_history: "https://usw2-red.pp.sgp.pvp.net",
+ common: "https://na-red.lol.sgp.pvp.net",
+ region_path: None,
+ },
+ Server {
+ id: "LA1",
+ match_history: "https://usw2-red.pp.sgp.pvp.net",
+ common: "https://lan-red.lol.sgp.pvp.net",
+ region_path: None,
+ },
+ Server {
+ id: "LA2",
+ match_history: "https://usw2-red.pp.sgp.pvp.net",
+ common: "https://las-red.lol.sgp.pvp.net",
+ region_path: None,
+ },
+ Server {
+ id: "PBE",
+ match_history: "https://usw2-red.pp.sgp.pvp.net",
+ common: "https://pbe-red.lol.sgp.pvp.net",
+ region_path: Some("PBE1"),
+ },
+ Server {
+ id: "EUW",
+ match_history: "https://euc1-red.pp.sgp.pvp.net",
+ common: "https://euw-red.lol.sgp.pvp.net",
+ region_path: Some("EUW1"),
+ },
+ Server {
+ id: "RU",
+ match_history: "https://euc1-red.pp.sgp.pvp.net",
+ common: "https://ru-red.lol.sgp.pvp.net",
+ region_path: None,
+ },
+ Server {
+ id: "TR1",
+ match_history: "https://euc1-red.pp.sgp.pvp.net",
+ common: "https://tr-red.lol.sgp.pvp.net",
+ region_path: None,
+ },
+ Server {
+ id: "JP",
+ match_history: "https://apne1-red.pp.sgp.pvp.net",
+ common: "https://jp-red.lol.sgp.pvp.net",
+ region_path: Some("JP1"),
+ },
+ Server {
+ id: "KR",
+ match_history: "https://apne1-red.pp.sgp.pvp.net",
+ common: "https://kr-red.lol.sgp.pvp.net",
+ region_path: None,
+ },
+ Server {
+ id: "OC1",
+ match_history: "https://apse1-red.pp.sgp.pvp.net",
+ common: "https://oce-red.lol.sgp.pvp.net",
+ region_path: None,
+ },
+ Server {
+ id: "TW2",
+ match_history: "https://apse1-red.pp.sgp.pvp.net",
+ common: "https://tw2-red.lol.sgp.pvp.net",
+ region_path: None,
+ },
+ Server {
+ id: "SG2",
+ match_history: "https://apse1-red.pp.sgp.pvp.net",
+ common: "https://sg2-red.lol.sgp.pvp.net",
+ region_path: None,
+ },
+ Server {
+ id: "PH2",
+ match_history: "https://apse1-red.pp.sgp.pvp.net",
+ common: "https://ph2-red.lol.sgp.pvp.net",
+ region_path: None,
+ },
+ Server {
+ id: "VN2",
+ match_history: "https://apse1-red.pp.sgp.pvp.net",
+ common: "https://vn2-red.lol.sgp.pvp.net",
+ region_path: None,
+ },
+ Server {
+ id: "TH2",
+ match_history: "https://apse1-red.pp.sgp.pvp.net",
+ common: "https://th2-red.lol.sgp.pvp.net",
+ region_path: None,
+ },
];
/// Normalises the region the client reports into a server id. Some clients
@@ -135,8 +215,12 @@ async fn target(client: &LcuClient) -> Result<Target, String> {
if !enabled() {
return Err("sgp disabled".to_string());
}
- let region = client.region.clone().ok_or_else(|| "region unknown".to_string())?;
- let server = server_for(&region).ok_or_else(|| format!("region {} has no sgp config", region))?;
+ let region = client
+ .region
+ .clone()
+ .ok_or_else(|| "region unknown".to_string())?;
+ let server =
+ server_for(&region).ok_or_else(|| format!("region {} has no sgp config", region))?;
let tokens = tokens(client).await?;
Ok(Target { server, tokens })
}
@@ -152,7 +236,9 @@ async fn send(
path: &str,
body: Option<Value>,
) -> Result<reqwest::Response, String> {
- let http = HTTP.clone().ok_or_else(|| "http client init failed".to_string())?;
+ let http = HTTP
+ .clone()
+ .ok_or_else(|| "http client init failed".to_string())?;
let (host, token) = match kind {
TokenKind::Entitlements => (target.server.match_history, &target.tokens.entitlements),
TokenKind::LeagueSession => (target.server.common, &target.tokens.league_session),
@@ -187,7 +273,12 @@ async fn get_json(target: &Target, kind: TokenKind, path: &str) -> Result<Value,
}
/// Match history in the client's own (match-v5 style) shape.
-async fn match_history_raw(target: &Target, puuid: &str, start: u32, count: u32) -> Result<Value, String> {
+async fn match_history_raw(
+ target: &Target,
+ puuid: &str,
+ start: u32,
+ count: u32,
+) -> Result<Value, String> {
get_json(
target,
TokenKind::Entitlements,
@@ -270,13 +361,23 @@ pub fn game_to_local(game: &Value, puuid: &str) -> Option<Value> {
/// Games for a player from the backend, already in the local shape. Empty
/// (not an error) when SGP is off or the region is unsupported, so callers can
/// fall through quietly.
-pub(crate) async fn match_history_local(client: &LcuClient, puuid: &str, start: u32, count: u32) -> Result<Vec<Value>, String> {
+pub(crate) async fn match_history_local(
+ client: &LcuClient,
+ puuid: &str,
+ start: u32,
+ count: u32,
+) -> Result<Vec<Value>, String> {
let target = target(client).await?;
let raw = match_history_raw(&target, puuid, start, count.min(50)).await?;
Ok(raw
.get("games")
.and_then(Value::as_array)
- .map(|games| games.iter().filter_map(|g| game_to_local(g, puuid)).collect())
+ .map(|games| {
+ games
+ .iter()
+ .filter_map(|g| game_to_local(g, puuid))
+ .collect()
+ })
.unwrap_or_default())
}
@@ -311,13 +412,18 @@ pub async fn league_sgp_status() -> Result<SgpStatus, String> {
/// Match history for any player, straight from the backend.
#[tauri::command]
-pub async fn league_sgp_match_history(puuid: String, start: Option<u32>, count: Option<u32>) -> Result<Value, String> {
+pub async fn league_sgp_match_history(
+ puuid: String,
+ start: Option<u32>,
+ count: Option<u32>,
+) -> Result<Value, String> {
ensure_enabled()?;
if puuid.is_empty() || !puuid.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
return Err("invalid player".to_string());
}
let client = get_client().await?;
- let games = match_history_local(&client, &puuid, start.unwrap_or(0), count.unwrap_or(20)).await?;
+ let games =
+ match_history_local(&client, &puuid, start.unwrap_or(0), count.unwrap_or(20)).await?;
Ok(json!({ "games": { "games": games }, "source": "sgp" }))
}
@@ -352,11 +458,17 @@ pub async fn league_sgp_summoners(puuids: Vec<String>) -> Result<Value, String>
"/summoner-ledge/v1/regions/{}/summoners/puuids",
region_segment(&target.server)
);
- send(&target, TokenKind::LeagueSession, reqwest::Method::POST, &path, Some(json!(puuids)))
- .await?
- .json::<Value>()
- .await
- .map_err(|e| format!("sgp decode failed: {}", e))
+ send(
+ &target,
+ TokenKind::LeagueSession,
+ reqwest::Method::POST,
+ &path,
+ Some(json!(puuids)),
+ )
+ .await?
+ .json::<Value>()
+ .await
+ .map_err(|e| format!("sgp decode failed: {}", e))
}
/// Downloads the replay file for a game into the default download folder.
@@ -373,7 +485,14 @@ pub async fn league_sgp_download_replay(game_id: i64) -> Result<String, String>
"/match-history-query/v3/product/lol/matchId/{}_{}/infoType/replay",
region, game_id
);
- let response = send(&target, TokenKind::Entitlements, reqwest::Method::GET, &path, None).await?;
+ let response = send(
+ &target,
+ TokenKind::Entitlements,
+ reqwest::Method::GET,
+ &path,
+ None,
+ )
+ .await?;
let bytes = response
.bytes()
.await
@@ -405,7 +524,10 @@ mod tests {
assert_eq!(server_id("euw"), "EUW");
assert_eq!(server_id("OCE"), "OC1");
assert!(server_for("BR").is_some());
- assert!(server_for("EUN1").is_none(), "no host is guessed for a region outside the table");
+ assert!(
+ server_for("EUN1").is_none(),
+ "no host is guessed for a region outside the table"
+ );
assert_eq!(server_for("EUW").unwrap().region_path, Some("EUW1"));
assert_eq!(region_segment(&server_for("BR1").unwrap()), "BR1");
}
@@ -437,7 +559,10 @@ mod tests {
assert_eq!(p["stats"]["item5"], 0);
assert_eq!(p["timeline"]["lane"], "MIDDLE");
assert_eq!(local["participantIdentities"][0]["player"]["puuid"], "me");
- assert_eq!(local["participantIdentities"][0]["player"]["gameName"], "Me");
+ assert_eq!(
+ local["participantIdentities"][0]["player"]["gameName"],
+ "Me"
+ );
assert!(game_to_local(&json!({ "json": {} }), "me").is_none());
}
}
diff --git a/src-tauri/src/commands/league/skins.rs b/src-tauri/src/commands/league/skins.rs
index 244cb8fa..8e6141d7 100644
--- a/src-tauri/src/commands/league/skins.rs
+++ b/src-tauri/src/commands/league/skins.rs
@@ -73,7 +73,11 @@ pub fn selectable_skins(carousel: &Value) -> Vec<SkinOption> {
.unwrap_or_default();
Some(SkinOption {
id: s.get("id").and_then(Value::as_i64)?,
- name: s.get("name").and_then(Value::as_str).unwrap_or("").to_string(),
+ name: s
+ .get("name")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string(),
is_base: s.get("isBase").and_then(Value::as_bool).unwrap_or(false),
chromas,
})
@@ -120,7 +124,11 @@ pub fn roll<R: rand::Rng>(
let skin = pool[rng.random_range(0..pool.len())];
// Slot 0 is "no chroma"; each chroma takes one more slot.
let slot = rng.random_range(0..=skin.chromas.len());
- let chroma = if slot == 0 { None } else { skin.chromas.get(slot - 1) };
+ let chroma = if slot == 0 {
+ None
+ } else {
+ skin.chromas.get(slot - 1)
+ };
Some(Roll {
skin_id: skin.id,
skin_name: skin.name.clone(),
@@ -130,8 +138,7 @@ pub fn roll<R: rand::Rng>(
}
/// Recent rolls per champion, so the same skin does not come back every game.
-static HISTORY: Lazy<Mutex<HashMap<i64, VecDeque<i64>>>> =
- Lazy::new(|| Mutex::new(HashMap::new()));
+static HISTORY: Lazy<Mutex<HashMap<i64, VecDeque<i64>>>> = Lazy::new(|| Mutex::new(HashMap::new()));
/// Champion the automatic roll already handled in this champ select.
static ROLLED_FOR: Lazy<Mutex<Option<i64>>> = Lazy::new(|| Mutex::new(None));
static WARD_ROLLED: Lazy<Mutex<bool>> = Lazy::new(|| Mutex::new(false));
@@ -159,7 +166,11 @@ async fn recent(champion_id: i64) -> Vec<i64> {
.unwrap_or_default()
}
-async fn roll_and_apply(client: &LcuClient, champion_id: i64, include_base: bool) -> Result<Roll, String> {
+async fn roll_and_apply(
+ client: &LcuClient,
+ champion_id: i64,
+ include_base: bool,
+) -> Result<Roll, String> {
let carousel = lcu_get_raw(client, "/lol-champ-select/v1/skin-carousel-skins").await?;
let skins = selectable_skins(&carousel);
let history = recent(champion_id).await;
@@ -271,7 +282,9 @@ pub(crate) async fn on_champ_select(
let already = { *ROLLED_FOR.lock().await == Some(champion) };
if !already {
*ROLLED_FOR.lock().await = Some(champion);
- if let Err(e) = roll_and_apply(client, champion, settings.skin_roulette_include_base).await {
+ if let Err(e) =
+ roll_and_apply(client, champion, settings.skin_roulette_include_base).await
+ {
tracing::debug!("[league] skin roulette skipped: {}", e);
}
}
@@ -297,7 +310,8 @@ pub async fn league_roll_skin(include_base: Option<bool>) -> Result<Roll, String
if champion <= 0 {
return Err("lock a champion first".to_string());
}
- let include_base = include_base.unwrap_or_else(|| super::league_settings().skin_roulette_include_base);
+ let include_base =
+ include_base.unwrap_or_else(|| super::league_settings().skin_roulette_include_base);
roll_and_apply(&client, champion, include_base).await
}
@@ -337,7 +351,11 @@ mod tests {
is_base: base,
chromas: chromas
.iter()
- .map(|c| Chroma { id: *c, name: format!("chroma {}", c), colors: vec![] })
+ .map(|c| Chroma {
+ id: *c,
+ name: format!("chroma {}", c),
+ colors: vec![],
+ })
.collect(),
}
}
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index 44379755..ac393363 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -29,8 +29,8 @@ pub mod yt_templates;
#[cfg(not(target_os = "android"))]
pub mod dependencies;
#[cfg(not(target_os = "android"))]
+pub mod search;
+#[cfg(not(target_os = "android"))]
pub mod spicetify;
#[cfg(not(target_os = "android"))]
pub mod tools;
-#[cfg(not(target_os = "android"))]
-pub mod search;
diff --git a/src-tauri/src/commands/spicetify.rs b/src-tauri/src/commands/spicetify.rs
index 9c85a546..c054a227 100644
--- a/src-tauri/src/commands/spicetify.rs
+++ b/src-tauri/src/commands/spicetify.rs
@@ -55,11 +55,18 @@ pub async fn spicetify_set_theme(theme: String, scheme: String) -> Result<CmdOut
if theme.contains(['/', '\\', '|']) || scheme.contains(['/', '\\', '|']) {
return Err("nome de tema invalido".into());
}
- spicetify::run_ok(&bin, &["config", "current_theme", theme, "color_scheme", scheme])
- .await
- .map_err(err)?;
+ spicetify::run_ok(
+ &bin,
+ &["config", "current_theme", theme, "color_scheme", scheme],
+ )
+ .await
+ .map_err(err)?;
let status = spicetify::status().await;
- let args: &[&str] = if status.applied { &["apply"] } else { &["backup", "apply"] };
+ let args: &[&str] = if status.applied {
+ &["apply"]
+ } else {
+ &["backup", "apply"]
+ };
spicetify::run_ok(&bin, args).await.map_err(err)
}
diff --git a/src-tauri/src/commands/tools/ai.rs b/src-tauri/src/commands/tools/ai.rs
index 23f73808..881e874e 100644
--- a/src-tauri/src/commands/tools/ai.rs
+++ b/src-tauri/src/commands/tools/ai.rs
@@ -14,13 +14,21 @@ pub fn tool_ollama_recommended() -> Vec<ollama::Recommended> {
}
#[tauri::command]
-pub async fn tool_ollama_pull(app: tauri::AppHandle, host: Option<String>, name: String) -> Result<(), String> {
- ollama::pull(host.as_deref().unwrap_or(""), &name, progress(&app)).await.map_err(err)
+pub async fn tool_ollama_pull(
+ app: tauri::AppHandle,
+ host: Option<String>,
+ name: String,
+) -> Result<(), String> {
+ ollama::pull(host.as_deref().unwrap_or(""), &name, progress(&app))
+ .await
+ .map_err(err)
}
#[tauri::command]
pub async fn tool_ollama_delete(host: Option<String>, name: String) -> Result<(), String> {
- ollama::delete(host.as_deref().unwrap_or(""), &name).await.map_err(err)
+ ollama::delete(host.as_deref().unwrap_or(""), &name)
+ .await
+ .map_err(err)
}
#[tauri::command]
@@ -29,8 +37,14 @@ pub async fn tool_pricing_info(force: Option<bool>) -> Result<pricing::PricingIn
}
#[tauri::command]
-pub async fn tool_pricing_search(query: String, mode: Option<String>, limit: Option<usize>) -> Result<Vec<pricing::ModelPrice>, String> {
- pricing::search(&query, mode.as_deref().unwrap_or(""), limit.unwrap_or(60)).await.map_err(err)
+pub async fn tool_pricing_search(
+ query: String,
+ mode: Option<String>,
+ limit: Option<usize>,
+) -> Result<Vec<pricing::ModelPrice>, String> {
+ pricing::search(&query, mode.as_deref().unwrap_or(""), limit.unwrap_or(60))
+ .await
+ .map_err(err)
}
#[tauri::command]
@@ -83,7 +97,11 @@ pub async fn tool_keys_balance(id: String) -> Result<ai_keys::KeyView, String> {
#[tauri::command]
pub async fn tool_keys_models(entry: ai_keys::KeyEntry) -> Result<Vec<String>, String> {
// Chave salva: a UI manda `key` vazia e o id; buscamos o segredo aqui.
- let e = if entry.key.is_empty() && !entry.id.is_empty() { ai_keys::entry_with_secret(&entry.id).map_err(err)? } else { entry };
+ let e = if entry.key.is_empty() && !entry.id.is_empty() {
+ ai_keys::entry_with_secret(&entry.id).map_err(err)?
+ } else {
+ entry
+ };
ai_keys::models(&e).await.map_err(err)
}
@@ -113,7 +131,11 @@ pub struct McpStatus {
#[tauri::command]
pub fn tool_mcp_status(app: tauri::AppHandle) -> McpStatus {
let settings = crate::storage::config::load_settings(&app);
- let url = if settings.bridge.port == 0 { String::new() } else { format!("http://127.0.0.1:{}/mcp", settings.bridge.port) };
+ let url = if settings.bridge.port == 0 {
+ String::new()
+ } else {
+ format!("http://127.0.0.1:{}/mcp", settings.bridge.port)
+ };
McpStatus {
enabled: crate::mcp::enabled(),
bridge_enabled: settings.bridge.enabled,
@@ -140,12 +162,41 @@ pub async fn tool_mcp_selftest(app: tauri::AppHandle) -> Result<String, String>
return Err("bridge sem porta".into());
}
let url = format!("http://127.0.0.1:{}/mcp", settings.bridge.port);
- let client = reqwest::Client::builder().timeout(std::time::Duration::from_secs(10)).build().map_err(err)?;
+ let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(10))
+ .build()
+ .map_err(err)?;
let init = serde_json::json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": crate::mcp::PROTOCOL, "capabilities": {}, "clientInfo": { "name": "omniget-selftest", "version": "1" } } });
- let r: serde_json::Value = client.post(&url).bearer_auth(&settings.bridge.token).json(&init).send().await.map_err(err)?.error_for_status().map_err(err)?.json().await.map_err(err)?;
- let version = r["result"]["protocolVersion"].as_str().unwrap_or("?").to_string();
+ let r: serde_json::Value = client
+ .post(&url)
+ .bearer_auth(&settings.bridge.token)
+ .json(&init)
+ .send()
+ .await
+ .map_err(err)?
+ .error_for_status()
+ .map_err(err)?
+ .json()
+ .await
+ .map_err(err)?;
+ let version = r["result"]["protocolVersion"]
+ .as_str()
+ .unwrap_or("?")
+ .to_string();
let list = serde_json::json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/list" });
- let r: serde_json::Value = client.post(&url).bearer_auth(&settings.bridge.token).json(&list).send().await.map_err(err)?.json().await.map_err(err)?;
- let n = r["result"]["tools"].as_array().map(|a| a.len()).unwrap_or(0);
+ let r: serde_json::Value = client
+ .post(&url)
+ .bearer_auth(&settings.bridge.token)
+ .json(&list)
+ .send()
+ .await
+ .map_err(err)?
+ .json()
+ .await
+ .map_err(err)?;
+ let n = r["result"]["tools"]
+ .as_array()
+ .map(|a| a.len())
+ .unwrap_or(0);
Ok(format!("{} · {} tools · {}", version, n, url))
}
diff --git a/src-tauri/src/commands/tools/desktop.rs b/src-tauri/src/commands/tools/desktop.rs
index 24e5d15d..30a63549 100644
--- a/src-tauri/src/commands/tools/desktop.rs
+++ b/src-tauri/src/commands/tools/desktop.rs
@@ -19,7 +19,10 @@ fn hotkeys_file() -> Option<std::path::PathBuf> {
}
pub fn tool_hotkeys() -> HashMap<String, String> {
- hotkeys_file().and_then(|p| std::fs::read_to_string(p).ok()).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
+ hotkeys_file()
+ .and_then(|p| std::fs::read_to_string(p).ok())
+ .and_then(|s| serde_json::from_str(&s).ok())
+ .unwrap_or_default()
}
fn save_hotkeys(map: &HashMap<String, String>) -> Result<(), String> {
@@ -34,7 +37,12 @@ pub fn register_tool_hotkeys(app: &tauri::AppHandle) {
match binding.parse::<Shortcut>() {
Ok(s) => {
if let Err(e) = app.global_shortcut().register(s) {
- tracing::warn!("[tools] atalho {} ({}) nao registrou: {}", binding, action, e);
+ tracing::warn!(
+ "[tools] atalho {} ({}) nao registrou: {}",
+ binding,
+ action,
+ e
+ );
}
}
Err(e) => tracing::warn!("[tools] atalho invalido {}: {}", binding, e),
@@ -44,7 +52,14 @@ pub fn register_tool_hotkeys(app: &tauri::AppHandle) {
/// Qual ação de tool este atalho dispara, se alguma.
pub fn action_for(shortcut: &Shortcut) -> Option<String> {
- tool_hotkeys().into_iter().find(|(_, b)| b.parse::<Shortcut>().map(|s| s == *shortcut).unwrap_or(false)).map(|(a, _)| a)
+ tool_hotkeys()
+ .into_iter()
+ .find(|(_, b)| {
+ b.parse::<Shortcut>()
+ .map(|s| s == *shortcut)
+ .unwrap_or(false)
+ })
+ .map(|(a, _)| a)
}
pub fn on_hotkey(app: &tauri::AppHandle, action: &str) {
@@ -54,15 +69,25 @@ pub fn on_hotkey(app: &tauri::AppHandle, action: &str) {
let _ = app.emit("tool-autoclick", serde_json::json!({ "running": running }));
}
Err(e) => {
- let _ = app.emit("tool-autoclick", serde_json::json!({ "running": false, "error": e.to_string() }));
+ let _ = app.emit(
+ "tool-autoclick",
+ serde_json::json!({ "running": false, "error": e.to_string() }),
+ );
}
},
"dictation" => {
let app = app.clone();
tauri::async_runtime::spawn(async move {
- let r = if dictation::is_recording() { dictation_finish(&app).await.map(|_| ()) } else { dictation::start(progress(&app)).await.map_err(err) };
+ let r = if dictation::is_recording() {
+ dictation_finish(&app).await.map(|_| ())
+ } else {
+ dictation::start(progress(&app)).await.map_err(err)
+ };
if let Err(e) = r {
- let _ = app.emit("tool-dictation", serde_json::json!({ "phase": "idle", "error": e }));
+ let _ = app.emit(
+ "tool-dictation",
+ serde_json::json!({ "phase": "idle", "error": e }),
+ );
}
});
}
@@ -71,13 +96,21 @@ pub fn on_hotkey(app: &tauri::AppHandle, action: &str) {
tauri::async_runtime::spawn(async move {
let st = screen_record::state();
let r = if st.running && st.replay {
- screen_record::save_replay().await.map(|p| serde_json::json!({ "saved": p }))
+ screen_record::save_replay()
+ .await
+ .map(|p| serde_json::json!({ "saved": p }))
} else if st.running {
- screen_record::stop().await.map(|s| serde_json::to_value(s).unwrap_or_default())
+ screen_record::stop()
+ .await
+ .map(|s| serde_json::to_value(s).unwrap_or_default())
} else {
Err(anyhow::anyhow!("nenhuma gravacao ativa"))
};
- let _ = app.emit("tool-record", r.map_err(|e| e.to_string()).unwrap_or_else(|e| serde_json::json!({ "error": e })));
+ let _ = app.emit(
+ "tool-record",
+ r.map_err(|e| e.to_string())
+ .unwrap_or_else(|e| serde_json::json!({ "error": e })),
+ );
});
}
_ => {}
@@ -91,7 +124,11 @@ pub fn tool_hotkeys_get() -> HashMap<String, String> {
/// Define (ou apaga, com `binding` vazio) o atalho de uma ação.
#[tauri::command]
-pub fn tool_hotkey_set(app: tauri::AppHandle, action: String, binding: String) -> Result<HashMap<String, String>, String> {
+pub fn tool_hotkey_set(
+ app: tauri::AppHandle,
+ action: String,
+ binding: String,
+) -> Result<HashMap<String, String>, String> {
let mut map = tool_hotkeys();
if let Some(old) = map.get(&action) {
if let Ok(s) = old.parse::<Shortcut>() {
@@ -102,11 +139,15 @@ pub fn tool_hotkey_set(app: tauri::AppHandle, action: String, binding: String) -
if binding.is_empty() {
map.remove(&action);
} else {
- let s: Shortcut = binding.parse().map_err(|e| format!("atalho invalido: {}", e))?;
+ let s: Shortcut = binding
+ .parse()
+ .map_err(|e| format!("atalho invalido: {}", e))?;
if map.values().any(|b| b == &binding) {
return Err("este atalho ja esta em uso por outra tool".into());
}
- app.global_shortcut().register(s).map_err(|e| format!("nao registrou o atalho: {}", e))?;
+ app.global_shortcut()
+ .register(s)
+ .map_err(|e| format!("nao registrou o atalho: {}", e))?;
map.insert(action, binding);
}
save_hotkeys(&map)?;
@@ -116,7 +157,9 @@ pub fn tool_hotkey_set(app: tauri::AppHandle, action: String, binding: String) -
// ── Autoclicker ────────────────────────────────────────────────────────
#[tauri::command]
-pub fn tool_autoclick_start(opts: autoclick::ClickOptions) -> Result<autoclick::ClickState, String> {
+pub fn tool_autoclick_start(
+ opts: autoclick::ClickOptions,
+) -> Result<autoclick::ClickState, String> {
autoclick::start(opts).map_err(err)?;
Ok(autoclick::state())
}
@@ -150,7 +193,9 @@ pub fn tool_dictation_options() -> dictation::DictationOptions {
}
#[tauri::command]
-pub fn tool_dictation_set_options(opts: dictation::DictationOptions) -> dictation::DictationOptions {
+pub fn tool_dictation_set_options(
+ opts: dictation::DictationOptions,
+) -> dictation::DictationOptions {
dictation::set_options(opts);
dictation::options()
}
@@ -161,9 +206,14 @@ pub fn tool_dictation_state() -> dictation::DictationState {
}
#[tauri::command]
-pub async fn tool_dictation_start(app: tauri::AppHandle) -> Result<dictation::DictationState, String> {
+pub async fn tool_dictation_start(
+ app: tauri::AppHandle,
+) -> Result<dictation::DictationState, String> {
dictation::start(progress(&app)).await.map_err(err)?;
- let _ = app.emit("tool-dictation", serde_json::json!({ "phase": "recording" }));
+ let _ = app.emit(
+ "tool-dictation",
+ serde_json::json!({ "phase": "recording" }),
+ );
Ok(dictation::state())
}
@@ -174,13 +224,18 @@ pub struct DictationOut {
}
async fn dictation_finish(app: &tauri::AppHandle) -> Result<DictationOut, String> {
- let _ = app.emit("tool-dictation", serde_json::json!({ "phase": "transcribing" }));
+ let _ = app.emit(
+ "tool-dictation",
+ serde_json::json!({ "phase": "transcribing" }),
+ );
let text = dictation::stop(progress(app)).await.map_err(err)?;
let opts = dictation::options();
let delivered = match opts.output.as_str() {
"paste" => {
app.clipboard().write_text(text.clone()).map_err(err)?;
- let r = tokio::task::spawn_blocking(dictation::press_paste).await.map_err(err)?;
+ let r = tokio::task::spawn_blocking(dictation::press_paste)
+ .await
+ .map_err(err)?;
match r {
Ok(_) => "paste",
Err(_) => "clipboard",
@@ -192,20 +247,31 @@ async fn dictation_finish(app: &tauri::AppHandle) -> Result<DictationOut, String
}
_ => {
let t = text.clone();
- let r = tokio::task::spawn_blocking(move || dictation::type_text(&t)).await.map_err(err)?;
+ let r = tokio::task::spawn_blocking(move || dictation::type_text(&t))
+ .await
+ .map_err(err)?;
match r {
Ok(_) => "type",
Err(e) => {
// Sem permissão para digitar: pelo menos deixa no clipboard.
app.clipboard().write_text(text.clone()).map_err(err)?;
- let _ = app.emit("tool-dictation", serde_json::json!({ "phase": "idle", "warning": e.to_string() }));
+ let _ = app.emit(
+ "tool-dictation",
+ serde_json::json!({ "phase": "idle", "warning": e.to_string() }),
+ );
"clipboard"
}
}
}
};
- let _ = app.emit("tool-dictation", serde_json::json!({ "phase": "idle", "text": text, "delivered": delivered }));
- Ok(DictationOut { text, delivered: delivered.into() })
+ let _ = app.emit(
+ "tool-dictation",
+ serde_json::json!({ "phase": "idle", "text": text, "delivered": delivered }),
+ );
+ Ok(DictationOut {
+ text,
+ delivered: delivered.into(),
+ })
}
#[tauri::command]
@@ -226,7 +292,9 @@ pub fn tool_record_state() -> screen_record::RecordState {
}
#[tauri::command]
-pub async fn tool_record_start(opts: screen_record::RecordOptions) -> Result<screen_record::RecordState, String> {
+pub async fn tool_record_start(
+ opts: screen_record::RecordOptions,
+) -> Result<screen_record::RecordState, String> {
screen_record::start(opts).await.map_err(err)
}
@@ -253,16 +321,40 @@ pub async fn tool_vs_launch() -> Result<(), String> {
}
#[tauri::command]
-pub async fn tool_vs_clone(app: tauri::AppHandle, opts: voicestudio::CloneOptions) -> Result<voicestudio::SpeechResult, String> {
- voicestudio::clone_speak(opts, progress(&app)).await.map_err(err)
+pub async fn tool_vs_clone(
+ app: tauri::AppHandle,
+ opts: voicestudio::CloneOptions,
+) -> Result<voicestudio::SpeechResult, String> {
+ voicestudio::clone_speak(opts, progress(&app))
+ .await
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_vs_design(app: tauri::AppHandle, opts: voicestudio::DesignOptions) -> Result<voicestudio::DesignResult, String> {
- voicestudio::design_speak(opts, progress(&app)).await.map_err(err)
+pub async fn tool_vs_design(
+ app: tauri::AppHandle,
+ opts: voicestudio::DesignOptions,
+) -> Result<voicestudio::DesignResult, String> {
+ voicestudio::design_speak(opts, progress(&app))
+ .await
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_vs_isolate(app: tauri::AppHandle, base_url: Option<String>, input: String, output_dir: Option<String>, instrumental: Option<bool>) -> Result<Vec<String>, String> {
- voicestudio::isolate(base_url.as_deref().unwrap_or(""), &input, output_dir.as_deref().unwrap_or(""), instrumental.unwrap_or(true), progress(&app)).await.map_err(err)
+pub async fn tool_vs_isolate(
+ app: tauri::AppHandle,
+ base_url: Option<String>,
+ input: String,
+ output_dir: Option<String>,
+ instrumental: Option<bool>,
+) -> Result<Vec<String>, String> {
+ voicestudio::isolate(
+ base_url.as_deref().unwrap_or(""),
+ &input,
+ output_dir.as_deref().unwrap_or(""),
+ instrumental.unwrap_or(true),
+ progress(&app),
+ )
+ .await
+ .map_err(err)
}
diff --git a/src-tauri/src/commands/tools/documents.rs b/src-tauri/src/commands/tools/documents.rs
index 4c3a87df..5ab31020 100644
--- a/src-tauri/src/commands/tools/documents.rs
+++ b/src-tauri/src/commands/tools/documents.rs
@@ -3,8 +3,14 @@ use omniget_core::core::tools::{calameo, gallery, gdocs, slides};
use super::{err, progress};
#[tauri::command]
-pub async fn tool_slideshare(app: tauri::AppHandle, url: String, dest: String) -> Result<slides::SlidesResult, String> {
- slides::download(&url, &dest, progress(&app)).await.map_err(err)
+pub async fn tool_slideshare(
+ app: tauri::AppHandle,
+ url: String,
+ dest: String,
+) -> Result<slides::SlidesResult, String> {
+ slides::download(&url, &dest, progress(&app))
+ .await
+ .map_err(err)
}
#[tauri::command]
@@ -13,13 +19,26 @@ pub fn tool_gdocs_parse(url: String) -> Option<gdocs::GdocInfo> {
}
#[tauri::command]
-pub async fn tool_gdocs_download(app: tauri::AppHandle, url: String, format: String, dest: String) -> Result<String, String> {
- gdocs::download(&url, &format, &dest, progress(&app)).await.map_err(err)
+pub async fn tool_gdocs_download(
+ app: tauri::AppHandle,
+ url: String,
+ format: String,
+ dest: String,
+) -> Result<String, String> {
+ gdocs::download(&url, &format, &dest, progress(&app))
+ .await
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_calameo(app: tauri::AppHandle, url: String, dest: String) -> Result<calameo::CalameoResult, String> {
- calameo::download(&url, &dest, progress(&app)).await.map_err(err)
+pub async fn tool_calameo(
+ app: tauri::AppHandle,
+ url: String,
+ dest: String,
+) -> Result<calameo::CalameoResult, String> {
+ calameo::download(&url, &dest, progress(&app))
+ .await
+ .map_err(err)
}
#[tauri::command]
@@ -33,6 +52,13 @@ pub async fn tool_gallery_install() -> Result<String, String> {
}
#[tauri::command]
-pub async fn tool_gallery_download(app: tauri::AppHandle, url: String, dest: String, cookies_file: Option<String>) -> Result<gallery::GalleryResult, String> {
- gallery::download(&url, &dest, cookies_file.as_deref(), progress(&app)).await.map_err(err)
+pub async fn tool_gallery_download(
+ app: tauri::AppHandle,
+ url: String,
+ dest: String,
+ cookies_file: Option<String>,
+) -> Result<gallery::GalleryResult, String> {
+ gallery::download(&url, &dest, cookies_file.as_deref(), progress(&app))
+ .await
+ .map_err(err)
}
diff --git a/src-tauri/src/commands/tools/downloads.rs b/src-tauri/src/commands/tools/downloads.rs
index b42f3b6f..e03c16c0 100644
--- a/src-tauri/src/commands/tools/downloads.rs
+++ b/src-tauri/src/commands/tools/downloads.rs
@@ -8,11 +8,19 @@ pub async fn tool_aria2_status() -> aria2::Aria2Status {
}
#[tauri::command]
-pub async fn tool_aria2_download(app: tauri::AppHandle, opts: aria2::Aria2Options) -> Result<aria2::Aria2Result, String> {
+pub async fn tool_aria2_download(
+ app: tauri::AppHandle,
+ opts: aria2::Aria2Options,
+) -> Result<aria2::Aria2Result, String> {
aria2::download(opts, progress(&app)).await.map_err(err)
}
#[tauri::command]
-pub async fn tool_manifest_download(app: tauri::AppHandle, opts: manifest_dl::ManifestOptions) -> Result<manifest_dl::ManifestResult, String> {
- manifest_dl::download(opts, progress(&app)).await.map_err(err)
+pub async fn tool_manifest_download(
+ app: tauri::AppHandle,
+ opts: manifest_dl::ManifestOptions,
+) -> Result<manifest_dl::ManifestResult, String> {
+ manifest_dl::download(opts, progress(&app))
+ .await
+ .map_err(err)
}
diff --git a/src-tauri/src/commands/tools/files.rs b/src-tauri/src/commands/tools/files.rs
index eb39b328..013f3aa2 100644
--- a/src-tauri/src/commands/tools/files.rs
+++ b/src-tauri/src/commands/tools/files.rs
@@ -6,9 +6,14 @@ use serde::Serialize;
use super::{err, progress};
#[tauri::command]
-pub async fn tool_dupes_scan(app: tauri::AppHandle, opts: dupes::DupesOptions) -> Result<dupes::DupesResult, String> {
+pub async fn tool_dupes_scan(
+ app: tauri::AppHandle,
+ opts: dupes::DupesOptions,
+) -> Result<dupes::DupesResult, String> {
let p = progress(&app);
- tokio::task::spawn_blocking(move || dupes::scan(&opts, &p)).await.map_err(err)
+ tokio::task::spawn_blocking(move || dupes::scan(&opts, &p))
+ .await
+ .map_err(err)
}
#[derive(Serialize)]
@@ -46,8 +51,18 @@ pub async fn tool_file_search_backend() -> file_search::SearchBackend {
}
#[tauri::command]
-pub async fn tool_file_search(query: String, folder: Option<String>, limit: Option<usize>) -> Result<Vec<file_search::Hit>, String> {
- file_search::search(&query, folder.as_deref().unwrap_or(""), limit.unwrap_or(300)).await.map_err(err)
+pub async fn tool_file_search(
+ query: String,
+ folder: Option<String>,
+ limit: Option<usize>,
+) -> Result<Vec<file_search::Hit>, String> {
+ file_search::search(
+ &query,
+ folder.as_deref().unwrap_or(""),
+ limit.unwrap_or(300),
+ )
+ .await
+ .map_err(err)
}
// ── Manter acordado (estudo 29, PowerToys Awake) ──
@@ -76,5 +91,9 @@ pub fn tool_awake_set(active: bool) -> Result<bool, String> {
#[tauri::command]
pub fn tool_awake_get() -> bool {
- AWAKE.get().and_then(|c| c.lock().ok()).map(|h| h.is_some()).unwrap_or(false)
+ AWAKE
+ .get()
+ .and_then(|c| c.lock().ok())
+ .map(|h| h.is_some())
+ .unwrap_or(false)
}
diff --git a/src-tauri/src/commands/tools/images.rs b/src-tauri/src/commands/tools/images.rs
index 255cbc2f..a4058f74 100644
--- a/src-tauri/src/commands/tools/images.rs
+++ b/src-tauri/src/commands/tools/images.rs
@@ -13,12 +13,18 @@ pub async fn tool_upscale_install(app: tauri::AppHandle) -> Result<String, Strin
}
#[tauri::command]
-pub async fn tool_upscale_run(app: tauri::AppHandle, opts: upscale::UpscaleOptions) -> Result<upscale::UpscaleResult, String> {
+pub async fn tool_upscale_run(
+ app: tauri::AppHandle,
+ opts: upscale::UpscaleOptions,
+) -> Result<upscale::UpscaleResult, String> {
upscale::run(opts, progress(&app)).await.map_err(err)
}
#[tauri::command]
-pub async fn tool_resize(app: tauri::AppHandle, opts: image_resize::ResizeOptions) -> Result<image_resize::ResizeResult, String> {
+pub async fn tool_resize(
+ app: tauri::AppHandle,
+ opts: image_resize::ResizeOptions,
+) -> Result<image_resize::ResizeResult, String> {
image_resize::run(opts, progress(&app)).await.map_err(err)
}
@@ -28,6 +34,12 @@ pub async fn tool_ocr_status() -> omniget_core::core::tools::ocr::OcrStatus {
}
#[tauri::command]
-pub async fn tool_ocr_run(app: tauri::AppHandle, inputs: Vec<String>, langs: String) -> Result<Vec<omniget_core::core::tools::ocr::OcrResult>, String> {
- omniget_core::core::tools::ocr::run(&inputs, &langs, progress(&app)).await.map_err(err)
+pub async fn tool_ocr_run(
+ app: tauri::AppHandle,
+ inputs: Vec<String>,
+ langs: String,
+) -> Result<Vec<omniget_core::core::tools::ocr::OcrResult>, String> {
+ omniget_core::core::tools::ocr::run(&inputs, &langs, progress(&app))
+ .await
+ .map_err(err)
}
diff --git a/src-tauri/src/commands/tools/instagram.rs b/src-tauri/src/commands/tools/instagram.rs
index 5ea18501..fc6ef787 100644
--- a/src-tauri/src/commands/tools/instagram.rs
+++ b/src-tauri/src/commands/tools/instagram.rs
@@ -6,7 +6,9 @@
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, OnceLock};
-use omniget_core::core::tools::instagram::{self as ig, analytics, follow, media, profile, publish, social, IgClient, Session};
+use omniget_core::core::tools::instagram::{
+ self as ig, analytics, follow, media, profile, publish, social, IgClient, Session,
+};
use serde::Serialize;
use super::{err, progress};
@@ -15,7 +17,8 @@ const DOMAIN: &str = "instagram.com";
pub(crate) fn load_client(slug: Option<&str>) -> Result<Arc<IgClient>, String> {
let slug_name = slug.unwrap_or("_default");
- let content = crate::cookies::storage::read_account_file(DOMAIN, slug_name).map_err(|_| ig::IgError::NoSession.to_string())?;
+ let content = crate::cookies::storage::read_account_file(DOMAIN, slug_name)
+ .map_err(|_| ig::IgError::NoSession.to_string())?;
let session = Session::from_netscape(&content).map_err(|e| e.to_string())?;
crate::cookies::touch_last_used(DOMAIN, slug_name);
IgClient::new(session).map_err(err)
@@ -28,7 +31,10 @@ struct Job {
impl Job {
fn new(id: &str) -> Self {
- Job { id: id.to_string(), flag: ig::job_start(id) }
+ Job {
+ id: id.to_string(),
+ flag: ig::job_start(id),
+ }
}
}
@@ -53,12 +59,15 @@ pub struct IgAccount {
#[tauri::command]
pub fn tool_ig_accounts() -> Vec<IgAccount> {
let registry = crate::cookies::load_registry();
- let Some(bucket) = registry.buckets.get(DOMAIN) else { return Vec::new() };
+ let Some(bucket) = registry.buckets.get(DOMAIN) else {
+ return Vec::new();
+ };
bucket
.accounts
.iter()
.map(|a| {
- let content = crate::cookies::storage::read_account_file(DOMAIN, &a.slug).unwrap_or_default();
+ let content =
+ crate::cookies::storage::read_account_file(DOMAIN, &a.slug).unwrap_or_default();
let session = Session::from_netscape(&content).ok();
IgAccount {
slug: a.slug.clone(),
@@ -94,17 +103,29 @@ pub fn tool_ig_cancel(job: String) -> bool {
pub async fn tool_ig_post(slug: Option<String>, url: String) -> Result<media::MediaItem, String> {
let client = load_client(slug.as_deref())?;
match ig::parse_target(&url) {
- ig::IgTarget::Post { shortcode } => media::post_info(&client, &shortcode).await.map_err(err),
+ ig::IgTarget::Post { shortcode } => {
+ media::post_info(&client, &shortcode).await.map_err(err)
+ }
_ => Err("cole o link de um post, reel ou IGTV".into()),
}
}
/// Resolve qualquer link (post, story, highlight, perfil) em itens de mídia.
-async fn resolve_items(client: &IgClient, url: &str, flag: &AtomicBool, p: &omniget_core::core::tools::ProgressFn, job: &str) -> Result<Vec<media::MediaItem>, String> {
+async fn resolve_items(
+ client: &IgClient,
+ url: &str,
+ flag: &AtomicBool,
+ p: &omniget_core::core::tools::ProgressFn,
+ job: &str,
+) -> Result<Vec<media::MediaItem>, String> {
match ig::parse_target(url) {
- ig::IgTarget::Post { shortcode } => Ok(vec![media::post_info(client, &shortcode).await.map_err(err)?]),
+ ig::IgTarget::Post { shortcode } => Ok(vec![media::post_info(client, &shortcode)
+ .await
+ .map_err(err)?]),
ig::IgTarget::Story { username, media_id } => {
- let user = profile::resolve_user(client, &username).await.map_err(err)?;
+ let user = profile::resolve_user(client, &username)
+ .await
+ .map_err(err)?;
let mut items = profile::stories_of(client, &user.pk).await.map_err(err)?;
if let Some(id) = media_id {
items.retain(|i| i.pk == id);
@@ -113,30 +134,62 @@ async fn resolve_items(client: &IgClient, url: &str, flag: &AtomicBool, p: &omni
}
ig::IgTarget::Highlight { id } => profile::highlight_items(client, &id).await.map_err(err),
ig::IgTarget::Profile { username, tab } => {
- let user = profile::resolve_user(client, &username).await.map_err(err)?;
+ let user = profile::resolve_user(client, &username)
+ .await
+ .map_err(err)?;
match tab.as_str() {
- "reels" => profile::user_reels(client, &user.pk, 24, flag, p, job).await.map_err(err),
- "tagged" => profile::user_tagged(client, &user.pk, 24, flag, p, job).await.map_err(err),
- _ => profile::user_posts(client, &user.username, 24, flag, p, job).await.map_err(err),
+ "reels" => profile::user_reels(client, &user.pk, 24, flag, p, job)
+ .await
+ .map_err(err),
+ "tagged" => profile::user_tagged(client, &user.pk, 24, flag, p, job)
+ .await
+ .map_err(err),
+ _ => profile::user_posts(client, &user.username, 24, flag, p, job)
+ .await
+ .map_err(err),
}
}
- ig::IgTarget::Tag { name } => social::tag_media(client, &name, "recent", 24, flag, p, job).await.map_err(err),
+ ig::IgTarget::Tag { name } => social::tag_media(client, &name, "recent", 24, flag, p, job)
+ .await
+ .map_err(err),
ig::IgTarget::Unknown => Err(format!("nao reconheci este link do Instagram: {}", url)),
}
}
#[tauri::command]
-pub async fn tool_ig_resolve(app: tauri::AppHandle, slug: Option<String>, url: String, job: String) -> Result<Vec<media::MediaItem>, String> {
+pub async fn tool_ig_resolve(
+ app: tauri::AppHandle,
+ slug: Option<String>,
+ url: String,
+ job: String,
+) -> Result<Vec<media::MediaItem>, String> {
let client = load_client(slug.as_deref())?;
let j = Job::new(&job);
resolve_items(&client, &url, &j.flag, &progress(&app), &job).await
}
#[tauri::command]
-pub async fn tool_ig_download(app: tauri::AppHandle, slug: Option<String>, items: Vec<media::MediaItem>, dest: String, opts: media::DownloadOptions, job: String) -> Result<media::DownloadResult, String> {
+pub async fn tool_ig_download(
+ app: tauri::AppHandle,
+ slug: Option<String>,
+ items: Vec<media::MediaItem>,
+ dest: String,
+ opts: media::DownloadOptions,
+ job: String,
+) -> Result<media::DownloadResult, String> {
let client = load_client(slug.as_deref())?;
let j = Job::new(&job);
- media::download_items(&client, &items, &dest, &opts, &progress(&app), &job, &j.flag).await.map_err(err)
+ media::download_items(
+ &client,
+ &items,
+ &dest,
+ &opts,
+ &progress(&app),
+ &job,
+ &j.flag,
+ )
+ .await
+ .map_err(err)
}
#[derive(Debug, Serialize)]
@@ -148,7 +201,14 @@ pub struct BulkResult {
/// Vários links de uma vez (um por linha), com pausa entre eles.
#[tauri::command]
-pub async fn tool_ig_download_bulk(app: tauri::AppHandle, slug: Option<String>, urls: Vec<String>, dest: String, opts: media::DownloadOptions, job: String) -> Result<BulkResult, String> {
+pub async fn tool_ig_download_bulk(
+ app: tauri::AppHandle,
+ slug: Option<String>,
+ urls: Vec<String>,
+ dest: String,
+ opts: media::DownloadOptions,
+ job: String,
+) -> Result<BulkResult, String> {
let client = load_client(slug.as_deref())?;
let j = Job::new(&job);
let p = progress(&app);
@@ -163,44 +223,76 @@ pub async fn tool_ig_download_bulk(app: tauri::AppHandle, slug: Option<String>,
if url.is_empty() {
continue;
}
- omniget_core::core::tools::report(&p, &format!("ig:{}", job), "resolve", i as u64, Some(total), Some(url.to_string()));
+ omniget_core::core::tools::report(
+ &p,
+ &format!("ig:{}", job),
+ "resolve",
+ i as u64,
+ Some(total),
+ Some(url.to_string()),
+ );
match resolve_items(&client, url, &j.flag, &p, &job).await {
Ok(mut v) => items.append(&mut v),
Err(e) => errors.push(format!("{}: {}", url, e)),
}
client.pause().await;
}
- let result = media::download_items(&client, &items, &dest, &opts, &p, &job, &j.flag).await.map_err(err)?;
- Ok(BulkResult { items: items.len(), result, errors })
+ let result = media::download_items(&client, &items, &dest, &opts, &p, &job, &j.flag)
+ .await
+ .map_err(err)?;
+ Ok(BulkResult {
+ items: items.len(),
+ result,
+ errors,
+ })
}
// ── Perfil, stories e highlights ─────────────────────────────────────────
#[tauri::command]
-pub async fn tool_ig_profile(slug: Option<String>, user: String) -> Result<profile::UserInfo, String> {
+pub async fn tool_ig_profile(
+ slug: Option<String>,
+ user: String,
+) -> Result<profile::UserInfo, String> {
let client = load_client(slug.as_deref())?;
profile::resolve_user(&client, &user).await.map_err(err)
}
#[tauri::command]
-pub async fn tool_ig_friendship(slug: Option<String>, user_id: String) -> Result<profile::Friendship, String> {
+pub async fn tool_ig_friendship(
+ slug: Option<String>,
+ user_id: String,
+) -> Result<profile::Friendship, String> {
let client = load_client(slug.as_deref())?;
profile::friendship(&client, &user_id).await.map_err(err)
}
/// `tab` = posts | reels | tagged | saved | stories | highlights (todos os itens).
#[tauri::command]
-pub async fn tool_ig_profile_media(app: tauri::AppHandle, slug: Option<String>, user: String, tab: String, limit: usize, job: String) -> Result<Vec<media::MediaItem>, String> {
+pub async fn tool_ig_profile_media(
+ app: tauri::AppHandle,
+ slug: Option<String>,
+ user: String,
+ tab: String,
+ limit: usize,
+ job: String,
+) -> Result<Vec<media::MediaItem>, String> {
let client = load_client(slug.as_deref())?;
let j = Job::new(&job);
let p = progress(&app);
if tab == "saved" {
- return profile::saved(&client, limit, &j.flag, &p, &job).await.map_err(err);
+ return profile::saved(&client, limit, &j.flag, &p, &job)
+ .await
+ .map_err(err);
}
let info = profile::resolve_user(&client, &user).await.map_err(err)?;
match tab.as_str() {
- "reels" => profile::user_reels(&client, &info.pk, limit, &j.flag, &p, &job).await.map_err(err),
- "tagged" => profile::user_tagged(&client, &info.pk, limit, &j.flag, &p, &job).await.map_err(err),
+ "reels" => profile::user_reels(&client, &info.pk, limit, &j.flag, &p, &job)
+ .await
+ .map_err(err),
+ "tagged" => profile::user_tagged(&client, &info.pk, limit, &j.flag, &p, &job)
+ .await
+ .map_err(err),
"stories" => profile::stories_of(&client, &info.pk).await.map_err(err),
"highlights" => {
let hls = profile::highlights(&client, &info.pk).await.map_err(err)?;
@@ -209,18 +301,34 @@ pub async fn tool_ig_profile_media(app: tauri::AppHandle, slug: Option<String>,
if ig::cancelled(&j.flag) {
break;
}
- omniget_core::core::tools::report(&p, &format!("ig:{}", job), "highlights", i as u64, Some(hls.len() as u64), Some(h.title.clone()));
- out.extend(profile::highlight_items(&client, &h.id).await.map_err(err)?);
+ omniget_core::core::tools::report(
+ &p,
+ &format!("ig:{}", job),
+ "highlights",
+ i as u64,
+ Some(hls.len() as u64),
+ Some(h.title.clone()),
+ );
+ out.extend(
+ profile::highlight_items(&client, &h.id)
+ .await
+ .map_err(err)?,
+ );
client.pause().await;
}
Ok(out)
}
- _ => profile::user_posts(&client, &info.username, limit, &j.flag, &p, &job).await.map_err(err),
+ _ => profile::user_posts(&client, &info.username, limit, &j.flag, &p, &job)
+ .await
+ .map_err(err),
}
}
#[tauri::command]
-pub async fn tool_ig_stories(slug: Option<String>, user: String) -> Result<Vec<profile::Reel>, String> {
+pub async fn tool_ig_stories(
+ slug: Option<String>,
+ user: String,
+) -> Result<Vec<profile::Reel>, String> {
let client = load_client(slug.as_deref())?;
let info = profile::resolve_user(&client, &user).await.map_err(err)?;
profile::reels_media(&client, &[info.pk]).await.map_err(err)
@@ -233,14 +341,20 @@ pub async fn tool_ig_stories_tray(slug: Option<String>) -> Result<Vec<profile::T
}
#[tauri::command]
-pub async fn tool_ig_highlights(slug: Option<String>, user: String) -> Result<Vec<profile::Highlight>, String> {
+pub async fn tool_ig_highlights(
+ slug: Option<String>,
+ user: String,
+) -> Result<Vec<profile::Highlight>, String> {
let client = load_client(slug.as_deref())?;
let info = profile::resolve_user(&client, &user).await.map_err(err)?;
profile::highlights(&client, &info.pk).await.map_err(err)
}
#[tauri::command]
-pub async fn tool_ig_highlight_items(slug: Option<String>, id: String) -> Result<Vec<media::MediaItem>, String> {
+pub async fn tool_ig_highlight_items(
+ slug: Option<String>,
+ id: String,
+) -> Result<Vec<media::MediaItem>, String> {
let client = load_client(slug.as_deref())?;
profile::highlight_items(&client, &id).await.map_err(err)
}
@@ -252,10 +366,16 @@ pub struct StoryViewers {
}
#[tauri::command]
-pub async fn tool_ig_story_viewers(slug: Option<String>, story_pk: String, job: String) -> Result<StoryViewers, String> {
+pub async fn tool_ig_story_viewers(
+ slug: Option<String>,
+ story_pk: String,
+ job: String,
+) -> Result<StoryViewers, String> {
let client = load_client(slug.as_deref())?;
let j = Job::new(&job);
- let (total, viewers) = profile::story_viewers(&client, &story_pk, &j.flag).await.map_err(err)?;
+ let (total, viewers) = profile::story_viewers(&client, &story_pk, &j.flag)
+ .await
+ .map_err(err)?;
Ok(StoryViewers { total, viewers })
}
@@ -266,7 +386,13 @@ fn owner_of(client: &IgClient) -> String {
}
#[tauri::command]
-pub async fn tool_ig_follow_lists(app: tauri::AppHandle, slug: Option<String>, user: Option<String>, limit: usize, job: String) -> Result<follow::FollowAnalysis, String> {
+pub async fn tool_ig_follow_lists(
+ app: tauri::AppHandle,
+ slug: Option<String>,
+ user: Option<String>,
+ limit: usize,
+ job: String,
+) -> Result<follow::FollowAnalysis, String> {
let client = load_client(slug.as_deref())?;
let j = Job::new(&job);
let p = progress(&app);
@@ -274,8 +400,12 @@ pub async fn tool_ig_follow_lists(app: tauri::AppHandle, slug: Option<String>, u
Some(u) => profile::resolve_user(&client, &u).await.map_err(err)?.pk,
None => owner_of(&client),
};
- let followers = follow::followers(&client, &target, limit, &j.flag, &p, &job).await.map_err(err)?;
- let following = follow::following(&client, &target, limit, &j.flag, &p, &job).await.map_err(err)?;
+ let followers = follow::followers(&client, &target, limit, &j.flag, &p, &job)
+ .await
+ .map_err(err)?;
+ let following = follow::following(&client, &target, limit, &j.flag, &p, &job)
+ .await
+ .map_err(err)?;
let wl = follow::whitelist_keys(&follow::whitelist_get(&owner_of(&client)));
Ok(follow::analyze(followers, following, &wl))
}
@@ -287,7 +417,10 @@ pub fn tool_ig_whitelist_get(slug: Option<String>) -> Result<follow::Whitelist,
}
#[tauri::command]
-pub fn tool_ig_whitelist_set(slug: Option<String>, users: Vec<follow::MiniUser>) -> Result<follow::Whitelist, String> {
+pub fn tool_ig_whitelist_set(
+ slug: Option<String>,
+ users: Vec<follow::MiniUser>,
+) -> Result<follow::Whitelist, String> {
let client = load_client(slug.as_deref())?;
let wl = follow::Whitelist { users };
follow::whitelist_set(&owner_of(&client), &wl).map_err(err)?;
@@ -302,14 +435,34 @@ pub fn tool_ig_actions_today(slug: Option<String>) -> Result<u32, String> {
/// `action` = unfollow | remove_follower.
#[tauri::command]
-pub async fn tool_ig_actions(app: tauri::AppHandle, slug: Option<String>, action: String, users: Vec<follow::MiniUser>, pacing: Option<follow::Pacing>, job: String) -> Result<follow::ActionReport, String> {
+pub async fn tool_ig_actions(
+ app: tauri::AppHandle,
+ slug: Option<String>,
+ action: String,
+ users: Vec<follow::MiniUser>,
+ pacing: Option<follow::Pacing>,
+ job: String,
+) -> Result<follow::ActionReport, String> {
let client = load_client(slug.as_deref())?;
let j = Job::new(&job);
- Ok(follow::run_actions(&client, &action, users, &pacing.unwrap_or_default(), &j.flag, &progress(&app), &job).await)
-}
-
-#[tauri::command]
-pub async fn tool_ig_resolve_users(slug: Option<String>, usernames: Vec<String>, job: String) -> Result<Vec<follow::MiniUser>, String> {
+ Ok(follow::run_actions(
+ &client,
+ &action,
+ users,
+ &pacing.unwrap_or_default(),
+ &j.flag,
+ &progress(&app),
+ &job,
+ )
+ .await)
+}
+
+#[tauri::command]
+pub async fn tool_ig_resolve_users(
+ slug: Option<String>,
+ usernames: Vec<String>,
+ job: String,
+) -> Result<Vec<follow::MiniUser>, String> {
let client = load_client(slug.as_deref())?;
let j = Job::new(&job);
let mut out = Vec::new();
@@ -318,7 +471,14 @@ pub async fn tool_ig_resolve_users(slug: Option<String>, usernames: Vec<String>,
break;
}
if let Ok(info) = profile::resolve_user(&client, &u).await {
- out.push(follow::MiniUser { pk: info.pk, username: info.username, full_name: info.full_name, is_private: info.is_private, is_verified: info.is_verified, profile_pic_url: info.profile_pic_url });
+ out.push(follow::MiniUser {
+ pk: info.pk,
+ username: info.username,
+ full_name: info.full_name,
+ is_private: info.is_private,
+ is_verified: info.is_verified,
+ profile_pic_url: info.profile_pic_url,
+ });
}
client.pause().await;
}
@@ -326,19 +486,37 @@ pub async fn tool_ig_resolve_users(slug: Option<String>, usernames: Vec<String>,
}
#[tauri::command]
-pub async fn tool_ig_snapshot_take(app: tauri::AppHandle, slug: Option<String>, job: String) -> Result<follow::SnapshotMeta, String> {
+pub async fn tool_ig_snapshot_take(
+ app: tauri::AppHandle,
+ slug: Option<String>,
+ job: String,
+) -> Result<follow::SnapshotMeta, String> {
let client = load_client(slug.as_deref())?;
let j = Job::new(&job);
let p = progress(&app);
let owner = owner_of(&client);
- let followers = follow::followers(&client, &owner, 0, &j.flag, &p, &job).await.map_err(err)?;
- let following = follow::following(&client, &owner, 0, &j.flag, &p, &job).await.map_err(err)?;
+ let followers = follow::followers(&client, &owner, 0, &j.flag, &p, &job)
+ .await
+ .map_err(err)?;
+ let following = follow::following(&client, &owner, 0, &j.flag, &p, &job)
+ .await
+ .map_err(err)?;
if ig::cancelled(&j.flag) {
return Err("cancelado".into());
}
- let snap = follow::Snapshot { taken_at: chrono::Utc::now().timestamp(), owner: owner.clone(), followers, following };
+ let snap = follow::Snapshot {
+ taken_at: chrono::Utc::now().timestamp(),
+ owner: owner.clone(),
+ followers,
+ following,
+ };
let file = follow::snapshot_save(&snap).map_err(err)?;
- Ok(follow::SnapshotMeta { file, taken_at: snap.taken_at, followers: snap.followers.len(), following: snap.following.len() })
+ Ok(follow::SnapshotMeta {
+ file,
+ taken_at: snap.taken_at,
+ followers: snap.followers.len(),
+ following: snap.following.len(),
+ })
}
#[tauri::command]
@@ -363,21 +541,36 @@ pub fn tool_ig_snapshot_delete(file: String) -> Result<(), String> {
}
#[tauri::command]
-pub async fn tool_ig_ghosts(app: tauri::AppHandle, slug: Option<String>, posts_limit: usize, comment_pages: usize, job: String) -> Result<analytics::GhostReport, String> {
+pub async fn tool_ig_ghosts(
+ app: tauri::AppHandle,
+ slug: Option<String>,
+ posts_limit: usize,
+ comment_pages: usize,
+ job: String,
+) -> Result<analytics::GhostReport, String> {
let client = load_client(slug.as_deref())?;
let j = Job::new(&job);
let p = progress(&app);
let me = profile::whoami(&client).await.map_err(err)?;
- let followers = follow::followers(&client, &me.pk, 0, &j.flag, &p, &job).await.map_err(err)?;
- let posts = profile::user_posts(&client, &me.username, posts_limit.max(1), &j.flag, &p, &job).await.map_err(err)?;
- analytics::ghosts(&client, followers, &posts, comment_pages, &j.flag, &p, &job).await.map_err(err)
+ let followers = follow::followers(&client, &me.pk, 0, &j.flag, &p, &job)
+ .await
+ .map_err(err)?;
+ let posts = profile::user_posts(&client, &me.username, posts_limit.max(1), &j.flag, &p, &job)
+ .await
+ .map_err(err)?;
+ analytics::ghosts(&client, followers, &posts, comment_pages, &j.flag, &p, &job)
+ .await
+ .map_err(err)
}
// ── Export oficial ───────────────────────────────────────────────────────
#[tauri::command]
pub async fn tool_ig_export(path: String) -> Result<analytics::ExportReport, String> {
- tokio::task::spawn_blocking(move || analytics::analyze_export(&path)).await.map_err(err)?.map_err(err)
+ tokio::task::spawn_blocking(move || analytics::analyze_export(&path))
+ .await
+ .map_err(err)?
+ .map_err(err)
}
#[tauri::command]
@@ -390,7 +583,16 @@ pub async fn tool_ig_read_text(path: String) -> Result<String, String> {
pub fn tool_ig_write_csv(path: String, rows: Vec<Vec<String>>) -> Result<String, String> {
let mut out = String::from("\u{feff}");
for row in rows {
- let line: Vec<String> = row.iter().map(|c| if c.contains([',', '"', '\n']) { format!("\"{}\"", c.replace('"', "\"\"")) } else { c.clone() }).collect();
+ let line: Vec<String> = row
+ .iter()
+ .map(|c| {
+ if c.contains([',', '"', '\n']) {
+ format!("\"{}\"", c.replace('"', "\"\""))
+ } else {
+ c.clone()
+ }
+ })
+ .collect();
out.push_str(&line.join(","));
out.push('\n');
}
@@ -401,7 +603,13 @@ pub fn tool_ig_write_csv(path: String, rows: Vec<Vec<String>>) -> Result<String,
// ── Analytics ────────────────────────────────────────────────────────────
#[tauri::command]
-pub async fn tool_ig_analytics(app: tauri::AppHandle, slug: Option<String>, users: Vec<String>, posts_limit: usize, job: String) -> Result<Vec<analytics::ProfileStats>, String> {
+pub async fn tool_ig_analytics(
+ app: tauri::AppHandle,
+ slug: Option<String>,
+ users: Vec<String>,
+ posts_limit: usize,
+ job: String,
+) -> Result<Vec<analytics::ProfileStats>, String> {
let client = load_client(slug.as_deref())?;
let j = Job::new(&job);
let p = progress(&app);
@@ -411,7 +619,16 @@ pub async fn tool_ig_analytics(app: tauri::AppHandle, slug: Option<String>, user
break;
}
let info = profile::resolve_user(&client, u).await.map_err(err)?;
- let posts = match profile::user_posts(&client, &info.username, posts_limit.max(1), &j.flag, &p, &job).await {
+ let posts = match profile::user_posts(
+ &client,
+ &info.username,
+ posts_limit.max(1),
+ &j.flag,
+ &p,
+ &job,
+ )
+ .await
+ {
Ok(v) => v,
Err(ig::IgError::Private) => Vec::new(),
Err(e) => return Err(e.to_string()),
@@ -429,11 +646,20 @@ pub struct HashtagResult {
}
#[tauri::command]
-pub async fn tool_ig_hashtag(app: tauri::AppHandle, slug: Option<String>, tag: String, tab: String, limit: usize, job: String) -> Result<HashtagResult, String> {
+pub async fn tool_ig_hashtag(
+ app: tauri::AppHandle,
+ slug: Option<String>,
+ tag: String,
+ tab: String,
+ limit: usize,
+ job: String,
+) -> Result<HashtagResult, String> {
let client = load_client(slug.as_deref())?;
let j = Job::new(&job);
let info = social::tag_info(&client, &tag).await.map_err(err)?;
- let items = social::tag_media(&client, &tag, &tab, limit, &j.flag, &progress(&app), &job).await.unwrap_or_default();
+ let items = social::tag_media(&client, &tag, &tab, limit, &j.flag, &progress(&app), &job)
+ .await
+ .unwrap_or_default();
Ok(HashtagResult { info, items })
}
@@ -444,12 +670,22 @@ pub struct CommentsResult {
}
#[tauri::command]
-pub async fn tool_ig_comments(app: tauri::AppHandle, slug: Option<String>, url: String, limit: usize, job: String) -> Result<CommentsResult, String> {
+pub async fn tool_ig_comments(
+ app: tauri::AppHandle,
+ slug: Option<String>,
+ url: String,
+ limit: usize,
+ job: String,
+) -> Result<CommentsResult, String> {
let client = load_client(slug.as_deref())?;
let j = Job::new(&job);
- let ig::IgTarget::Post { shortcode } = ig::parse_target(&url) else { return Err("cole o link de um post ou reel".into()) };
+ let ig::IgTarget::Post { shortcode } = ig::parse_target(&url) else {
+ return Err("cole o link de um post ou reel".into());
+ };
let item = media::post_info(&client, &shortcode).await.map_err(err)?;
- let comments = social::comments(&client, &item.pk, limit, &j.flag, &progress(&app), &job).await.map_err(err)?;
+ let comments = social::comments(&client, &item.pk, limit, &j.flag, &progress(&app), &job)
+ .await
+ .map_err(err)?;
Ok(CommentsResult { item, comments })
}
@@ -463,30 +699,49 @@ pub struct LikersResult {
#[tauri::command]
pub async fn tool_ig_likers(slug: Option<String>, url: String) -> Result<LikersResult, String> {
let client = load_client(slug.as_deref())?;
- let ig::IgTarget::Post { shortcode } = ig::parse_target(&url) else { return Err("cole o link de um post ou reel".into()) };
+ let ig::IgTarget::Post { shortcode } = ig::parse_target(&url) else {
+ return Err("cole o link de um post ou reel".into());
+ };
let item = media::post_info(&client, &shortcode).await.map_err(err)?;
let (count, users) = social::likers(&client, &item.pk).await.map_err(err)?;
Ok(LikersResult { item, count, users })
}
#[tauri::command]
-pub fn tool_ig_giveaway(comments: Vec<social::Comment>, rules: social::GiveawayRules) -> social::GiveawayResult {
+pub fn tool_ig_giveaway(
+ comments: Vec<social::Comment>,
+ rules: social::GiveawayRules,
+) -> social::GiveawayResult {
social::giveaway(&comments, &rules)
}
// ── Publicar e agendar ───────────────────────────────────────────────────
#[tauri::command]
-pub async fn tool_ig_publish(app: tauri::AppHandle, slug: Option<String>, request: publish::PublishRequest, job: String) -> Result<publish::PublishResult, String> {
+pub async fn tool_ig_publish(
+ app: tauri::AppHandle,
+ slug: Option<String>,
+ request: publish::PublishRequest,
+ job: String,
+) -> Result<publish::PublishResult, String> {
let client = load_client(slug.as_deref())?;
let _j = Job::new(&job);
- publish::publish_web(&client, &request, &progress(&app), &job).await.map_err(err)
+ publish::publish_web(&client, &request, &progress(&app), &job)
+ .await
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_ig_publish_graph(app: tauri::AppHandle, auth: publish::GraphAuth, request: publish::PublishRequest, job: String) -> Result<publish::PublishResult, String> {
+pub async fn tool_ig_publish_graph(
+ app: tauri::AppHandle,
+ auth: publish::GraphAuth,
+ request: publish::PublishRequest,
+ job: String,
+) -> Result<publish::PublishResult, String> {
let _j = Job::new(&job);
- publish::publish_graph(&auth, &request, &progress(&app), &job).await.map_err(err)
+ publish::publish_graph(&auth, &request, &progress(&app), &job)
+ .await
+ .map_err(err)
}
#[tauri::command]
@@ -496,7 +751,10 @@ pub fn tool_ig_schedule_list(app: tauri::AppHandle) -> publish::ScheduleStore {
}
#[tauri::command]
-pub fn tool_ig_schedule_add(app: tauri::AppHandle, post: publish::ScheduledPost) -> Result<publish::ScheduleStore, String> {
+pub fn tool_ig_schedule_add(
+ app: tauri::AppHandle,
+ post: publish::ScheduledPost,
+) -> Result<publish::ScheduleStore, String> {
start_scheduler(app);
publish::schedule_add(post).map_err(err)
}
@@ -517,7 +775,9 @@ pub fn start_scheduler(app: tauri::AppHandle) {
loop {
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
let now = chrono::Utc::now().timestamp();
- let Some(mut post) = publish::schedule_due(now) else { continue };
+ let Some(mut post) = publish::schedule_due(now) else {
+ continue;
+ };
post.status = "running".into();
let _ = publish::schedule_update(&post);
let job = format!("schedule:{}", post.id);
@@ -549,4 +809,3 @@ pub fn start_scheduler(app: tauri::AppHandle) {
}
});
}
-
diff --git a/src-tauri/src/commands/tools/pdf.rs b/src-tauri/src/commands/tools/pdf.rs
index 8cc54d82..649e6998 100644
--- a/src-tauri/src/commands/tools/pdf.rs
+++ b/src-tauri/src/commands/tools/pdf.rs
@@ -13,31 +13,62 @@ pub async fn tool_pdf_status() -> pdf::PdfStatus {
#[tauri::command]
pub async fn tool_pdf_info(path: String, password: Option<String>) -> Result<pdf::PdfInfo, String> {
- tokio::task::spawn_blocking(move || pdf::info(&path, password.as_deref())).await.map_err(err)?.map_err(err)
+ tokio::task::spawn_blocking(move || pdf::info(&path, password.as_deref()))
+ .await
+ .map_err(err)?
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_pdf_merge(app: tauri::AppHandle, opts: pdf::MergeOptions) -> Result<pdf::PdfOut, String> {
+pub async fn tool_pdf_merge(
+ app: tauri::AppHandle,
+ opts: pdf::MergeOptions,
+) -> Result<pdf::PdfOut, String> {
let p = progress(&app);
- tokio::task::spawn_blocking(move || pdf::merge(&opts, &p)).await.map_err(err)?.map_err(err)
+ tokio::task::spawn_blocking(move || pdf::merge(&opts, &p))
+ .await
+ .map_err(err)?
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_pdf_split(app: tauri::AppHandle, opts: pdf::SplitOptions) -> Result<pdf::PdfOuts, String> {
+pub async fn tool_pdf_split(
+ app: tauri::AppHandle,
+ opts: pdf::SplitOptions,
+) -> Result<pdf::PdfOuts, String> {
let p = progress(&app);
- tokio::task::spawn_blocking(move || pdf::split(&opts, &p)).await.map_err(err)?.map_err(err)
+ tokio::task::spawn_blocking(move || pdf::split(&opts, &p))
+ .await
+ .map_err(err)?
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_pdf_render(app: tauri::AppHandle, opts: pdf::RenderOptions) -> Result<Vec<String>, String> {
+pub async fn tool_pdf_render(
+ app: tauri::AppHandle,
+ opts: pdf::RenderOptions,
+) -> Result<Vec<String>, String> {
let p = progress(&app);
- tokio::task::spawn_blocking(move || pdf::render(&opts, &p)).await.map_err(err)?.map_err(err)
+ tokio::task::spawn_blocking(move || pdf::render(&opts, &p))
+ .await
+ .map_err(err)?
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_pdf_text(input: String, pages: Option<String>, save: Option<bool>, output_dir: Option<String>) -> Result<pdf::TextResult, String> {
+pub async fn tool_pdf_text(
+ input: String,
+ pages: Option<String>,
+ save: Option<bool>,
+ output_dir: Option<String>,
+) -> Result<pdf::TextResult, String> {
tokio::task::spawn_blocking(move || {
- pdf::to_text(&input, pages.as_deref().unwrap_or(""), save.unwrap_or(false), output_dir.as_deref().unwrap_or(""))
+ pdf::to_text(
+ &input,
+ pages.as_deref().unwrap_or(""),
+ save.unwrap_or(false),
+ output_dir.as_deref().unwrap_or(""),
+ )
})
.await
.map_err(err)?
@@ -45,31 +76,84 @@ pub async fn tool_pdf_text(input: String, pages: Option<String>, save: Option<bo
}
#[tauri::command]
-pub async fn tool_pdf_from_images(app: tauri::AppHandle, inputs: Vec<String>, output: String, quality: Option<u8>) -> Result<pdf::PdfOut, String> {
+pub async fn tool_pdf_from_images(
+ app: tauri::AppHandle,
+ inputs: Vec<String>,
+ output: String,
+ quality: Option<u8>,
+) -> Result<pdf::PdfOut, String> {
let p = progress(&app);
- tokio::task::spawn_blocking(move || pdf::images_to_pdf(&inputs, &output, quality.unwrap_or(0), &p)).await.map_err(err)?.map_err(err)
+ tokio::task::spawn_blocking(move || {
+ pdf::images_to_pdf(&inputs, &output, quality.unwrap_or(0), &p)
+ })
+ .await
+ .map_err(err)?
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_pdf_compress(app: tauri::AppHandle, opts: pdf::CompressOptions) -> Result<pdf::CompressResult, String> {
+pub async fn tool_pdf_compress(
+ app: tauri::AppHandle,
+ opts: pdf::CompressOptions,
+) -> Result<pdf::CompressResult, String> {
pdf::compress(opts, progress(&app)).await.map_err(err)
}
#[tauri::command]
-pub async fn tool_pdf_sanitize(app: tauri::AppHandle, input: String, output_dir: Option<String>, dpi: Option<u32>, quality: Option<u8>) -> Result<pdf::PdfOut, String> {
+pub async fn tool_pdf_sanitize(
+ app: tauri::AppHandle,
+ input: String,
+ output_dir: Option<String>,
+ dpi: Option<u32>,
+ quality: Option<u8>,
+) -> Result<pdf::PdfOut, String> {
let p = progress(&app);
- tokio::task::spawn_blocking(move || pdf::sanitize(&input, output_dir.as_deref().unwrap_or(""), dpi.unwrap_or(0), quality.unwrap_or(0), &p))
- .await
- .map_err(err)?
- .map_err(err)
+ tokio::task::spawn_blocking(move || {
+ pdf::sanitize(
+ &input,
+ output_dir.as_deref().unwrap_or(""),
+ dpi.unwrap_or(0),
+ quality.unwrap_or(0),
+ &p,
+ )
+ })
+ .await
+ .map_err(err)?
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_pdf_ocr(app: tauri::AppHandle, input: String, langs: String, output_dir: Option<String>, dpi: Option<u32>) -> Result<pdf::PdfOut, String> {
- pdf::ocr(input, langs, output_dir.unwrap_or_default(), dpi.unwrap_or(0), progress(&app)).await.map_err(err)
+pub async fn tool_pdf_ocr(
+ app: tauri::AppHandle,
+ input: String,
+ langs: String,
+ output_dir: Option<String>,
+ dpi: Option<u32>,
+) -> Result<pdf::PdfOut, String> {
+ pdf::ocr(
+ input,
+ langs,
+ output_dir.unwrap_or_default(),
+ dpi.unwrap_or(0),
+ progress(&app),
+ )
+ .await
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_pdf_office(app: tauri::AppHandle, inputs: Vec<String>, target: String, output_dir: Option<String>) -> Result<Vec<String>, String> {
- pdf::office_convert(inputs, target, output_dir.unwrap_or_default(), progress(&app)).await.map_err(err)
+pub async fn tool_pdf_office(
+ app: tauri::AppHandle,
+ inputs: Vec<String>,
+ target: String,
+ output_dir: Option<String>,
+) -> Result<Vec<String>, String> {
+ pdf::office_convert(
+ inputs,
+ target,
+ output_dir.unwrap_or_default(),
+ progress(&app),
+ )
+ .await
+ .map_err(err)
}
diff --git a/src-tauri/src/commands/tools/phone.rs b/src-tauri/src/commands/tools/phone.rs
index 3b268142..159fda73 100644
--- a/src-tauri/src/commands/tools/phone.rs
+++ b/src-tauri/src/commands/tools/phone.rs
@@ -19,7 +19,9 @@ pub async fn tool_kde_share(device: String, kind: String, value: String) -> Resu
#[tauri::command]
pub async fn tool_kde_ping(device: String, message: Option<String>) -> Result<String, String> {
- kdeconnect::ping(&device, message.as_deref().unwrap_or("")).await.map_err(err)
+ kdeconnect::ping(&device, message.as_deref().unwrap_or(""))
+ .await
+ .map_err(err)
}
#[tauri::command]
diff --git a/src-tauri/src/commands/tools/pinterest.rs b/src-tauri/src/commands/tools/pinterest.rs
index fe3ad62f..794289fa 100644
--- a/src-tauri/src/commands/tools/pinterest.rs
+++ b/src-tauri/src/commands/tools/pinterest.rs
@@ -10,14 +10,18 @@ use futures::StreamExt;
use omniget_core::core::tools::pinterest::analysis::{self, DupeGroup, Swatch};
use omniget_core::core::tools::pinterest::api::Feed;
use omniget_core::core::tools::pinterest::media::{self, DownloadOptions};
-use omniget_core::core::tools::pinterest::{export, parse_target, Board, Pin, PinClient, Section, Target, User};
+use omniget_core::core::tools::pinterest::{
+ export, parse_target, Board, Pin, PinClient, Section, Target, User,
+};
use omniget_core::core::tools::{report, ProgressFn};
use serde::{Deserialize, Serialize};
use super::{err, progress};
fn client(cookies: &Option<String>) -> Result<Arc<PinClient>, String> {
- PinClient::new(cookies.as_deref()).map(Arc::new).map_err(err)
+ PinClient::new(cookies.as_deref())
+ .map(Arc::new)
+ .map_err(err)
}
fn target_of(url: &str) -> Result<Target, String> {
@@ -54,7 +58,9 @@ fn keep(p: &Pin, f: &Filters) -> bool {
if f.skip_promoted && p.is_promoted {
return false;
}
- if f.ai_level > 0 && (p.ai.labeled || (p.ai.keyword_level > 0 && p.ai.keyword_level >= f.ai_level)) {
+ if f.ai_level > 0
+ && (p.ai.labeled || (p.ai.keyword_level > 0 && p.ai.keyword_level >= f.ai_level))
+ {
return false;
}
if !f.only_kind.is_empty() {
@@ -70,7 +76,13 @@ fn keep(p: &Pin, f: &Filters) -> bool {
}
}
if f.min_width > 0 {
- let w = p.image.as_ref().map(|m| m.width).filter(|w| *w > 0).or_else(|| p.image_large.as_ref().map(|m| m.width)).unwrap_or(0);
+ let w = p
+ .image
+ .as_ref()
+ .map(|m| m.width)
+ .filter(|w| *w > 0)
+ .or_else(|| p.image_large.as_ref().map(|m| m.width))
+ .unwrap_or(0);
if w > 0 && w < f.min_width {
return false;
}
@@ -117,10 +129,17 @@ pub async fn tool_pin_inspect(url: String, cookies: Option<String>) -> Result<In
}
out.board = Some(b);
}
- Target::Section { user, slug, section } => {
+ Target::Section {
+ user,
+ slug,
+ section,
+ } => {
let b = c.board(user, slug).await.map_err(err)?;
let secs = c.board_sections(&b.id).await.unwrap_or_default();
- out.section = secs.iter().find(|x| &x.slug == section || x.title.eq_ignore_ascii_case(section)).cloned();
+ out.section = secs
+ .iter()
+ .find(|x| &x.slug == section || x.title.eq_ignore_ascii_case(section))
+ .cloned();
out.sections = secs;
out.board = Some(b);
}
@@ -146,7 +165,14 @@ pub struct ListOut {
pub hidden: usize,
}
-async fn list_pins(c: &PinClient, target: &Target, limit: usize, filters: &Filters, pid: &str, p: &ProgressFn) -> Result<(String, Vec<Pin>, Vec<String>, usize), String> {
+async fn list_pins(
+ c: &PinClient,
+ target: &Target,
+ limit: usize,
+ filters: &Filters,
+ pid: &str,
+ p: &ProgressFn,
+) -> Result<(String, Vec<Pin>, Vec<String>, usize), String> {
let (feed, title) = c.feed_for(target).await.map_err(err)?;
let mut guides = Vec::new();
if let Feed::Search { .. } = &feed {
@@ -155,9 +181,17 @@ async fn list_pins(c: &PinClient, target: &Target, limit: usize, filters: &Filte
}
}
// com filtro, pede um pouco mais para compensar o que cai
- let fetch = if limit == 0 { 0 } else if filters.skip_promoted || filters.ai_level > 0 || !filters.only_kind.is_empty() { limit * 2 } else { limit };
+ let fetch = if limit == 0 {
+ 0
+ } else if filters.skip_promoted || filters.ai_level > 0 || !filters.only_kind.is_empty() {
+ limit * 2
+ } else {
+ limit
+ };
let pins = c
- .collect(&feed, fetch, |n| report(p, pid, "list", n as u64, None, Some(title.clone())))
+ .collect(&feed, fetch, |n| {
+ report(p, pid, "list", n as u64, None, Some(title.clone()))
+ })
.await
.map_err(err)?;
let before = pins.len();
@@ -170,18 +204,44 @@ async fn list_pins(c: &PinClient, target: &Target, limit: usize, filters: &Filte
}
#[tauri::command]
-pub async fn tool_pin_list(app: tauri::AppHandle, url: String, cookies: Option<String>, limit: Option<usize>, filters: Option<Filters>) -> Result<ListOut, String> {
+pub async fn tool_pin_list(
+ app: tauri::AppHandle,
+ url: String,
+ cookies: Option<String>,
+ limit: Option<usize>,
+ filters: Option<Filters>,
+) -> Result<ListOut, String> {
let c = client(&cookies)?;
let (target, _) = resolve(&c, &url).await?;
let filters = filters.unwrap_or_default();
let p = progress(&app);
- let (title, pins, guides, hidden) = list_pins(&c, &target, limit.unwrap_or(100), &filters, "pinterest:list", &p).await?;
- Ok(ListOut { title, target, pins, guides, hidden })
+ let (title, pins, guides, hidden) = list_pins(
+ &c,
+ &target,
+ limit.unwrap_or(100),
+ &filters,
+ "pinterest:list",
+ &p,
+ )
+ .await?;
+ Ok(ListOut {
+ title,
+ target,
+ pins,
+ guides,
+ hidden,
+ })
}
/// Pins parecidos com um pin (o "More like this").
#[tauri::command]
-pub async fn tool_pin_related(app: tauri::AppHandle, url: String, cookies: Option<String>, limit: Option<usize>, filters: Option<Filters>) -> Result<ListOut, String> {
+pub async fn tool_pin_related(
+ app: tauri::AppHandle,
+ url: String,
+ cookies: Option<String>,
+ limit: Option<usize>,
+ filters: Option<Filters>,
+) -> Result<ListOut, String> {
let c = client(&cookies)?;
let (target, _) = resolve(&c, &url).await?;
let Target::Pin { id } = &target else {
@@ -191,26 +251,48 @@ pub async fn tool_pin_related(app: tauri::AppHandle, url: String, cookies: Optio
let p = progress(&app);
let feed = Feed::Related { pin_id: id.clone() };
let pins = c
- .collect(&feed, limit.unwrap_or(60) * 2, |n| report(&p, "pinterest:related", "list", n as u64, None, None))
+ .collect(&feed, limit.unwrap_or(60) * 2, |n| {
+ report(&p, "pinterest:related", "list", n as u64, None, None)
+ })
.await
.map_err(err)?;
let before = pins.len();
- let mut kept: Vec<Pin> = pins.into_iter().filter(|x| x.id != *id && keep(x, &filters)).collect();
+ let mut kept: Vec<Pin> = pins
+ .into_iter()
+ .filter(|x| x.id != *id && keep(x, &filters))
+ .collect();
kept.truncate(limit.unwrap_or(60));
- Ok(ListOut { title: format!("parecidos com {}", id), target, hidden: before - kept.len(), pins: kept, guides: vec![] })
+ Ok(ListOut {
+ title: format!("parecidos com {}", id),
+ target,
+ hidden: before - kept.len(),
+ pins: kept,
+ guides: vec![],
+ })
}
/// Busca de boards por palavra.
#[tauri::command]
-pub async fn tool_pin_boards_search(query: String, cookies: Option<String>, limit: Option<usize>) -> Result<Vec<Board>, String> {
+pub async fn tool_pin_boards_search(
+ query: String,
+ cookies: Option<String>,
+ limit: Option<usize>,
+) -> Result<Vec<Board>, String> {
let c = client(&cookies)?;
- c.search_boards(&query, limit.unwrap_or(40)).await.map_err(err)
+ c.search_boards(&query, limit.unwrap_or(40))
+ .await
+ .map_err(err)
}
// ───────────────────────── baixar ─────────────────────────
#[tauri::command]
-pub async fn tool_pin_download(app: tauri::AppHandle, url: String, opts: DownloadOptions, cookies: Option<String>) -> Result<media::PinFiles, String> {
+pub async fn tool_pin_download(
+ app: tauri::AppHandle,
+ url: String,
+ opts: DownloadOptions,
+ cookies: Option<String>,
+) -> Result<media::PinFiles, String> {
let c = client(&cookies)?;
let (target, _) = resolve(&c, &url).await?;
let Target::Pin { id } = &target else {
@@ -220,9 +302,16 @@ pub async fn tool_pin_download(app: tauri::AppHandle, url: String, opts: Downloa
report(&p, "pinterest:pin", "download", 0, Some(1), None);
let pin = c.pin(id).await.map_err(err)?;
let dir = PathBuf::from(&opts.dest);
- let files = media::download_pin(&c, &pin, &dir, &opts).await.map_err(err)?;
+ let files = media::download_pin(&c, &pin, &dir, &opts)
+ .await
+ .map_err(err)?;
report(&p, "pinterest:pin", "done", 1, Some(1), None);
- Ok(media::PinFiles { id: pin.id.clone(), files, skipped: false, error: None })
+ Ok(media::PinFiles {
+ id: pin.id.clone(),
+ files,
+ skipped: false,
+ error: None,
+ })
}
#[derive(Debug, Clone, Serialize)]
@@ -234,11 +323,28 @@ pub struct ManyOut {
pub files: usize,
}
-async fn download_many(c: Arc<PinClient>, pins: Vec<Pin>, opts: &DownloadOptions, root: &Path, pid: &str, p: &ProgressFn) -> (HashMap<String, Vec<String>>, ManyOut) {
- let archive = if opts.skip_downloaded { media::load_archive(root) } else { Default::default() };
+async fn download_many(
+ c: Arc<PinClient>,
+ pins: Vec<Pin>,
+ opts: &DownloadOptions,
+ root: &Path,
+ pid: &str,
+ p: &ProgressFn,
+) -> (HashMap<String, Vec<String>>, ManyOut) {
+ let archive = if opts.skip_downloaded {
+ media::load_archive(root)
+ } else {
+ Default::default()
+ };
let total = pins.len();
let mut done = 0usize;
- let mut out = ManyOut { dest: root.to_string_lossy().to_string(), downloaded: 0, skipped: 0, failed: vec![], files: 0 };
+ let mut out = ManyOut {
+ dest: root.to_string_lossy().to_string(),
+ downloaded: 0,
+ skipped: 0,
+ failed: vec![],
+ files: 0,
+ };
let mut files_by_id: HashMap<String, Vec<String>> = HashMap::new();
let opts = Arc::new(opts.clone());
let root_buf = root.to_path_buf();
@@ -252,7 +358,9 @@ async fn download_many(c: Arc<PinClient>, pins: Vec<Pin>, opts: &DownloadOptions
return (pin, Ok(Vec::new()), true);
}
let dir = match (&pin.section, opts.section_folders) {
- (Some(s), true) if !s.is_empty() => root.join(omniget_core::core::tools::sanitize_name(s)),
+ (Some(s), true) if !s.is_empty() => {
+ root.join(omniget_core::core::tools::sanitize_name(s))
+ }
_ => root.clone(),
};
let r = media::download_pin(&c, &pin, &dir, &opts).await;
@@ -272,23 +380,47 @@ async fn download_many(c: Arc<PinClient>, pins: Vec<Pin>, opts: &DownloadOptions
media::append_archive(root, &pin.id);
files_by_id.insert(pin.id.clone(), files);
}
- Err(e) => out.failed.push(media::PinFiles { id: pin.id.clone(), files: vec![], skipped: false, error: Some(e.to_string()) }),
+ Err(e) => out.failed.push(media::PinFiles {
+ id: pin.id.clone(),
+ files: vec![],
+ skipped: false,
+ error: Some(e.to_string()),
+ }),
}
}
- report(p, pid, "download", done as u64, Some(total as u64), Some(pin.title.clone()));
+ report(
+ p,
+ pid,
+ "download",
+ done as u64,
+ Some(total as u64),
+ Some(pin.title.clone()),
+ );
}
(files_by_id, out)
}
/// Baixa uma lista de pins já listada (resultados de busca selecionados).
#[tauri::command]
-pub async fn tool_pin_download_many(app: tauri::AppHandle, pins: Vec<Pin>, opts: DownloadOptions, cookies: Option<String>) -> Result<ManyOut, String> {
+pub async fn tool_pin_download_many(
+ app: tauri::AppHandle,
+ pins: Vec<Pin>,
+ opts: DownloadOptions,
+ cookies: Option<String>,
+) -> Result<ManyOut, String> {
let c = client(&cookies)?;
let root = PathBuf::from(&opts.dest);
std::fs::create_dir_all(&root).map_err(err)?;
let p = progress(&app);
let (_, out) = download_many(c, pins, &opts, &root, "pinterest:many", &p).await;
- report(&p, "pinterest:many", "done", out.downloaded as u64, Some(out.downloaded as u64), None);
+ report(
+ &p,
+ "pinterest:many",
+ "done",
+ out.downloaded as u64,
+ Some(out.downloaded as u64),
+ None,
+ );
Ok(out)
}
@@ -336,18 +468,50 @@ pub struct BackupOut {
}
/// Lista um board com as seções nomeadas (pins soltos + cada seção).
-async fn board_with_sections(c: &PinClient, board: &Board, limit: usize, pid: &str, p: &ProgressFn) -> Result<Vec<Pin>, String> {
+async fn board_with_sections(
+ c: &PinClient,
+ board: &Board,
+ limit: usize,
+ pid: &str,
+ p: &ProgressFn,
+) -> Result<Vec<Pin>, String> {
let mut all: Vec<Pin> = Vec::new();
let loose = c
- .collect(&Feed::Board { board_id: board.id.clone(), include_sections: false }, limit, |n| report(p, pid, "list", n as u64, None, Some(board.name.clone())))
+ .collect(
+ &Feed::Board {
+ board_id: board.id.clone(),
+ include_sections: false,
+ },
+ limit,
+ |n| report(p, pid, "list", n as u64, None, Some(board.name.clone())),
+ )
.await
.map_err(err)?;
all.extend(loose);
if board.section_count > 0 && (limit == 0 || all.len() < limit) {
for sec in c.board_sections(&board.id).await.unwrap_or_default() {
- let want = if limit == 0 { 0 } else { limit.saturating_sub(all.len()).max(1) };
+ let want = if limit == 0 {
+ 0
+ } else {
+ limit.saturating_sub(all.len()).max(1)
+ };
let pins = c
- .collect(&Feed::Section { section_id: sec.id.clone() }, want, |n| report(p, pid, "list", (all.len() + n) as u64, None, Some(sec.title.clone())))
+ .collect(
+ &Feed::Section {
+ section_id: sec.id.clone(),
+ },
+ want,
+ |n| {
+ report(
+ p,
+ pid,
+ "list",
+ (all.len() + n) as u64,
+ None,
+ Some(sec.title.clone()),
+ )
+ },
+ )
.await
.unwrap_or_default();
for mut x in pins {
@@ -367,7 +531,14 @@ async fn board_with_sections(c: &PinClient, board: &Board, limit: usize, pid: &s
Ok(all)
}
-async fn write_outputs(title: &str, dest: &Path, pins: &[Pin], files: &HashMap<String, Vec<String>>, metadata: bool, gallery: bool) -> (Option<String>, Option<String>, Option<String>) {
+async fn write_outputs(
+ title: &str,
+ dest: &Path,
+ pins: &[Pin],
+ files: &HashMap<String, Vec<String>>,
+ metadata: bool,
+ gallery: bool,
+) -> (Option<String>, Option<String>, Option<String>) {
let mut csv_path = None;
let mut json_path = None;
let mut html_path = None;
@@ -385,7 +556,11 @@ async fn write_outputs(title: &str, dest: &Path, pins: &[Pin], files: &HashMap<S
}
if gallery {
let p = dest.join("index.html");
- let sub = format!("{} pins · OmniGet · {}", pins.len(), chrono::Local::now().format("%Y-%m-%d %H:%M"));
+ let sub = format!(
+ "{} pins · OmniGet · {}",
+ pins.len(),
+ chrono::Local::now().format("%Y-%m-%d %H:%M")
+ );
let html = export::html_gallery(title, &sub, pins, files, &dest.to_string_lossy());
if tokio::fs::write(&p, html).await.is_ok() {
html_path = Some(p.to_string_lossy().to_string());
@@ -396,7 +571,10 @@ async fn write_outputs(title: &str, dest: &Path, pins: &[Pin], files: &HashMap<S
/// Backup de board, seção, perfil (todos os boards), busca ou relacionados.
#[tauri::command]
-pub async fn tool_pin_backup(app: tauri::AppHandle, opts: BackupOptions) -> Result<BackupOut, String> {
+pub async fn tool_pin_backup(
+ app: tauri::AppHandle,
+ opts: BackupOptions,
+) -> Result<BackupOut, String> {
let c = client(&opts.cookies)?;
let (target, _) = resolve(&c, &opts.url).await?;
let p = progress(&app);
@@ -409,7 +587,11 @@ pub async fn tool_pin_backup(app: tauri::AppHandle, opts: BackupOptions) -> Resu
let user = c.user(username).await.map_err(err)?;
let boards = c.user_boards(username).await.map_err(err)?;
let mut agg = BackupOut {
- title: if user.name.is_empty() { username.clone() } else { user.name.clone() },
+ title: if user.name.is_empty() {
+ username.clone()
+ } else {
+ user.name.clone()
+ },
dest: root.to_string_lossy().to_string(),
total: 0,
hidden: 0,
@@ -425,11 +607,23 @@ pub async fn tool_pin_backup(app: tauri::AppHandle, opts: BackupOptions) -> Resu
let mut all_pins: Vec<Pin> = Vec::new();
let mut all_files: HashMap<String, Vec<String>> = HashMap::new();
for (i, b) in boards.iter().enumerate() {
- report(&p, pid, "board", i as u64, Some(boards.len() as u64), Some(b.name.clone()));
+ report(
+ &p,
+ pid,
+ "board",
+ i as u64,
+ Some(boards.len() as u64),
+ Some(b.name.clone()),
+ );
let pins = match board_with_sections(&c, b, opts.limit, pid, &p).await {
Ok(x) => x,
Err(e) => {
- agg.failed.push(media::PinFiles { id: b.id.clone(), files: vec![], skipped: false, error: Some(e) });
+ agg.failed.push(media::PinFiles {
+ id: b.id.clone(),
+ files: vec![],
+ skipped: false,
+ error: Some(e),
+ });
continue;
}
};
@@ -438,7 +632,11 @@ pub async fn tool_pin_backup(app: tauri::AppHandle, opts: BackupOptions) -> Resu
.into_iter()
.filter(|x| keep(x, &opts.filters))
.map(|mut x| {
- x.board = Some(omniget_core::core::tools::pinterest::api::BoardRef { id: Some(b.id.clone()), name: Some(b.name.clone()), url: Some(b.url.clone()) });
+ x.board = Some(omniget_core::core::tools::pinterest::api::BoardRef {
+ id: Some(b.id.clone()),
+ name: Some(b.name.clone()),
+ url: Some(b.url.clone()),
+ });
x
})
.collect();
@@ -446,7 +644,8 @@ pub async fn tool_pin_backup(app: tauri::AppHandle, opts: BackupOptions) -> Resu
agg.total += pins.len();
let bdir = root.join(omniget_core::core::tools::sanitize_name(&b.name));
std::fs::create_dir_all(&bdir).map_err(err)?;
- let (files, out) = download_many(c.clone(), pins.clone(), &opts.download, &bdir, pid, &p).await;
+ let (files, out) =
+ download_many(c.clone(), pins.clone(), &opts.download, &bdir, pid, &p).await;
agg.downloaded += out.downloaded;
agg.skipped += out.skipped;
agg.files += out.files;
@@ -457,11 +656,18 @@ pub async fn tool_pin_backup(app: tauri::AppHandle, opts: BackupOptions) -> Resu
}
if opts.include_created {
let pins = c
- .collect(&Feed::UserCreated { username: username.clone() }, opts.limit, |n| report(&p, pid, "list", n as u64, None, Some("criados".into())))
+ .collect(
+ &Feed::UserCreated {
+ username: username.clone(),
+ },
+ opts.limit,
+ |n| report(&p, pid, "list", n as u64, None, Some("criados".into())),
+ )
.await
.unwrap_or_default();
let cdir = root.join("_criados");
- let (files, out) = download_many(c.clone(), pins.clone(), &opts.download, &cdir, pid, &p).await;
+ let (files, out) =
+ download_many(c.clone(), pins.clone(), &opts.download, &cdir, pid, &p).await;
agg.total += pins.len();
agg.downloaded += out.downloaded;
agg.skipped += out.skipped;
@@ -470,11 +676,26 @@ pub async fn tool_pin_backup(app: tauri::AppHandle, opts: BackupOptions) -> Resu
all_files.extend(files);
all_pins.extend(pins);
}
- let (csv, json, html) = write_outputs(&agg.title, &root, &all_pins, &all_files, opts.metadata, opts.gallery).await;
+ let (csv, json, html) = write_outputs(
+ &agg.title,
+ &root,
+ &all_pins,
+ &all_files,
+ opts.metadata,
+ opts.gallery,
+ )
+ .await;
agg.csv_path = csv;
agg.json_path = json;
agg.html_path = html;
- report(&p, pid, "done", agg.downloaded as u64, Some(agg.total as u64), None);
+ report(
+ &p,
+ pid,
+ "done",
+ agg.downloaded as u64,
+ Some(agg.total as u64),
+ None,
+ );
return Ok(agg);
}
@@ -483,17 +704,29 @@ pub async fn tool_pin_backup(app: tauri::AppHandle, opts: BackupOptions) -> Resu
let b = c.board(user, slug).await.map_err(err)?;
let pins = board_with_sections(&c, &b, opts.limit, pid, &p).await?;
let before = pins.len();
- let pins: Vec<Pin> = pins.into_iter().filter(|x| keep(x, &opts.filters)).collect();
+ let pins: Vec<Pin> = pins
+ .into_iter()
+ .filter(|x| keep(x, &opts.filters))
+ .collect();
(b.name.clone(), pins.clone(), before - pins.len())
}
_ => {
- let (title, pins, _, hidden) = list_pins(&c, &target, opts.limit, &opts.filters, pid, &p).await?;
+ let (title, pins, _, hidden) =
+ list_pins(&c, &target, opts.limit, &opts.filters, pid, &p).await?;
(title, pins, hidden)
}
};
let (files, out) = download_many(c.clone(), pins.clone(), &opts.download, &root, pid, &p).await;
- let (csv_path, json_path, html_path) = write_outputs(&title, &root, &pins, &files, opts.metadata, opts.gallery).await;
- report(&p, pid, "done", out.downloaded as u64, Some(pins.len() as u64), None);
+ let (csv_path, json_path, html_path) =
+ write_outputs(&title, &root, &pins, &files, opts.metadata, opts.gallery).await;
+ report(
+ &p,
+ pid,
+ "done",
+ out.downloaded as u64,
+ Some(pins.len() as u64),
+ None,
+ );
Ok(BackupOut {
title,
dest: out.dest,
@@ -528,7 +761,13 @@ pub struct DupesOut {
}
#[tauri::command]
-pub async fn tool_pin_dupes(app: tauri::AppHandle, url: String, cookies: Option<String>, limit: Option<usize>, threshold: Option<u32>) -> Result<DupesOut, String> {
+pub async fn tool_pin_dupes(
+ app: tauri::AppHandle,
+ url: String,
+ cookies: Option<String>,
+ limit: Option<usize>,
+ threshold: Option<u32>,
+) -> Result<DupesOut, String> {
let c = client(&cookies)?;
let (target, _) = resolve(&c, &url).await?;
let p = progress(&app);
@@ -538,7 +777,18 @@ pub async fn tool_pin_dupes(app: tauri::AppHandle, url: String, cookies: Option<
let b = c.board(user, slug).await.map_err(err)?;
board_with_sections(&c, &b, limit.unwrap_or(0), pid, &p).await?
}
- _ => list_pins(&c, &target, limit.unwrap_or(0), &Filters::default(), pid, &p).await?.1,
+ _ => {
+ list_pins(
+ &c,
+ &target,
+ limit.unwrap_or(0),
+ &Filters::default(),
+ pid,
+ &p,
+ )
+ .await?
+ .1
+ }
};
let title = match &target {
Target::Board { slug, .. } => slug.clone(),
@@ -547,14 +797,24 @@ pub async fn tool_pin_dupes(app: tauri::AppHandle, url: String, cookies: Option<
let total = pins.len();
let inputs: Vec<(String, Option<String>, Option<String>)> = pins
.iter()
- .map(|pin| (pin.id.clone(), pin.image_signature.clone(), pin.thumb.clone().or_else(|| pin.image_large.as_ref().map(|m| m.url.clone()))))
+ .map(|pin| {
+ (
+ pin.id.clone(),
+ pin.image_signature.clone(),
+ pin.thumb
+ .clone()
+ .or_else(|| pin.image_large.as_ref().map(|m| m.url.clone())),
+ )
+ })
.collect();
let jobs = inputs.into_iter().map(|(id, sig, thumb)| {
let c = c.clone();
async move {
let hash = match thumb {
Some(u) => match c.http().get(&u).send().await {
- Ok(r) if r.status().is_success() => r.bytes().await.ok().and_then(|b| analysis::dhash(&b)),
+ Ok(r) if r.status().is_success() => {
+ r.bytes().await.ok().and_then(|b| analysis::dhash(&b))
+ }
_ => None,
},
None => None,
@@ -566,16 +826,36 @@ pub async fn tool_pin_dupes(app: tauri::AppHandle, url: String, cookies: Option<
let mut stream = futures::stream::iter(jobs).buffer_unordered(8);
while let Some(it) = stream.next().await {
items.push(it);
- report(&p, pid, "hash", items.len() as u64, Some(total as u64), None);
+ report(
+ &p,
+ pid,
+ "hash",
+ items.len() as u64,
+ Some(total as u64),
+ None,
+ );
}
let groups: Vec<DupeGroup> = analysis::group_dupes(&items, threshold.unwrap_or(6));
let by_id: HashMap<&str, &Pin> = pins.iter().map(|x| (x.id.as_str(), x)).collect();
let groups = groups
.into_iter()
- .map(|g| DupeGroupOut { kind: g.kind, distance: g.distance, pins: g.ids.iter().filter_map(|id| by_id.get(id.as_str()).map(|x| (*x).clone())).collect() })
+ .map(|g| DupeGroupOut {
+ kind: g.kind,
+ distance: g.distance,
+ pins: g
+ .ids
+ .iter()
+ .filter_map(|id| by_id.get(id.as_str()).map(|x| (*x).clone()))
+ .collect(),
+ })
.collect();
report(&p, pid, "done", total as u64, Some(total as u64), None);
- Ok(DupesOut { title, scanned: total, groups, has_session: c.has_session() })
+ Ok(DupesOut {
+ title,
+ scanned: total,
+ groups,
+ has_session: c.has_session(),
+ })
}
#[derive(Debug, Clone, Serialize)]
@@ -586,12 +866,18 @@ pub struct UnsaveOut {
/// Desfaz saves seus (exige cookies de sessão). Sequencial de propósito.
#[tauri::command]
-pub async fn tool_pin_unsave(ids: Vec<String>, cookies: Option<String>) -> Result<UnsaveOut, String> {
+pub async fn tool_pin_unsave(
+ ids: Vec<String>,
+ cookies: Option<String>,
+) -> Result<UnsaveOut, String> {
let c = client(&cookies)?;
if !c.has_session() {
return Err("informe os cookies da sua sessao do Pinterest para desfazer saves".into());
}
- let mut out = UnsaveOut { done: vec![], failed: vec![] };
+ let mut out = UnsaveOut {
+ done: vec![],
+ failed: vec![],
+ };
for id in ids {
match c.unsave(&id).await {
Ok(()) => out.done.push(id),
@@ -615,7 +901,14 @@ pub struct PaletteOut {
}
#[tauri::command]
-pub async fn tool_pin_palette(app: tauri::AppHandle, url: String, cookies: Option<String>, limit: Option<usize>, colors: Option<usize>, skip_extremes: Option<bool>) -> Result<PaletteOut, String> {
+pub async fn tool_pin_palette(
+ app: tauri::AppHandle,
+ url: String,
+ cookies: Option<String>,
+ limit: Option<usize>,
+ colors: Option<usize>,
+ skip_extremes: Option<bool>,
+) -> Result<PaletteOut, String> {
let c = client(&cookies)?;
let (target, _) = resolve(&c, &url).await?;
let p = progress(&app);
@@ -626,7 +919,15 @@ pub async fn tool_pin_palette(app: tauri::AppHandle, url: String, cookies: Optio
(pin.title.clone(), vec![pin])
}
_ => {
- let (t, pins, _, _) = list_pins(&c, &target, limit.unwrap_or(60), &Filters::default(), pid, &p).await?;
+ let (t, pins, _, _) = list_pins(
+ &c,
+ &target,
+ limit.unwrap_or(60),
+ &Filters::default(),
+ pid,
+ &p,
+ )
+ .await?;
(t, pins)
}
};
@@ -635,14 +936,30 @@ pub async fn tool_pin_palette(app: tauri::AppHandle, url: String, cookies: Optio
let total = pins.len();
let inputs: Vec<Option<String>> = pins
.iter()
- .map(|pin| if total == 1 { pin.image_large.as_ref().map(|m| m.url.clone()).or_else(|| pin.thumb.clone()) } else { pin.thumb.clone() })
+ .map(|pin| {
+ if total == 1 {
+ pin.image_large
+ .as_ref()
+ .map(|m| m.url.clone())
+ .or_else(|| pin.thumb.clone())
+ } else {
+ pin.thumb.clone()
+ }
+ })
.collect();
let jobs = inputs.into_iter().map(|u| {
let c = c.clone();
async move {
match u {
Some(u) => match c.http().get(&u).send().await {
- Ok(r) if r.status().is_success() => r.bytes().await.ok().map(|b| analysis::sample_pixels(&b, if total == 1 { 2304 } else { 400 }, skip)).unwrap_or_default(),
+ Ok(r) if r.status().is_success() => r
+ .bytes()
+ .await
+ .ok()
+ .map(|b| {
+ analysis::sample_pixels(&b, if total == 1 { 2304 } else { 400 }, skip)
+ })
+ .unwrap_or_default(),
_ => Vec::new(),
},
None => Vec::new(),
@@ -658,10 +975,18 @@ pub async fn tool_pin_palette(app: tauri::AppHandle, url: String, cookies: Optio
report(&p, pid, "sample", done as u64, Some(total as u64), None);
}
let swatches = analysis::kmeans_palette(&samples, k);
- let dom: Vec<[u8; 3]> = pins.iter().filter_map(|x| x.dominant_color.as_deref().and_then(analysis::parse_hex)).collect();
+ let dom: Vec<[u8; 3]> = pins
+ .iter()
+ .filter_map(|x| x.dominant_color.as_deref().and_then(analysis::parse_hex))
+ .collect();
let dominant = analysis::kmeans_palette(&dom, k.min(dom.len().max(1)));
report(&p, pid, "done", total as u64, Some(total as u64), None);
- Ok(PaletteOut { title, pins_used: total, swatches, dominant })
+ Ok(PaletteOut {
+ title,
+ pins_used: total,
+ swatches,
+ dominant,
+ })
}
// ───────────────────────── exportar ─────────────────────────
@@ -691,7 +1016,10 @@ pub struct ExportOut {
}
#[tauri::command]
-pub async fn tool_pin_export(app: tauri::AppHandle, opts: ExportOptions) -> Result<ExportOut, String> {
+pub async fn tool_pin_export(
+ app: tauri::AppHandle,
+ opts: ExportOptions,
+) -> Result<ExportOut, String> {
let c = client(&opts.cookies)?;
let (target, _) = resolve(&c, &opts.url).await?;
let p = progress(&app);
@@ -700,10 +1028,16 @@ pub async fn tool_pin_export(app: tauri::AppHandle, opts: ExportOptions) -> Resu
Target::Board { user, slug } => {
let b = c.board(user, slug).await.map_err(err)?;
let pins = board_with_sections(&c, &b, opts.limit, pid, &p).await?;
- (b.name.clone(), pins.into_iter().filter(|x| keep(x, &opts.filters)).collect::<Vec<_>>())
+ (
+ b.name.clone(),
+ pins.into_iter()
+ .filter(|x| keep(x, &opts.filters))
+ .collect::<Vec<_>>(),
+ )
}
_ => {
- let (t, pins, _, _) = list_pins(&c, &target, opts.limit, &opts.filters, pid, &p).await?;
+ let (t, pins, _, _) =
+ list_pins(&c, &target, opts.limit, &opts.filters, pid, &p).await?;
(t, pins)
}
};
@@ -716,23 +1050,41 @@ pub async fn tool_pin_export(app: tauri::AppHandle, opts: ExportOptions) -> Resu
let path = match opts.format.as_str() {
"csv" => {
let path = dest.join(format!("{}.csv", stem));
- tokio::fs::write(&path, export::csv(&pins, &HashMap::new())).await.map_err(err)?;
+ tokio::fs::write(&path, export::csv(&pins, &HashMap::new()))
+ .await
+ .map_err(err)?;
path
}
"json" => {
let path = dest.join(format!("{}.json", stem));
- tokio::fs::write(&path, serde_json::to_string_pretty(&pins).map_err(err)?).await.map_err(err)?;
+ tokio::fs::write(&path, serde_json::to_string_pretty(&pins).map_err(err)?)
+ .await
+ .map_err(err)?;
path
}
"pdf" => {
- let work = omniget_core::core::tools::temp_dir().join(format!("pinterest-pdf-{}", uuid::Uuid::new_v4()));
+ let work = omniget_core::core::tools::temp_dir()
+ .join(format!("pinterest-pdf-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&work).map_err(err)?;
let mut images: Vec<Vec<u8>> = Vec::new();
for (i, pin) in pins.iter().enumerate() {
- report(&p, pid, "download", i as u64, Some(pins.len() as u64), Some(pin.title.clone()));
- let Some(m) = pin.image.as_ref().or(pin.image_large.as_ref()) else { continue };
- let Ok((bytes, _)) = media::fetch_image(&c, &m.url).await else { continue };
- let jpeg = omniget_core::core::tools::pinterest::export::to_jpeg(bytes, &work, i).await.map_err(err)?;
+ report(
+ &p,
+ pid,
+ "download",
+ i as u64,
+ Some(pins.len() as u64),
+ Some(pin.title.clone()),
+ );
+ let Some(m) = pin.image.as_ref().or(pin.image_large.as_ref()) else {
+ continue;
+ };
+ let Ok((bytes, _)) = media::fetch_image(&c, &m.url).await else {
+ continue;
+ };
+ let jpeg = omniget_core::core::tools::pinterest::export::to_jpeg(bytes, &work, i)
+ .await
+ .map_err(err)?;
images.push(jpeg);
}
let _ = std::fs::remove_dir_all(&work);
@@ -762,15 +1114,30 @@ pub async fn tool_pin_export(app: tauri::AppHandle, opts: ExportOptions) -> Resu
let (f, _) = download_many(c.clone(), pins.clone(), &dl, &folder, pid, &p).await;
files = f;
}
- let sub = format!("{} pins · OmniGet · {}", pins.len(), chrono::Local::now().format("%Y-%m-%d %H:%M"));
+ let sub = format!(
+ "{} pins · OmniGet · {}",
+ pins.len(),
+ chrono::Local::now().format("%Y-%m-%d %H:%M")
+ );
let html = export::html_gallery(&title, &sub, &pins, &files, &folder.to_string_lossy());
let path = folder.join("index.html");
tokio::fs::write(&path, html).await.map_err(err)?;
path
}
};
- report(&p, pid, "done", pins.len() as u64, Some(pins.len() as u64), None);
- Ok(ExportOut { title, path: path.to_string_lossy().to_string(), pins: pins.len() })
+ report(
+ &p,
+ pid,
+ "done",
+ pins.len() as u64,
+ Some(pins.len() as u64),
+ None,
+ );
+ Ok(ExportOut {
+ title,
+ path: path.to_string_lossy().to_string(),
+ pins: pins.len(),
+ })
}
// ───────────────────────── palavras-chave ─────────────────────────
@@ -787,23 +1154,65 @@ pub struct KeywordsOut {
}
#[tauri::command]
-pub async fn tool_pin_keywords(term: String, cookies: Option<String>) -> Result<KeywordsOut, String> {
+pub async fn tool_pin_keywords(
+ term: String,
+ cookies: Option<String>,
+) -> Result<KeywordsOut, String> {
let c = client(&cookies)?;
let term = term.trim().to_string();
if term.is_empty() {
return Err("digite um termo".into());
}
let suggestions = c.typeahead(&term).await.unwrap_or_default();
- let feed = Feed::Search { query: term.clone(), scope: "pins".into() };
+ let feed = Feed::Search {
+ query: term.clone(),
+ scope: "pins".into(),
+ };
let (pins, _, guides) = c.feed_page(&feed, None, 50).await.map_err(err)?;
- let stop: &[&str] = &["the", "and", "for", "with", "your", "this", "that", "from", "you", "are", "how", "our", "para", "com", "que", "uma", "dos", "das", "los", "las", "por", "una", "more", "ideas", "idea", "pin", "pinterest", "http", "https", "www", "com"];
+ let stop: &[&str] = &[
+ "the",
+ "and",
+ "for",
+ "with",
+ "your",
+ "this",
+ "that",
+ "from",
+ "you",
+ "are",
+ "how",
+ "our",
+ "para",
+ "com",
+ "que",
+ "uma",
+ "dos",
+ "das",
+ "los",
+ "las",
+ "por",
+ "una",
+ "more",
+ "ideas",
+ "idea",
+ "pin",
+ "pinterest",
+ "http",
+ "https",
+ "www",
+ "com",
+ ];
let mut counts: HashMap<String, usize> = HashMap::new();
for p in &pins {
let text = format!("{} {} {}", p.title, p.description, p.alt_text).to_lowercase();
let mut seen: Vec<String> = Vec::new();
for w in text.split(|c: char| !(c.is_alphanumeric() || c == '#' || c == '-')) {
let w = w.trim_matches('-');
- if w.len() < 3 || stop.contains(&w) || w.chars().all(|c| c.is_ascii_digit()) || seen.iter().any(|s| s == w) {
+ if w.len() < 3
+ || stop.contains(&w)
+ || w.chars().all(|c| c.is_ascii_digit())
+ || seen.iter().any(|s| s == w)
+ {
continue;
}
seen.push(w.to_string());
@@ -813,7 +1222,13 @@ pub async fn tool_pin_keywords(term: String, cookies: Option<String>) -> Result<
let mut common: Vec<(String, usize)> = counts.into_iter().filter(|(_, n)| *n >= 2).collect();
common.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
common.truncate(40);
- Ok(KeywordsOut { term, suggestions, guides, common, sample: pins.len() })
+ Ok(KeywordsOut {
+ term,
+ suggestions,
+ guides,
+ common,
+ sample: pins.len(),
+ })
}
// ───────────────────────── fonte ─────────────────────────
@@ -839,7 +1254,13 @@ pub struct SourceOut {
async fn check_link(url: &str) -> LinkCheck {
let Ok(client) = omniget_core::core::tools::client() else {
- return LinkCheck { url: url.into(), status: None, final_url: None, ok: false, error: Some("cliente".into()) };
+ return LinkCheck {
+ url: url.into(),
+ status: None,
+ final_url: None,
+ ok: false,
+ error: Some("cliente".into()),
+ };
};
let timeout = std::time::Duration::from_secs(15);
let r = match client.head(url).timeout(timeout).send().await {
@@ -849,9 +1270,21 @@ async fn check_link(url: &str) -> LinkCheck {
match r {
Ok(r) => {
let st = r.status().as_u16();
- LinkCheck { url: url.into(), status: Some(st), final_url: Some(r.url().to_string()), ok: (200..400).contains(&st), error: None }
+ LinkCheck {
+ url: url.into(),
+ status: Some(st),
+ final_url: Some(r.url().to_string()),
+ ok: (200..400).contains(&st),
+ error: None,
+ }
}
- Err(e) => LinkCheck { url: url.into(), status: None, final_url: None, ok: false, error: Some(e.to_string()) },
+ Err(e) => LinkCheck {
+ url: url.into(),
+ status: None,
+ final_url: None,
+ ok: false,
+ error: Some(e.to_string()),
+ },
}
}
@@ -865,7 +1298,9 @@ async fn wayback(url: &str) -> Option<String> {
.await
.ok()?;
let v: serde_json::Value = r.json().await.ok()?;
- v["archived_snapshots"]["closest"]["url"].as_str().map(|s| s.to_string())
+ v["archived_snapshots"]["closest"]["url"]
+ .as_str()
+ .map(|s| s.to_string())
}
#[tauri::command]
@@ -876,20 +1311,46 @@ pub async fn tool_pin_source(url: String, cookies: Option<String>) -> Result<Sou
return Err("cole o link de um pin".into());
};
let pin = c.pin(id).await.map_err(err)?;
- let img = pin.image.as_ref().or(pin.image_large.as_ref()).map(|m| m.url.clone()).unwrap_or_default();
+ let img = pin
+ .image
+ .as_ref()
+ .or(pin.image_large.as_ref())
+ .map(|m| m.url.clone())
+ .unwrap_or_default();
let enc = urlencoding::encode(&img).to_string();
let reverse = if img.is_empty() {
vec![]
} else {
vec![
- ("Google Lens".to_string(), format!("https://lens.google.com/uploadbyurl?url={}", enc)),
- ("TinEye".to_string(), format!("https://tineye.com/search?url={}", enc)),
- ("Yandex".to_string(), format!("https://yandex.com/images/search?rpt=imageview&url={}", enc)),
- ("Bing".to_string(), format!("https://www.bing.com/images/search?view=detailv2&iss=sbi&q=imgurl:{}", enc)),
- ("SauceNAO".to_string(), format!("https://saucenao.com/search.php?url={}", enc)),
+ (
+ "Google Lens".to_string(),
+ format!("https://lens.google.com/uploadbyurl?url={}", enc),
+ ),
+ (
+ "TinEye".to_string(),
+ format!("https://tineye.com/search?url={}", enc),
+ ),
+ (
+ "Yandex".to_string(),
+ format!("https://yandex.com/images/search?rpt=imageview&url={}", enc),
+ ),
+ (
+ "Bing".to_string(),
+ format!(
+ "https://www.bing.com/images/search?view=detailv2&iss=sbi&q=imgurl:{}",
+ enc
+ ),
+ ),
+ (
+ "SauceNAO".to_string(),
+ format!("https://saucenao.com/search.php?url={}", enc),
+ ),
]
};
- let link_url = pin.link.clone().or_else(|| pin.rich.as_ref().and_then(|r| r.url.clone()));
+ let link_url = pin
+ .link
+ .clone()
+ .or_else(|| pin.rich.as_ref().and_then(|r| r.url.clone()));
let (link, wb) = match &link_url {
Some(l) => {
let chk = check_link(l).await;
@@ -898,7 +1359,13 @@ pub async fn tool_pin_source(url: String, cookies: Option<String>) -> Result<Sou
}
None => (None, None),
};
- Ok(SourceOut { pin, link, wayback: wb, reverse, resolved_url })
+ Ok(SourceOut {
+ pin,
+ link,
+ wayback: wb,
+ reverse,
+ resolved_url,
+ })
}
/// Expande pin.it e devolve a URL final + alvo reconhecido.
diff --git a/src-tauri/src/commands/tools/speech.rs b/src-tauri/src/commands/tools/speech.rs
index 2aa1cdac..792ca442 100644
--- a/src-tauri/src/commands/tools/speech.rs
+++ b/src-tauri/src/commands/tools/speech.rs
@@ -10,13 +10,25 @@ pub async fn tool_whisper_status() -> whisper::WhisperStatus {
}
#[tauri::command]
-pub async fn tool_whisper_install(app: tauri::AppHandle, variant: String) -> Result<String, String> {
- whisper::install(&variant, progress(&app)).await.map(|p| p.to_string_lossy().to_string()).map_err(err)
+pub async fn tool_whisper_install(
+ app: tauri::AppHandle,
+ variant: String,
+) -> Result<String, String> {
+ whisper::install(&variant, progress(&app))
+ .await
+ .map(|p| p.to_string_lossy().to_string())
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_whisper_model_download(app: tauri::AppHandle, id: String) -> Result<String, String> {
- whisper::download_model(&id, progress(&app)).await.map(|p| p.to_string_lossy().to_string()).map_err(err)
+pub async fn tool_whisper_model_download(
+ app: tauri::AppHandle,
+ id: String,
+) -> Result<String, String> {
+ whisper::download_model(&id, progress(&app))
+ .await
+ .map(|p| p.to_string_lossy().to_string())
+ .map_err(err)
}
#[tauri::command]
@@ -25,7 +37,10 @@ pub async fn tool_whisper_model_remove(id: String) -> Result<(), String> {
}
#[tauri::command]
-pub async fn tool_whisper_transcribe(app: tauri::AppHandle, opts: whisper::TranscribeOptions) -> Result<whisper::TranscribeResult, String> {
+pub async fn tool_whisper_transcribe(
+ app: tauri::AppHandle,
+ opts: whisper::TranscribeOptions,
+) -> Result<whisper::TranscribeResult, String> {
whisper::transcribe(opts, progress(&app)).await.map_err(err)
}
@@ -35,8 +50,14 @@ pub async fn tool_tts_voices() -> Result<Vec<edge_tts::Voice>, String> {
}
#[tauri::command]
-pub async fn tool_tts_speak(app: tauri::AppHandle, opts: edge_tts::TtsOptions, output_path: String) -> Result<edge_tts::TtsResult, String> {
- edge_tts::synthesize(opts, std::path::Path::new(&output_path), progress(&app)).await.map_err(err)
+pub async fn tool_tts_speak(
+ app: tauri::AppHandle,
+ opts: edge_tts::TtsOptions,
+ output_path: String,
+) -> Result<edge_tts::TtsResult, String> {
+ edge_tts::synthesize(opts, std::path::Path::new(&output_path), progress(&app))
+ .await
+ .map_err(err)
}
#[derive(Serialize)]
@@ -61,7 +82,9 @@ pub async fn tool_srt_translate(
return Err("a legenda esta vazia ou num formato desconhecido".into());
}
let target = opts.target_lang.clone();
- let result = srt_translate::translate_cues(&cues, &opts, progress(&app)).await.map_err(err)?;
+ let result = srt_translate::translate_cues(&cues, &opts, progress(&app))
+ .await
+ .map_err(err)?;
let mut out = result.cues;
if bilingual {
for (i, c) in out.iter_mut().enumerate() {
@@ -70,16 +93,32 @@ pub async fn tool_srt_translate(
}
}
}
- let out_path = output_path.filter(|p| !p.trim().is_empty()).unwrap_or_else(|| {
- let p = std::path::Path::new(&srt_path);
- let stem = p.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "legenda".into());
- p.with_file_name(format!("{}.{}.srt", stem, target)).to_string_lossy().to_string()
- });
- tokio::fs::write(&out_path, cues_to_srt(&out)).await.map_err(err)?;
- Ok(SrtTranslateOut { output_path: out_path, cues: out.len(), failed: result.failed.len() })
+ let out_path = output_path
+ .filter(|p| !p.trim().is_empty())
+ .unwrap_or_else(|| {
+ let p = std::path::Path::new(&srt_path);
+ let stem = p
+ .file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| "legenda".into());
+ p.with_file_name(format!("{}.{}.srt", stem, target))
+ .to_string_lossy()
+ .to_string()
+ });
+ tokio::fs::write(&out_path, cues_to_srt(&out))
+ .await
+ .map_err(err)?;
+ Ok(SrtTranslateOut {
+ output_path: out_path,
+ cues: out.len(),
+ failed: result.failed.len(),
+ })
}
#[tauri::command]
-pub async fn tool_dub(app: tauri::AppHandle, opts: dub::DubOptions) -> Result<dub::DubResult, String> {
+pub async fn tool_dub(
+ app: tauri::AppHandle,
+ opts: dub::DubOptions,
+) -> Result<dub::DubResult, String> {
dub::dub(opts, progress(&app)).await.map_err(err)
}
diff --git a/src-tauri/src/commands/tools/system.rs b/src-tauri/src/commands/tools/system.rs
index 67473f60..f56a79d4 100644
--- a/src-tauri/src/commands/tools/system.rs
+++ b/src-tauri/src/commands/tools/system.rs
@@ -2,7 +2,9 @@
//! inicialização, desinstalador e (só Windows) debloat, registro e
//! atualizador. A lógica mora em `omniget_core::core::tools`.
-use omniget_core::core::tools::{disk, startup, sysclean, uninstall, win_apps, win_registry, win_tweaks, win_updater};
+use omniget_core::core::tools::{
+ disk, startup, sysclean, uninstall, win_apps, win_registry, win_tweaks, win_updater,
+};
use serde::Serialize;
use super::{err, progress};
@@ -22,13 +24,20 @@ pub async fn tool_win_tweak_apply(id: String, enable: bool) -> Result<win_tweaks
#[tauri::command]
pub async fn tool_clean_scan(app: tauri::AppHandle) -> Result<Vec<sysclean::CleanRule>, String> {
let p = progress(&app);
- tokio::task::spawn_blocking(move || sysclean::scan(&p)).await.map_err(err)
+ tokio::task::spawn_blocking(move || sysclean::scan(&p))
+ .await
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_clean_run(app: tauri::AppHandle, req: sysclean::CleanRequest) -> Result<sysclean::CleanResult, String> {
+pub async fn tool_clean_run(
+ app: tauri::AppHandle,
+ req: sysclean::CleanRequest,
+) -> Result<sysclean::CleanResult, String> {
let p = progress(&app);
- tokio::task::spawn_blocking(move || sysclean::clean(&req, &p)).await.map_err(err)
+ tokio::task::spawn_blocking(move || sysclean::clean(&req, &p))
+ .await
+ .map_err(err)
}
// ── Analisador de disco ──
@@ -39,9 +48,19 @@ pub fn tool_disk_volumes() -> Vec<disk::Volume> {
}
#[tauri::command]
-pub async fn tool_disk_scan(app: tauri::AppHandle, root: String, depth: Option<usize>, children: Option<usize>) -> Result<disk::DiskScan, String> {
+pub async fn tool_disk_scan(
+ app: tauri::AppHandle,
+ root: String,
+ depth: Option<usize>,
+ children: Option<usize>,
+) -> Result<disk::DiskScan, String> {
let p = progress(&app);
- tokio::task::spawn_blocking(move || disk::scan(&root, depth.unwrap_or(4), children.unwrap_or(40), &p)).await.map_err(err)?.map_err(err)
+ tokio::task::spawn_blocking(move || {
+ disk::scan(&root, depth.unwrap_or(4), children.unwrap_or(40), &p)
+ })
+ .await
+ .map_err(err)?
+ .map_err(err)
}
#[derive(Serialize)]
@@ -64,7 +83,10 @@ pub async fn tool_startup_list() -> Vec<startup::StartupItem> {
}
#[tauri::command]
-pub async fn tool_startup_set(item: startup::StartupItem, enabled: bool) -> Result<Vec<startup::StartupItem>, String> {
+pub async fn tool_startup_set(
+ item: startup::StartupItem,
+ enabled: bool,
+) -> Result<Vec<startup::StartupItem>, String> {
startup::set_enabled(&item, enabled).await.map_err(err)?;
Ok(startup::list().await)
}
@@ -78,11 +100,16 @@ pub async fn tool_uninstall_list(app: tauri::AppHandle) -> Vec<uninstall::App> {
#[tauri::command]
pub async fn tool_uninstall_leftovers(app: uninstall::App) -> Vec<uninstall::Leftover> {
- tokio::task::spawn_blocking(move || uninstall::leftovers(&app)).await.unwrap_or_default()
+ tokio::task::spawn_blocking(move || uninstall::leftovers(&app))
+ .await
+ .unwrap_or_default()
}
#[tauri::command]
-pub async fn tool_uninstall_run(app: uninstall::App, leftovers: Vec<String>) -> uninstall::UninstallResult {
+pub async fn tool_uninstall_run(
+ app: uninstall::App,
+ leftovers: Vec<String>,
+) -> uninstall::UninstallResult {
uninstall::uninstall(&app, &leftovers).await
}
@@ -94,7 +121,11 @@ pub async fn tool_debloat_list() -> Result<Vec<win_apps::AppxPackage>, String> {
}
#[tauri::command]
-pub async fn tool_debloat_remove(app: tauri::AppHandle, names: Vec<String>, provisioned: Option<bool>) -> win_apps::RemoveResult {
+pub async fn tool_debloat_remove(
+ app: tauri::AppHandle,
+ names: Vec<String>,
+ provisioned: Option<bool>,
+) -> win_apps::RemoveResult {
win_apps::remove(&names, provisioned.unwrap_or(false), &progress(&app)).await
}
@@ -124,6 +155,9 @@ pub async fn tool_updater_status() -> win_updater::UpdaterStatus {
}
#[tauri::command]
-pub async fn tool_updater_upgrade(app: tauri::AppHandle, items: Vec<win_updater::Outdated>) -> win_updater::UpgradeResult {
+pub async fn tool_updater_upgrade(
+ app: tauri::AppHandle,
+ items: Vec<win_updater::Outdated>,
+) -> win_updater::UpgradeResult {
win_updater::upgrade(&items, &progress(&app)).await
}
diff --git a/src-tauri/src/commands/tools/x.rs b/src-tauri/src/commands/tools/x.rs
index e72315f6..1634d6ad 100644
--- a/src-tauri/src/commands/tools/x.rs
+++ b/src-tauri/src/commands/tools/x.rs
@@ -1,6 +1,8 @@
//! Comandos da categoria X / Twitter (estudo 67).
-use omniget_core::core::tools::x::{self, archive, bookmarks, follows, grok, media, profile, search, thread, XPost, XUser};
+use omniget_core::core::tools::x::{
+ self, archive, bookmarks, follows, grok, media, profile, search, thread, XPost, XUser,
+};
use serde::Serialize;
use super::{err, progress};
@@ -19,14 +21,26 @@ pub async fn tool_x_session() -> Result<XSession, String> {
let client = x::client::XClient::new().map_err(err)?;
let logged_in = client.authed();
let user_id = client.user_id();
- let user = if logged_in { follows::me(&client).await.ok() } else { None };
- Ok(XSession { logged_in, user_id, user, query_ids_cached: x::query_ids::cached_count(), query_ids_age_secs: x::query_ids::cache_age_secs() })
+ let user = if logged_in {
+ follows::me(&client).await.ok()
+ } else {
+ None
+ };
+ Ok(XSession {
+ logged_in,
+ user_id,
+ user,
+ query_ids_cached: x::query_ids::cached_count(),
+ query_ids_age_secs: x::query_ids::cache_age_secs(),
+ })
}
#[tauri::command]
pub async fn tool_x_query_ids_refresh() -> Result<usize, String> {
let client = x::client::XClient::new().map_err(err)?;
- x::query_ids::refresh(&client.http, client.cookie()).await.map_err(err)
+ x::query_ids::refresh(&client.http, client.cookie())
+ .await
+ .map_err(err)
}
#[tauri::command]
@@ -36,7 +50,8 @@ pub fn tool_x_cancel(job: String) {
#[tauri::command]
pub async fn tool_x_post(input: String) -> Result<XPost, String> {
- let id = x::post_id_from(&input).ok_or_else(|| format!("nao reconheci um post do X em: {}", input))?;
+ let id = x::post_id_from(&input)
+ .ok_or_else(|| format!("nao reconheci um post do X em: {}", input))?;
x::fx::status(&id).await.map_err(err)
}
@@ -46,17 +61,30 @@ pub async fn tool_x_thread(input: String) -> Result<thread::Thread, String> {
}
#[tauri::command]
-pub fn tool_x_export_posts(posts: Vec<XPost>, format: String, dest: String, title: String) -> Result<String, String> {
+pub fn tool_x_export_posts(
+ posts: Vec<XPost>,
+ format: String,
+ dest: String,
+ title: String,
+) -> Result<String, String> {
x::export::write_posts(&posts, &format, std::path::Path::new(&dest), &title).map_err(err)
}
#[tauri::command]
-pub fn tool_x_export_users(users: Vec<XUser>, format: String, dest: String) -> Result<String, String> {
+pub fn tool_x_export_users(
+ users: Vec<XUser>,
+ format: String,
+ dest: String,
+) -> Result<String, String> {
x::export::write_users(&users, &format, std::path::Path::new(&dest)).map_err(err)
}
#[tauri::command]
-pub fn tool_x_render_posts(posts: Vec<XPost>, format: String, title: String) -> Result<String, String> {
+pub fn tool_x_render_posts(
+ posts: Vec<XPost>,
+ format: String,
+ title: String,
+) -> Result<String, String> {
Ok(match format.as_str() {
"md" | "markdown" => x::export::posts_markdown(&title, &posts),
"html" => x::export::posts_html(&title, &posts),
@@ -67,30 +95,77 @@ pub fn tool_x_render_posts(posts: Vec<XPost>, format: String, title: String) ->
}
#[tauri::command]
-pub async fn tool_x_profile(input: String, limit: Option<usize>, with_replies: Option<bool>) -> Result<profile::ProfileReport, String> {
- profile::analyze(&input, limit.unwrap_or(200), with_replies.unwrap_or(false)).await.map_err(err)
+pub async fn tool_x_profile(
+ input: String,
+ limit: Option<usize>,
+ with_replies: Option<bool>,
+) -> Result<profile::ProfileReport, String> {
+ profile::analyze(&input, limit.unwrap_or(200), with_replies.unwrap_or(false))
+ .await
+ .map_err(err)
}
#[tauri::command]
pub async fn tool_x_profile_lookup(input: String) -> Result<XUser, String> {
- let handle = x::handle_from(&input).ok_or_else(|| format!("nao reconheci um perfil do X em: {}", input))?;
+ let handle = x::handle_from(&input)
+ .ok_or_else(|| format!("nao reconheci um perfil do X em: {}", input))?;
x::fx::profile(&handle).await.map_err(err)
}
#[tauri::command]
-pub async fn tool_x_media(app: tauri::AppHandle, input: String, dest: String, limit: Option<usize>, photos: Option<bool>, videos: Option<bool>) -> Result<media::MediaResult, String> {
- media::download_profile(&input, &dest, limit.unwrap_or(0), photos.unwrap_or(true), videos.unwrap_or(true), progress(&app)).await.map_err(err)
+pub async fn tool_x_media(
+ app: tauri::AppHandle,
+ input: String,
+ dest: String,
+ limit: Option<usize>,
+ photos: Option<bool>,
+ videos: Option<bool>,
+) -> Result<media::MediaResult, String> {
+ media::download_profile(
+ &input,
+ &dest,
+ limit.unwrap_or(0),
+ photos.unwrap_or(true),
+ videos.unwrap_or(true),
+ progress(&app),
+ )
+ .await
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_x_media_posts(app: tauri::AppHandle, posts: Vec<XPost>, dest: String, job: String) -> Result<media::MediaResult, String> {
+pub async fn tool_x_media_posts(
+ app: tauri::AppHandle,
+ posts: Vec<XPost>,
+ dest: String,
+ job: String,
+) -> Result<media::MediaResult, String> {
x::clear_cancel(&job);
- media::download_posts(&posts, std::path::Path::new(&dest), true, true, &job, &progress(&app)).await.map_err(err)
+ media::download_posts(
+ &posts,
+ std::path::Path::new(&dest),
+ true,
+ true,
+ &job,
+ &progress(&app),
+ )
+ .await
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_x_search(query: String, feed: Option<String>, cursor: Option<String>) -> Result<search::SearchPage, String> {
- search::search(&query, feed.as_deref().unwrap_or("latest"), cursor.as_deref()).await.map_err(err)
+pub async fn tool_x_search(
+ query: String,
+ feed: Option<String>,
+ cursor: Option<String>,
+) -> Result<search::SearchPage, String> {
+ search::search(
+ &query,
+ feed.as_deref().unwrap_or("latest"),
+ cursor.as_deref(),
+ )
+ .await
+ .map_err(err)
}
#[tauri::command]
@@ -99,18 +174,51 @@ pub async fn tool_x_trends() -> Result<Vec<x::fx::Trend>, String> {
}
#[tauri::command]
-pub async fn tool_x_bookmarks_export(app: tauri::AppHandle, dest: String, formats: Vec<String>, with_media: Option<bool>, max: Option<usize>) -> Result<bookmarks::BookmarksResult, String> {
- bookmarks::export(&dest, &formats, with_media.unwrap_or(false), max.unwrap_or(0), progress(&app)).await.map_err(err)
+pub async fn tool_x_bookmarks_export(
+ app: tauri::AppHandle,
+ dest: String,
+ formats: Vec<String>,
+ with_media: Option<bool>,
+ max: Option<usize>,
+) -> Result<bookmarks::BookmarksResult, String> {
+ bookmarks::export(
+ &dest,
+ &formats,
+ with_media.unwrap_or(false),
+ max.unwrap_or(0),
+ progress(&app),
+ )
+ .await
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_x_follows_audit(app: tauri::AppHandle, limit: Option<usize>) -> Result<follows::Audit, String> {
- follows::audit(limit.unwrap_or(0), progress(&app)).await.map_err(err)
+pub async fn tool_x_follows_audit(
+ app: tauri::AppHandle,
+ limit: Option<usize>,
+) -> Result<follows::Audit, String> {
+ follows::audit(limit.unwrap_or(0), progress(&app))
+ .await
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_x_unfollow(app: tauri::AppHandle, ids: Vec<String>, min_delay: Option<u64>, max_delay: Option<u64>, daily_cap: Option<usize>) -> Result<follows::UnfollowResult, String> {
- follows::unfollow(&ids, min_delay.unwrap_or(15), max_delay.unwrap_or(40), daily_cap.unwrap_or(100), progress(&app)).await.map_err(err)
+pub async fn tool_x_unfollow(
+ app: tauri::AppHandle,
+ ids: Vec<String>,
+ min_delay: Option<u64>,
+ max_delay: Option<u64>,
+ daily_cap: Option<usize>,
+) -> Result<follows::UnfollowResult, String> {
+ follows::unfollow(
+ &ids,
+ min_delay.unwrap_or(15),
+ max_delay.unwrap_or(40),
+ daily_cap.unwrap_or(100),
+ progress(&app),
+ )
+ .await
+ .map_err(err)
}
#[tauri::command]
@@ -125,12 +233,23 @@ pub fn tool_x_whitelist_set(handles: Vec<String>) -> Result<Vec<String>, String>
#[tauri::command]
pub async fn tool_x_archive_open(path: String) -> Result<archive::ArchiveSummary, String> {
- tokio::task::spawn_blocking(move || archive::open(&path)).await.map_err(err)?.map_err(err)
+ tokio::task::spawn_blocking(move || archive::open(&path))
+ .await
+ .map_err(err)?
+ .map_err(err)
}
#[tauri::command]
-pub async fn tool_x_archive_export(path: String, dest: String, what: String, format: String) -> Result<String, String> {
- tokio::task::spawn_blocking(move || archive::export(&path, &dest, &what, &format)).await.map_err(err)?.map_err(err)
+pub async fn tool_x_archive_export(
+ path: String,
+ dest: String,
+ what: String,
+ format: String,
+) -> Result<String, String> {
+ tokio::task::spawn_blocking(move || archive::export(&path, &dest, &what, &format))
+ .await
+ .map_err(err)?
+ .map_err(err)
}
#[tauri::command]
@@ -139,7 +258,11 @@ pub fn tool_x_grok_config() -> grok::GrokConfigView {
}
#[tauri::command]
-pub fn tool_x_grok_config_set(xai_key: Option<String>, xai_model: Option<String>, x_model: Option<String>) -> Result<grok::GrokConfigView, String> {
+pub fn tool_x_grok_config_set(
+ xai_key: Option<String>,
+ xai_model: Option<String>,
+ x_model: Option<String>,
+) -> Result<grok::GrokConfigView, String> {
grok::set(xai_key, xai_model, x_model).map_err(err)
}
@@ -153,13 +276,30 @@ pub async fn tool_x_grok_ask(request: grok::GrokRequest) -> Result<grok::GrokAns
pub async fn tool_x_data_url(url: String) -> Result<String, String> {
use base64::Engine;
let client = omniget_core::core::tools::client().map_err(err)?;
- let resp = client.get(&url).header("Referer", "https://x.com/").send().await.map_err(err)?;
+ let resp = client
+ .get(&url)
+ .header("Referer", "https://x.com/")
+ .send()
+ .await
+ .map_err(err)?;
if !resp.status().is_success() {
return Err(format!("HTTP {}", resp.status()));
}
- let mime = resp.headers().get("content-type").and_then(|v| v.to_str().ok()).unwrap_or("image/jpeg").split(';').next().unwrap_or("image/jpeg").to_string();
+ let mime = resp
+ .headers()
+ .get("content-type")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("image/jpeg")
+ .split(';')
+ .next()
+ .unwrap_or("image/jpeg")
+ .to_string();
let bytes = resp.bytes().await.map_err(err)?;
- Ok(format!("data:{};base64,{}", mime, base64::engine::general_purpose::STANDARD.encode(&bytes)))
+ Ok(format!(
+ "data:{};base64,{}",
+ mime,
+ base64::engine::general_purpose::STANDARD.encode(&bytes)
+ ))
}
/// Grava um PNG (data URL) vindo do canvas.
@@ -167,7 +307,9 @@ pub async fn tool_x_data_url(url: String) -> Result<String, String> {
pub async fn tool_x_save_data_url(data_url: String, dest: String) -> Result<String, String> {
use base64::Engine;
let b64 = data_url.split(',').nth(1).ok_or("data URL invalida")?;
- let bytes = base64::engine::general_purpose::STANDARD.decode(b64).map_err(err)?;
+ let bytes = base64::engine::general_purpose::STANDARD
+ .decode(b64)
+ .map_err(err)?;
if let Some(parent) = std::path::Path::new(&dest).parent() {
std::fs::create_dir_all(parent).map_err(err)?;
}
diff --git a/src-tauri/src/commands/tools/youtube.rs b/src-tauri/src/commands/tools/youtube.rs
index 1e36465f..c65d1e58 100644
--- a/src-tauri/src/commands/tools/youtube.rs
+++ b/src-tauri/src/commands/tools/youtube.rs
@@ -3,8 +3,13 @@ use omniget_core::core::tools::{ryd, sponsorblock};
use super::err;
#[tauri::command]
-pub async fn tool_sponsorblock(url: String, categories: Option<Vec<String>>) -> Result<sponsorblock::SponsorResult, String> {
- sponsorblock::segments(&url, &categories.unwrap_or_default()).await.map_err(err)
+pub async fn tool_sponsorblock(
+ url: String,
+ categories: Option<Vec<String>>,
+) -> Result<sponsorblock::SponsorResult, String> {
+ sponsorblock::segments(&url, &categories.unwrap_or_default())
+ .await
+ .map_err(err)
}
#[tauri::command]
diff --git a/src-tauri/src/cookies/commands.rs b/src-tauri/src/cookies/commands.rs
index 2fe4b01e..5b73eb92 100644
--- a/src-tauri/src/cookies/commands.rs
+++ b/src-tauri/src/cookies/commands.rs
@@ -472,17 +472,32 @@ fn test_x_twitter_cookie(slug: Option<&str>) -> CookieTestResponse {
fn test_instagram_cookie(slug: Option<&str>) -> CookieTestResponse {
let Some(path) = storage::account_path_for_consumer("instagram.com", slug) else {
- return CookieTestResponse { ok: false, message: "No Instagram cookie account found".to_string() };
+ return CookieTestResponse {
+ ok: false,
+ message: "No Instagram cookie account found".to_string(),
+ };
};
let Ok(content) = std::fs::read_to_string(path) else {
- return CookieTestResponse { ok: false, message: "Could not read Instagram cookie file".to_string() };
+ return CookieTestResponse {
+ ok: false,
+ message: "Could not read Instagram cookie file".to_string(),
+ };
};
let names = cookie_names_from_netscape(&content);
- let missing: Vec<&str> = ["sessionid", "ds_user_id", "csrftoken"].into_iter().filter(|n| !names.contains(*n)).collect();
+ let missing: Vec<&str> = ["sessionid", "ds_user_id", "csrftoken"]
+ .into_iter()
+ .filter(|n| !names.contains(*n))
+ .collect();
if missing.is_empty() {
- CookieTestResponse { ok: true, message: "ok".to_string() }
+ CookieTestResponse {
+ ok: true,
+ message: "ok".to_string(),
+ }
} else {
- CookieTestResponse { ok: false, message: format!("Missing Instagram cookie fields: {}", missing.join(", ")) }
+ CookieTestResponse {
+ ok: false,
+ message: format!("Missing Instagram cookie fields: {}", missing.join(", ")),
+ }
}
}
diff --git a/src-tauri/src/cookies/platform.rs b/src-tauri/src/cookies/platform.rs
index 5a4e90c3..7f17f273 100644
--- a/src-tauri/src/cookies/platform.rs
+++ b/src-tauri/src/cookies/platform.rs
@@ -78,13 +78,11 @@ impl PlatformKind {
/// long (`app.rocketseat.com.br` -> `rocketseat.com.br`). Without this the
/// Cookie Manager filed every Brazilian site under one `com.br` bucket.
const TWO_LABEL_PUBLIC_SUFFIXES: &[&str] = &[
- "com.br", "net.br", "org.br", "edu.br", "gov.br", "art.br", "eng.br",
- "co.uk", "org.uk", "ac.uk", "gov.uk", "me.uk",
- "com.au", "net.au", "org.au", "edu.au",
- "co.jp", "ne.jp", "or.jp", "ac.jp",
- "com.mx", "org.mx", "com.ar", "com.co", "com.pe", "com.cl", "com.ve", "com.uy",
- "co.za", "co.nz", "co.in", "co.kr", "co.id", "com.sg", "com.hk", "com.tw", "com.my",
- "com.tr", "com.pt", "com.es", "com.pl", "com.ua", "com.ru", "com.cn", "com.ph",
+ "com.br", "net.br", "org.br", "edu.br", "gov.br", "art.br", "eng.br", "co.uk", "org.uk",
+ "ac.uk", "gov.uk", "me.uk", "com.au", "net.au", "org.au", "edu.au", "co.jp", "ne.jp", "or.jp",
+ "ac.jp", "com.mx", "org.mx", "com.ar", "com.co", "com.pe", "com.cl", "com.ve", "com.uy",
+ "co.za", "co.nz", "co.in", "co.kr", "co.id", "com.sg", "com.hk", "com.tw", "com.my", "com.tr",
+ "com.pt", "com.es", "com.pl", "com.ua", "com.ru", "com.cn", "com.ph",
];
pub fn root_domain_of(host: &str) -> String {
diff --git a/src-tauri/src/core/nfo_sidecar.rs b/src-tauri/src/core/nfo_sidecar.rs
index 20c90ed5..92e44345 100644
--- a/src-tauri/src/core/nfo_sidecar.rs
+++ b/src-tauri/src/core/nfo_sidecar.rs
@@ -20,7 +20,11 @@ pub fn render(info: &MediaInfo, source_url: &str) -> String {
}
if let Some(d) = info.duration_seconds {
if d > 0.0 {
- write_tag(&mut buf, "runtime", &format!("{}", (d / 60.0).round().max(1.0) as i64));
+ write_tag(
+ &mut buf,
+ "runtime",
+ &format!("{}", (d / 60.0).round().max(1.0) as i64),
+ );
}
}
if let Some(thumb) = info.thumbnail_url.as_deref() {
@@ -104,7 +108,9 @@ mod tests {
assert!(xml.contains("<runtime>2</runtime>"));
assert!(xml.contains("<thumb>https://img.example/t.jpg?a=1&amp;b=2</thumb>"));
assert!(xml.contains("<tag>youtube</tag>"));
- assert!(xml.contains("<uniqueid type=\"url\" default=\"true\">https://youtu.be/abc?x=1&amp;y=2</uniqueid>"));
+ assert!(xml.contains(
+ "<uniqueid type=\"url\" default=\"true\">https://youtu.be/abc?x=1&amp;y=2</uniqueid>"
+ ));
assert!(xml.contains("<dateadded>"));
assert!(xml.trim_end().ends_with("</movie>"));
}
diff --git a/src-tauri/src/core/queue.rs b/src-tauri/src/core/queue.rs
index 4355df3d..669124fa 100644
--- a/src-tauri/src/core/queue.rs
+++ b/src-tauri/src/core/queue.rs
@@ -38,10 +38,10 @@ fn shared_http_client() -> &'static reqwest::Client {
use crate::core::ffmpeg::{self, MetadataEmbed};
use crate::models::media::MediaInfo;
-use omniget_core::core::ytdlp::CommandRecord;
-use omniget_core::models::progress::StreamInfo;
use crate::platforms::traits::PlatformDownloader;
use crate::storage::config;
+use omniget_core::core::ytdlp::CommandRecord;
+use omniget_core::models::progress::StreamInfo;
struct CachedInfo {
info: MediaInfo,
@@ -541,7 +541,11 @@ impl DownloadQueue {
.unwrap_or(true);
if changed {
if let Some(prev) = item.current_stream.take() {
- if !item.streams_done.iter().any(|d| d.format_id == prev.format_id) {
+ if !item
+ .streams_done
+ .iter()
+ .any(|d| d.format_id == prev.format_id)
+ {
item.streams_done.push(prev);
}
}
@@ -877,11 +881,16 @@ impl DownloadQueue {
.iter_mut()
.find(|i| i.id == id)
.ok_or_else(|| "Download not found".to_string())?;
- if !matches!(item.status, QueueStatus::Error { .. } | QueueStatus::Complete { .. }) {
+ if !matches!(
+ item.status,
+ QueueStatus::Error { .. } | QueueStatus::Complete { .. }
+ ) {
return Err("Download is still running".to_string());
}
if omniget_core::core::ytdlp::get_command(id).is_none() {
- return Err("This download did not run yt-dlp; there is no command to edit".to_string());
+ return Err(
+ "This download did not run yt-dlp; there is no command to edit".to_string(),
+ );
}
item.status = QueueStatus::Queued;
item.cancel_token = CancellationToken::new();
diff --git a/src-tauri/src/local_bridge.rs b/src-tauri/src/local_bridge.rs
index d0fcaf83..ba78fee2 100644
--- a/src-tauri/src/local_bridge.rs
+++ b/src-tauri/src/local_bridge.rs
@@ -529,7 +529,11 @@ pub fn build_pairing_url(port: u16) -> String {
/// `POST /mcp`: JSON-RPC do MCP. Mesmo bearer da extensão; 403 quando a
/// tool "Servidor MCP" está desligada; 202 sem corpo para notificações.
-async fn mcp_post(State(state): State<BridgeState>, headers: HeaderMap, body: axum::body::Bytes) -> Response {
+async fn mcp_post(
+ State(state): State<BridgeState>,
+ headers: HeaderMap,
+ body: axum::body::Bytes,
+) -> Response {
if !check_bearer(&headers, &state.token) {
return unauthorized();
}
diff --git a/src-tauri/src/mcp.rs b/src-tauri/src/mcp.rs
index c616fc0e..976254aa 100644
--- a/src-tauri/src/mcp.rs
+++ b/src-tauri/src/mcp.rs
@@ -4,7 +4,10 @@
//! que é o que Claude Code, Cursor, Goose e o `mcp-remote` do Claude Desktop
//! aceitam. Sem crate de MCP: o protocolo aqui é JSON-RPC com quatro métodos.
-use omniget_core::core::tools::{self as tools, ai_keys, disk, dupes, edge_tts, file_search, humanize, image_resize, ocr, pdf, pricing, ryd, sponsorblock, startup, sysclean, uninstall, whisper, x};
+use omniget_core::core::tools::{
+ self as tools, ai_keys, disk, dupes, edge_tts, file_search, humanize, image_resize, ocr, pdf,
+ pricing, ryd, sponsorblock, startup, sysclean, uninstall, whisper, x,
+};
use serde::Serialize;
use serde_json::{json, Value};
use tauri::AppHandle;
@@ -24,7 +27,11 @@ fn obj(props: Value, required: &[&str]) -> Value {
}
pub fn tools() -> Vec<ToolDef> {
- let t = |name, description, input_schema| ToolDef { name, description, input_schema };
+ let t = |name, description, input_schema| ToolDef {
+ name,
+ description,
+ input_schema,
+ };
vec![
t("download_url", "Queue a URL (video, audio, playlist, course, image) in the OmniGet Downloads panel. Same as pasting it in the app.", obj(json!({ "url": { "type": "string" } }), &["url"])),
t("youtube_sponsorblock", "SponsorBlock segments (sponsor, intro, outro, selfpromo…) of a YouTube video.", obj(json!({ "url": { "type": "string" }, "categories": { "type": "array", "items": { "type": "string" } } }), &["url"])),
@@ -64,7 +71,14 @@ fn s(v: &Value, k: &str) -> String {
v.get(k).and_then(|x| x.as_str()).unwrap_or("").to_string()
}
fn list(v: &Value, k: &str) -> Vec<String> {
- v.get(k).and_then(|x| x.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect()).unwrap_or_default()
+ v.get(k)
+ .and_then(|x| x.as_array())
+ .map(|a| {
+ a.iter()
+ .filter_map(|x| x.as_str().map(String::from))
+ .collect()
+ })
+ .unwrap_or_default()
}
fn num(v: &Value, k: &str) -> Option<u64> {
v.get(k).and_then(|x| x.as_u64())
@@ -84,55 +98,157 @@ pub async fn call(app: &AppHandle, name: &str, a: Value) -> Result<Value, String
let action = crate::external_url::handle_external_url(app, url.clone(), "mcp").await?;
Ok(json!({ "url": url, "action": format!("{:?}", action).to_lowercase() }))
}
- "youtube_sponsorblock" => to_json(sponsorblock::segments(&s(&a, "url"), &list(&a, "categories")).await.map_err(err)?),
+ "youtube_sponsorblock" => to_json(
+ sponsorblock::segments(&s(&a, "url"), &list(&a, "categories"))
+ .await
+ .map_err(err)?,
+ ),
"youtube_dislikes" => to_json(ryd::votes(&s(&a, "url")).await.map_err(err)?),
"pdf_info" => {
let path = s(&a, "path");
- to_json(tokio::task::spawn_blocking(move || pdf::info(&path, None)).await.map_err(err)?.map_err(err)?)
+ to_json(
+ tokio::task::spawn_blocking(move || pdf::info(&path, None))
+ .await
+ .map_err(err)?
+ .map_err(err)?,
+ )
}
"pdf_merge" => {
- let opts = pdf::MergeOptions { inputs: list(&a, "inputs"), output: s(&a, "output") };
- to_json(tokio::task::spawn_blocking(move || pdf::merge(&opts, &p)).await.map_err(err)?.map_err(err)?)
+ let opts = pdf::MergeOptions {
+ inputs: list(&a, "inputs"),
+ output: s(&a, "output"),
+ };
+ to_json(
+ tokio::task::spawn_blocking(move || pdf::merge(&opts, &p))
+ .await
+ .map_err(err)?
+ .map_err(err)?,
+ )
}
"pdf_split" => {
- let opts = pdf::SplitOptions { input: s(&a, "input"), mode: s(&a, "mode"), every: num(&a, "every").unwrap_or(0) as usize, ranges: s(&a, "ranges"), output_dir: s(&a, "output_dir") };
- to_json(tokio::task::spawn_blocking(move || pdf::split(&opts, &p)).await.map_err(err)?.map_err(err)?)
+ let opts = pdf::SplitOptions {
+ input: s(&a, "input"),
+ mode: s(&a, "mode"),
+ every: num(&a, "every").unwrap_or(0) as usize,
+ ranges: s(&a, "ranges"),
+ output_dir: s(&a, "output_dir"),
+ };
+ to_json(
+ tokio::task::spawn_blocking(move || pdf::split(&opts, &p))
+ .await
+ .map_err(err)?
+ .map_err(err)?,
+ )
}
"pdf_text" => {
let (path, pages) = (s(&a, "path"), s(&a, "pages"));
- to_json(tokio::task::spawn_blocking(move || pdf::to_text(&path, &pages, false, "")).await.map_err(err)?.map_err(err)?)
+ to_json(
+ tokio::task::spawn_blocking(move || pdf::to_text(&path, &pages, false, ""))
+ .await
+ .map_err(err)?
+ .map_err(err)?,
+ )
}
"pdf_render" => {
- let opts = pdf::RenderOptions { input: s(&a, "input"), pages: s(&a, "pages"), dpi: num(&a, "dpi").unwrap_or(0) as u32, format: s(&a, "format"), quality: 0, output_dir: s(&a, "output_dir") };
- to_json(tokio::task::spawn_blocking(move || pdf::render(&opts, &p)).await.map_err(err)?.map_err(err)?)
+ let opts = pdf::RenderOptions {
+ input: s(&a, "input"),
+ pages: s(&a, "pages"),
+ dpi: num(&a, "dpi").unwrap_or(0) as u32,
+ format: s(&a, "format"),
+ quality: 0,
+ output_dir: s(&a, "output_dir"),
+ };
+ to_json(
+ tokio::task::spawn_blocking(move || pdf::render(&opts, &p))
+ .await
+ .map_err(err)?
+ .map_err(err)?,
+ )
}
"pdf_sanitize" => {
let (input, dir) = (s(&a, "input"), s(&a, "output_dir"));
- to_json(tokio::task::spawn_blocking(move || pdf::sanitize(&input, &dir, 0, 0, &p)).await.map_err(err)?.map_err(err)?)
+ to_json(
+ tokio::task::spawn_blocking(move || pdf::sanitize(&input, &dir, 0, 0, &p))
+ .await
+ .map_err(err)?
+ .map_err(err)?,
+ )
}
"tts_speak" => {
- let voice = { let v = s(&a, "voice"); if v.is_empty() { "pt-BR-AntonioNeural".to_string() } else { v } };
- let opts: edge_tts::TtsOptions = serde_json::from_value(json!({ "text": s(&a, "text"), "voice": voice })).map_err(err)?;
- to_json(edge_tts::synthesize(opts, std::path::Path::new(&s(&a, "output")), p).await.map_err(err)?)
+ let voice = {
+ let v = s(&a, "voice");
+ if v.is_empty() {
+ "pt-BR-AntonioNeural".to_string()
+ } else {
+ v
+ }
+ };
+ let opts: edge_tts::TtsOptions =
+ serde_json::from_value(json!({ "text": s(&a, "text"), "voice": voice }))
+ .map_err(err)?;
+ to_json(
+ edge_tts::synthesize(opts, std::path::Path::new(&s(&a, "output")), p)
+ .await
+ .map_err(err)?,
+ )
}
"transcribe" => {
- let model = { let m = s(&a, "model"); if m.is_empty() { "base".to_string() } else { m } };
- let language = { let l = s(&a, "language"); if l.is_empty() { "auto".to_string() } else { l } };
- let opts: whisper::TranscribeOptions = serde_json::from_value(json!({ "input": s(&a, "input"), "model": model, "language": language })).map_err(err)?;
+ let model = {
+ let m = s(&a, "model");
+ if m.is_empty() {
+ "base".to_string()
+ } else {
+ m
+ }
+ };
+ let language = {
+ let l = s(&a, "language");
+ if l.is_empty() {
+ "auto".to_string()
+ } else {
+ l
+ }
+ };
+ let opts: whisper::TranscribeOptions = serde_json::from_value(
+ json!({ "input": s(&a, "input"), "model": model, "language": language }),
+ )
+ .map_err(err)?;
let r = whisper::transcribe(opts, p).await.map_err(err)?;
- Ok(json!({ "language": r.language, "text": r.text, "srt": r.srt_path, "vtt": r.vtt_path, "txt": r.txt_path, "seconds": r.seconds }))
+ Ok(
+ json!({ "language": r.language, "text": r.text, "srt": r.srt_path, "vtt": r.vtt_path, "txt": r.txt_path, "seconds": r.seconds }),
+ )
}
"image_resize" => {
let opts: image_resize::ResizeOptions = serde_json::from_value(json!({ "inputs": list(&a, "inputs"), "mode": s(&a, "mode"), "value": num(&a, "value").unwrap_or(1024), "value2": num(&a, "value2").unwrap_or(0), "format": s(&a, "format"), "output_dir": s(&a, "output_dir") })).map_err(err)?;
to_json(image_resize::run(opts, p).await.map_err(err)?)
}
- "ocr" => to_json(ocr::run(&list(&a, "inputs"), &s(&a, "langs"), p).await.map_err(err)?),
+ "ocr" => to_json(
+ ocr::run(&list(&a, "inputs"), &s(&a, "langs"), p)
+ .await
+ .map_err(err)?,
+ ),
"find_duplicates" => {
let opts: dupes::DupesOptions = serde_json::from_value(json!({ "dirs": list(&a, "dirs"), "min_size": num(&a, "min_size").unwrap_or(1024) })).map_err(err)?;
- to_json(tokio::task::spawn_blocking(move || dupes::scan(&opts, &p)).await.map_err(err)?)
+ to_json(
+ tokio::task::spawn_blocking(move || dupes::scan(&opts, &p))
+ .await
+ .map_err(err)?,
+ )
}
- "file_search" => to_json(file_search::search(&s(&a, "query"), &s(&a, "folder"), num(&a, "limit").unwrap_or(100) as usize).await.map_err(err)?),
- "ai_prices" => to_json(pricing::search(&s(&a, "query"), "", num(&a, "limit").unwrap_or(30) as usize).await.map_err(err)?),
+ "file_search" => to_json(
+ file_search::search(
+ &s(&a, "query"),
+ &s(&a, "folder"),
+ num(&a, "limit").unwrap_or(100) as usize,
+ )
+ .await
+ .map_err(err)?,
+ ),
+ "ai_prices" => to_json(
+ pricing::search(&s(&a, "query"), "", num(&a, "limit").unwrap_or(30) as usize)
+ .await
+ .map_err(err)?,
+ ),
"humanize" => Ok(json!({ "text": humanize::humanize(&s(&a, "text"), None).await? })),
"x_post" => {
let input = s(&a, "url");
@@ -140,18 +256,52 @@ pub async fn call(app: &AppHandle, name: &str, a: Value) -> Result<Value, String
to_json(x::fx::status(&id).await.map_err(err)?)
}
"x_thread" => to_json(x::thread::unroll(&s(&a, "url")).await.map_err(err)?),
- "x_profile" => to_json(x::profile::analyze(&s(&a, "handle"), num(&a, "limit").unwrap_or(100) as usize, false).await.map_err(err)?),
+ "x_profile" => to_json(
+ x::profile::analyze(
+ &s(&a, "handle"),
+ num(&a, "limit").unwrap_or(100) as usize,
+ false,
+ )
+ .await
+ .map_err(err)?,
+ ),
"x_search" => {
- let feed = { let f = s(&a, "feed"); if f.is_empty() { "latest".to_string() } else { f } };
- to_json(x::search::search(&s(&a, "query"), &feed, None).await.map_err(err)?)
+ let feed = {
+ let f = s(&a, "feed");
+ if f.is_empty() {
+ "latest".to_string()
+ } else {
+ f
+ }
+ };
+ to_json(
+ x::search::search(&s(&a, "query"), &feed, None)
+ .await
+ .map_err(err)?,
+ )
}
"x_trends" => to_json(x::search::trends().await.map_err(err)?),
"instagram_profile" => {
- let account = { let v = s(&a, "account"); if v.is_empty() { None } else { Some(v) } };
+ let account = {
+ let v = s(&a, "account");
+ if v.is_empty() {
+ None
+ } else {
+ Some(v)
+ }
+ };
let client = crate::commands::tools::instagram::load_client(account.as_deref())?;
- to_json(tools::instagram::profile::resolve_user(&client, &s(&a, "username")).await.map_err(err)?)
+ to_json(
+ tools::instagram::profile::resolve_user(&client, &s(&a, "username"))
+ .await
+ .map_err(err)?,
+ )
}
- "gallery_download" => to_json(tools::gallery::download(&s(&a, "url"), &s(&a, "dest"), None, p).await.map_err(err)?),
+ "gallery_download" => to_json(
+ tools::gallery::download(&s(&a, "url"), &s(&a, "dest"), None, p)
+ .await
+ .map_err(err)?,
+ ),
"aria2_download" => {
let opts: tools::aria2::Aria2Options = serde_json::from_value(json!({ "url": s(&a, "url"), "dest_dir": s(&a, "dest_dir"), "connections": num(&a, "connections").unwrap_or(16) })).map_err(err)?;
to_json(tools::aria2::download(opts, p).await.map_err(err)?)
@@ -159,9 +309,18 @@ pub async fn call(app: &AppHandle, name: &str, a: Value) -> Result<Value, String
"disk_volumes" => to_json(disk::volumes()),
"disk_scan" => {
let (path, depth) = (s(&a, "path"), num(&a, "depth").unwrap_or(2) as usize);
- to_json(tokio::task::spawn_blocking(move || disk::scan(&path, depth, 25, &p)).await.map_err(err)?.map_err(err)?)
+ to_json(
+ tokio::task::spawn_blocking(move || disk::scan(&path, depth, 25, &p))
+ .await
+ .map_err(err)?
+ .map_err(err)?,
+ )
}
- "clean_scan" => to_json(tokio::task::spawn_blocking(move || sysclean::scan(&p)).await.map_err(err)?),
+ "clean_scan" => to_json(
+ tokio::task::spawn_blocking(move || sysclean::scan(&p))
+ .await
+ .map_err(err)?,
+ ),
"startup_items" => to_json(startup::list().await),
"installed_apps" => to_json(uninstall::list(p).await),
"ai_keys" => to_json(ai_keys::list()),
@@ -186,7 +345,11 @@ pub fn enabled() -> bool {
pub fn set_enabled(on: bool) -> Result<(), String> {
let p = config_file().ok_or("no data dir")?;
std::fs::create_dir_all(p.parent().unwrap()).map_err(err)?;
- std::fs::write(&p, serde_json::to_string_pretty(&json!({ "enabled": on })).unwrap()).map_err(err)
+ std::fs::write(
+ &p,
+ serde_json::to_string_pretty(&json!({ "enabled": on })).unwrap(),
+ )
+ .map_err(err)
}
// ── JSON-RPC ───────────────────────────────────────────────────────────
@@ -210,8 +373,15 @@ pub async fn handle(app: &AppHandle, msg: &Value) -> Option<Value> {
let id = id?;
Some(match method {
"initialize" => {
- let requested = params.get("protocolVersion").and_then(|v| v.as_str()).unwrap_or(PROTOCOL);
- let version = if matches!(requested, "2024-11-05" | "2025-03-26" | "2025-06-18") { requested } else { PROTOCOL };
+ let requested = params
+ .get("protocolVersion")
+ .and_then(|v| v.as_str())
+ .unwrap_or(PROTOCOL);
+ let version = if matches!(requested, "2024-11-05" | "2025-03-26" | "2025-06-18") {
+ requested
+ } else {
+ PROTOCOL
+ };
rpc_ok(
id,
json!({
@@ -229,10 +399,20 @@ pub async fn handle(app: &AppHandle, msg: &Value) -> Option<Value> {
let args = params.get("arguments").cloned().unwrap_or(json!({}));
match call(app, name, args).await {
Ok(v) => {
- let text = if let Some(t) = v.as_str() { t.to_string() } else { serde_json::to_string_pretty(&v).unwrap_or_default() };
- rpc_ok(id, json!({ "content": [{ "type": "text", "text": text }], "structuredContent": v, "isError": false }))
+ let text = if let Some(t) = v.as_str() {
+ t.to_string()
+ } else {
+ serde_json::to_string_pretty(&v).unwrap_or_default()
+ };
+ rpc_ok(
+ id,
+ json!({ "content": [{ "type": "text", "text": text }], "structuredContent": v, "isError": false }),
+ )
}
- Err(e) => rpc_ok(id, json!({ "content": [{ "type": "text", "text": e }], "isError": true })),
+ Err(e) => rpc_ok(
+ id,
+ json!({ "content": [{ "type": "text", "text": e }], "isError": true }),
+ ),
}
}
"resources/list" => rpc_ok(id, json!({ "resources": [] })),
diff --git a/src-tauri/src/plugin_loader.rs b/src-tauri/src/plugin_loader.rs
index ddcd9372..5dcefcfc 100644
--- a/src-tauri/src/plugin_loader.rs
+++ b/src-tauri/src/plugin_loader.rs
@@ -436,7 +436,6 @@ fn load_single_plugin(
})
}
-
fn load_error_hint(detail: &str) -> Option<&'static str> {
if !cfg!(windows) {
return None;