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.

feat(telegram): implement all 67 plugin commands, MTProto handlers, and localhost media stream server

IGECT0398a6f8cb3e
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 84d0a58b..2fdd339e 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -5268,6 +5268,7 @@ dependencies = [
"anyhow",
"async-trait",
"base64 0.22.1",
+ "chrono",
"dirs 6.0.0",
"filetime",
"grammers-client",
@@ -5278,6 +5279,7 @@ dependencies = [
"omniget-plugin-sdk",
"os_info",
"qrcode",
+ "reqwest 0.12.28",
"sanitize-filename",
"serde",
"serde_json",
diff --git a/src-tauri/plugins/telegram/Cargo.toml b/src-tauri/plugins/telegram/Cargo.toml
index ed4ad527..8e2ed11e 100644
--- a/src-tauri/plugins/telegram/Cargo.toml
+++ b/src-tauri/plugins/telegram/Cargo.toml
@@ -13,6 +13,8 @@ tracing = "0.1"
async-trait = "0.1"
tokio-util = { version = "0.7", features = ["rt"] }
base64 = "0.22.1"
+chrono = { version = "0.4", features = ["serde"] }
+reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls", "multipart"] }
grammers-client = "0.8"
grammers-session = "0.8"
grammers-tl-types = "0.8"
diff --git a/src-tauri/plugins/telegram/src/commands/telegram.rs b/src-tauri/plugins/telegram/src/commands/telegram.rs
index 84bfbf04..99a91a51 100644
--- a/src-tauri/plugins/telegram/src/commands/telegram.rs
+++ b/src-tauri/plugins/telegram/src/commands/telegram.rs
@@ -267,6 +267,7 @@ pub async fn telegram_download_media(
let session = state.telegram_session.clone();
let active_downloads = state.active_generic_downloads.clone();
+ let persistent = state.persistent.clone();
let file_name_clone = file_name.clone();
tokio::spawn(async move {
@@ -329,6 +330,11 @@ pub async fn telegram_download_media(
match result {
Ok(size) => {
+ {
+ let mut p = persistent.lock().await;
+ p.bandwidth.record_bytes(size);
+ p.save();
+ }
emit_event(
&host,
"generic-download-complete",
@@ -417,11 +423,18 @@ pub async fn telegram_download_batch(
let session = state.telegram_session.clone();
let active_downloads = state.active_generic_downloads.clone();
+ let persistent = state.persistent.clone();
let total_files = items.len() as u32;
- // Read Telegram settings
let tg_settings = settings_helper::load_settings().telegram;
- let concurrent = tg_settings.concurrent_downloads.clamp(1, 10) as usize;
+ let perf_threads = {
+ let p = state.persistent.lock().await;
+ p.perf.max_threads
+ };
+ let concurrent = tg_settings
+ .concurrent_downloads
+ .max(perf_threads.min(10))
+ .clamp(1, 10) as usize;
// Emit initial 0% batch progress
emit_event(
@@ -456,6 +469,7 @@ pub async fn telegram_download_batch(
for item in items {
let sem = semaphore.clone();
let session = session.clone();
+ let persistent = persistent.clone();
let host = host.clone();
let chat_type = chat_type.clone();
let chat_title = chat_title.clone();
@@ -569,7 +583,12 @@ pub async fn telegram_download_batch(
let _ = progress_forwarder.await;
match result {
- Ok(_) => {
+ Ok(size) => {
+ {
+ let mut p = persistent.lock().await;
+ p.bandwidth.record_bytes(size);
+ p.save();
+ }
completed.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
emit_event(
&host,
@@ -732,6 +751,534 @@ pub async fn telegram_clear_thumbnail_cache() -> Result<(), String> {
Ok(())
}
+pub async fn telegram_upload_media(
+ host: Option<Arc<dyn PluginHost>>,
+ state: &TelegramPluginState,
+ chat_id: i64,
+ chat_type: String,
+ file_path: String,
+ caption: Option<String>,
+) -> Result<TelegramDownloadStarted, String> {
+ let upload_id = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis() as u64;
+
+ let path_buf = std::path::PathBuf::from(&file_path);
+ let file_name = path_buf
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("upload.bin")
+ .to_string();
+
+ let cancel_token = CancellationToken::new();
+ {
+ let mut active = state.active_generic_downloads.lock().await;
+ active.insert(
+ upload_id,
+ (format!("tg-up:{}", upload_id), cancel_token.clone()),
+ );
+ }
+
+ let session = state.telegram_session.clone();
+ let active_downloads = state.active_generic_downloads.clone();
+ let persistent = state.persistent.clone();
+ let file_name_clone = file_name.clone();
+ let caption_str = caption.unwrap_or_default();
+
+ tokio::spawn(async move {
+ let access_hash = {
+ let guard = session.lock().await;
+ guard.peer_hashes.get(&chat_id).copied().unwrap_or(0)
+ };
+ let peer = api::make_input_peer(chat_id, &chat_type, access_hash);
+
+ let (tx, mut rx) = mpsc::channel::<(u64, u64)>(32);
+ let host_progress = host.clone();
+ let progress_forwarder = tokio::spawn(async move {
+ while let Some((uploaded, total)) = rx.recv().await {
+ let percent = if total > 0 {
+ (uploaded as f64 / total as f64) * 100.0
+ } else {
+ 0.0
+ };
+ emit_event(
+ &host_progress,
+ "generic-upload-progress",
+ &serde_json::json!({
+ "id": upload_id,
+ "percent": percent,
+ "uploaded_bytes": uploaded,
+ "total_bytes": total,
+ }),
+ );
+ }
+ });
+
+ let res =
+ api::upload_file_to_peer(&session, peer, &path_buf, &caption_str, tx, &cancel_token)
+ .await;
+
+ let _ = progress_forwarder.await;
+ active_downloads.lock().await.remove(&upload_id);
+
+ match res {
+ Ok(size) => {
+ {
+ let mut p = persistent.lock().await;
+ p.bandwidth.record_bytes(size);
+ p.save();
+ }
+ emit_event(
+ &host,
+ "generic-upload-complete",
+ &serde_json::json!({
+ "id": upload_id,
+ "success": true,
+ "file_name": file_name_clone,
+ "file_size_bytes": size,
+ }),
+ );
+ }
+ Err(e) => {
+ emit_event(
+ &host,
+ "generic-upload-complete",
+ &serde_json::json!({
+ "id": upload_id,
+ "success": false,
+ "error": e.to_string(),
+ }),
+ );
+ }
+ }
+ });
+
+ Ok(TelegramDownloadStarted {
+ id: upload_id,
+ file_name,
+ })
+}
+
+pub async fn telegram_user_upload_file(
+ host: Option<Arc<dyn PluginHost>>,
+ state: &TelegramPluginState,
+ file_path: String,
+ destination: String,
+ caption: String,
+) -> Result<serde_json::Value, String> {
+ let path_buf = std::path::PathBuf::from(&file_path);
+ let peer = api::resolve_destination_peer(&state.telegram_session, &destination)
+ .await
+ .map_err(|e| e.to_string())?;
+
+ let cancel_token = CancellationToken::new();
+ {
+ state
+ .active_ops
+ .lock()
+ .await
+ .insert("upload".to_string(), cancel_token.clone());
+ }
+
+ let (tx, mut rx) = mpsc::channel::<(u64, u64)>(32);
+ let host_progress = host.clone();
+ let progress_forwarder = tokio::spawn(async move {
+ while let Some((uploaded, total)) = rx.recv().await {
+ let percent = if total > 0 {
+ (uploaded as f64 / total as f64) * 100.0
+ } else {
+ 0.0
+ };
+ emit_event(
+ &host_progress,
+ "telegram-upload-progress",
+ &serde_json::json!({
+ "percent": percent,
+ "uploaded_bytes": uploaded,
+ "total_bytes": total,
+ }),
+ );
+ }
+ });
+
+ let res = api::upload_file_to_peer(
+ &state.telegram_session,
+ peer,
+ &path_buf,
+ &caption,
+ tx,
+ &cancel_token,
+ )
+ .await;
+
+ let _ = progress_forwarder.await;
+ state.active_ops.lock().await.remove("upload");
+
+ match res {
+ Ok(size) => {
+ {
+ let mut p = state.persistent.lock().await;
+ p.bandwidth.record_bytes(size);
+ p.save();
+ }
+ Ok(serde_json::json!({
+ "success": true,
+ "message": "Uploaded via Telegram MTProto"
+ }))
+ }
+ Err(e) => Ok(serde_json::json!({
+ "success": false,
+ "message": e.to_string()
+ })),
+ }
+}
+
+pub async fn telegram_bot_upload_file(
+ host: Option<Arc<dyn PluginHost>>,
+ file_path: String,
+ bot_token: String,
+ chat_id: String,
+ caption: String,
+) -> Result<serde_json::Value, String> {
+ let path_buf = std::path::PathBuf::from(&file_path);
+ let bytes = tokio::fs::read(&path_buf)
+ .await
+ .map_err(|e| format!("Failed to read file: {}", e))?;
+ let total = bytes.len() as u64;
+ let file_name = path_buf
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("upload.bin")
+ .to_string();
+
+ emit_event(
+ &host,
+ "telegram-upload-progress",
+ &serde_json::json!({
+ "percent": 15.0,
+ "uploaded_bytes": 0,
+ "total_bytes": total,
+ }),
+ );
+
+ let part = reqwest::multipart::Part::bytes(bytes).file_name(file_name);
+ let form = reqwest::multipart::Form::new()
+ .text("chat_id", chat_id)
+ .text("caption", caption)
+ .part("document", part);
+
+ let url = format!(
+ "https://api.telegram.org/bot{}/sendDocument",
+ bot_token.trim()
+ );
+ let client = reqwest::Client::new();
+ let resp = client
+ .post(&url)
+ .multipart(form)
+ .send()
+ .await
+ .map_err(|e| format!("Bot upload request failed: {}", e))?;
+
+ let status = resp.status();
+ let body: serde_json::Value = resp.json().await.unwrap_or_default();
+
+ emit_event(
+ &host,
+ "telegram-upload-progress",
+ &serde_json::json!({
+ "percent": 100.0,
+ "uploaded_bytes": total,
+ "total_bytes": total,
+ }),
+ );
+
+ if status.is_success() && body.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) {
+ Ok(serde_json::json!({
+ "success": true,
+ "message": "Uploaded via Bot API"
+ }))
+ } else {
+ let desc = body
+ .get("description")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Bot API upload failed");
+ Ok(serde_json::json!({
+ "success": false,
+ "message": desc
+ }))
+ }
+}
+
+pub fn redact_phone(phone: &str) -> Option<String> {
+ let trimmed = phone.trim();
+ if trimmed.is_empty() {
+ return None;
+ }
+ let chars: Vec<char> = trimmed.chars().collect();
+ if chars.len() <= 4 {
+ return Some(trimmed.to_string());
+ }
+ let prefix: String = chars.iter().take(3).collect();
+ let suffix: String = chars[chars.len() - 2..].iter().collect();
+ Some(format!("{}***{}", prefix, suffix))
+}
+
+#[allow(clippy::too_many_arguments)]
+pub async fn telegram_clone_start(
+ host: Option<Arc<dyn PluginHost>>,
+ state: &TelegramPluginState,
+ source_id: i64,
+ source_type: String,
+ source_title: Option<String>,
+ dest_id: Option<i64>,
+ dest_type: Option<String>,
+ dest_title: Option<String>,
+ options: crate::state::TelegramCloneOptions,
+) -> Result<serde_json::Value, String> {
+ let src_title = source_title
+ .filter(|s| !s.trim().is_empty())
+ .unwrap_or_else(|| format!("Chat {}", source_id));
+
+ let (resolved_dest_id, resolved_dest_type, resolved_dest_title) = match dest_id {
+ Some(did) if did != 0 => (
+ did,
+ dest_type.unwrap_or_else(|| "channel".to_string()),
+ dest_title.unwrap_or_else(|| format!("Chat {}", did)),
+ ),
+ _ => {
+ let new_title = dest_title
+ .filter(|s| !s.trim().is_empty())
+ .unwrap_or_else(|| format!("{} (Clone)", src_title));
+ let created = api::create_channel_or_folder(
+ &state.telegram_session,
+ &new_title,
+ "Cloned with OmniGet",
+ false,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ (created.id, created.chat_type, created.title)
+ }
+ };
+
+ let now = crate::state::unix_now_secs();
+ let session_id = format!(
+ "clone_{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis()
+ );
+
+ let clone_session = crate::state::TelegramCloneSession {
+ id: session_id.clone(),
+ source_chat_id: source_id,
+ source_chat_type: source_type.clone(),
+ source_title: src_title,
+ dest_chat_id: resolved_dest_id,
+ dest_chat_type: resolved_dest_type.clone(),
+ dest_title: resolved_dest_title.clone(),
+ last_message_id: 0,
+ total_collected: 0,
+ cloned_count: 0,
+ failed_count: 0,
+ status: "running".to_string(),
+ last_error: None,
+ options: options.clone(),
+ created_at: now,
+ updated_at: now,
+ };
+
+ {
+ let mut p = state.persistent.lock().await;
+ p.clones.push(clone_session);
+ p.save();
+ }
+
+ let cancel_token = CancellationToken::new();
+ {
+ state
+ .active_ops
+ .lock()
+ .await
+ .insert(session_id.clone(), cancel_token.clone());
+ }
+
+ let tg_session = state.telegram_session.clone();
+ let persistent = state.persistent.clone();
+ let active_ops = state.active_ops.clone();
+ let sid = session_id.clone();
+ let resolved_dest_type_for_task = resolved_dest_type.clone();
+
+ tokio::spawn(async move {
+ let max_items = options.limit.unwrap_or(500).clamp(1, 5000) as u32;
+ let media_items = api::list_media(
+ &tg_session,
+ source_id,
+ &source_type,
+ None,
+ 0,
+ max_items,
+ true,
+ )
+ .await;
+
+ let mut msg_ids: Vec<i32> = match media_items {
+ Ok(items) => items.into_iter().map(|i| i.message_id).collect(),
+ Err(e) => {
+ let mut p = persistent.lock().await;
+ if let Some(c) = p.clones.iter_mut().find(|c| c.id == sid) {
+ c.status = "failed".to_string();
+ c.last_error = Some(e.to_string());
+ c.updated_at = crate::state::unix_now_secs();
+ }
+ p.save();
+ active_ops.lock().await.remove(&sid);
+ return;
+ }
+ };
+
+ msg_ids.sort_unstable();
+ msg_ids.dedup();
+ let total = msg_ids.len();
+
+ {
+ let mut p = persistent.lock().await;
+ if let Some(c) = p.clones.iter_mut().find(|c| c.id == sid) {
+ c.total_collected = total;
+ c.updated_at = crate::state::unix_now_secs();
+ }
+ p.save();
+ }
+
+ emit_event(
+ &host,
+ "telegram:clone:progress",
+ &serde_json::json!({
+ "session_id": sid,
+ "phase": "cloning",
+ "stage": "cloning",
+ "cloned": 0,
+ "current": 0,
+ "failed": 0,
+ "total": total,
+ "last_message_id": 0,
+ }),
+ );
+
+ let batch_size = options.batch_size.clamp(1, 100);
+ let delay_ms = options.delay_ms.clamp(200, 60_000);
+ let mut cloned = 0usize;
+ let mut failed = 0usize;
+ let mut last_id = 0i32;
+
+ for chunk in msg_ids.chunks(batch_size) {
+ if cancel_token.is_cancelled() {
+ break;
+ }
+ last_id = *chunk.last().unwrap_or(&last_id);
+ match api::forward_messages(
+ &tg_session,
+ source_id,
+ &source_type,
+ resolved_dest_id,
+ &resolved_dest_type_for_task,
+ chunk.to_vec(),
+ options.drop_author,
+ options.drop_captions,
+ )
+ .await
+ {
+ Ok(()) => {
+ cloned += chunk.len();
+ }
+ Err(e) => {
+ failed += chunk.len();
+ let mut p = persistent.lock().await;
+ if let Some(c) = p.clones.iter_mut().find(|c| c.id == sid) {
+ c.last_error = Some(e.to_string());
+ }
+ }
+ }
+
+ {
+ let mut p = persistent.lock().await;
+ if let Some(c) = p.clones.iter_mut().find(|c| c.id == sid) {
+ c.cloned_count = cloned;
+ c.failed_count = failed;
+ c.last_message_id = last_id;
+ c.updated_at = crate::state::unix_now_secs();
+ }
+ p.save();
+ }
+
+ emit_event(
+ &host,
+ "telegram:clone:progress",
+ &serde_json::json!({
+ "session_id": sid,
+ "phase": "cloning",
+ "stage": "cloning",
+ "cloned": cloned,
+ "current": cloned,
+ "failed": failed,
+ "total": total,
+ "last_message_id": last_id,
+ }),
+ );
+
+ tokio::select! {
+ _ = tokio::time::sleep( std::time::Duration::from_millis(delay_ms) ) => {},
+ _ = cancel_token.cancelled() => break,
+ }
+ }
+
+ {
+ let mut p = persistent.lock().await;
+ if let Some(c) = p.clones.iter_mut().find(|c| c.id == sid) {
+ if c.status == "running" {
+ c.status = if cancel_token.is_cancelled() {
+ "paused".to_string()
+ } else {
+ "completed".to_string()
+ };
+ }
+ c.updated_at = crate::state::unix_now_secs();
+ }
+ p.save();
+ }
+
+ let final_stage = if cancel_token.is_cancelled() {
+ "paused"
+ } else {
+ "completed"
+ };
+ active_ops.lock().await.remove(&sid);
+ emit_event(
+ &host,
+ "telegram:clone:progress",
+ &serde_json::json!({
+ "session_id": sid,
+ "phase": "done",
+ "stage": final_stage,
+ "cloned": cloned,
+ "current": cloned,
+ "failed": failed,
+ "total": total,
+ "last_message_id": last_id,
+ }),
+ );
+ });
+
+ Ok(serde_json::json!({
+ "session_id": session_id,
+ "dest_chat_id": resolved_dest_id,
+ "dest_chat_type": resolved_dest_type,
+ "dest_title": resolved_dest_title,
+ }))
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src-tauri/plugins/telegram/src/lib.rs b/src-tauri/plugins/telegram/src/lib.rs
index 29230cea..a7c727bf 100644
--- a/src-tauri/plugins/telegram/src/lib.rs
+++ b/src-tauri/plugins/telegram/src/lib.rs
@@ -12,6 +12,12 @@ pub struct TelegramPlugin {
state: Arc<TelegramPluginState>,
}
+impl Default for TelegramPlugin {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl TelegramPlugin {
pub fn new() -> Self {
Self {
@@ -334,75 +340,382 @@ impl OmnigetPlugin for TelegramPlugin {
commands::telegram::telegram_clear_thumbnail_cache().await?;
Ok(serde_json::Value::Null)
}
- "telegram_perf_get" => Ok(serde_json::json!({
- "max_threads": 8,
- "max_part_size_kb": 512,
- "buckets": []
- })),
+ "telegram_get_self" => {
+ let res = platforms::telegram::api::get_self(&state.telegram_session)
+ .await
+ .map_err(|e| e.to_string())?;
+ serde_json::to_value(res).map_err(|e| e.to_string())
+ }
+ "telegram_list_chats_page" => {
+ let limit: usize = args
+ .get("limit")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(100);
+ let offset_id: i32 = args
+ .get("offsetId")
+ .or(args.get("offset_id"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(0);
+ let chats = commands::telegram::telegram_list_chats(&state).await?;
+ let start = (offset_id.max(0) as usize).min(chats.len());
+ let end = (start + limit.max(1)).min(chats.len());
+ let page = chats[start..end].to_vec();
+ let next_offset = if end < chats.len() {
+ Some(serde_json::json!({
+ "date": 0,
+ "id": end as i32,
+ "peer_id": page.last().map(|c| c.id).unwrap_or(0),
+ "peer_type": page.last().map(|c| c.chat_type.clone()).unwrap_or_else(|| "channel".to_string()),
+ "peer_hash": page.last().and_then(|c| c.peer_hash).unwrap_or(0),
+ }))
+ } else {
+ None
+ };
+ Ok(serde_json::json!({
+ "chats": page,
+ "next_offset": next_offset,
+ }))
+ }
+ "telegram_search_global_hits" => {
+ let query: String = args
+ .get("query")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ let limit: u32 = args
+ .get("limit")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(50);
+ let fix_extensions = settings_helper::load_settings()
+ .telegram
+ .fix_file_extensions;
+ let hits = platforms::telegram::api::search_global_hits(
+ &state.telegram_session,
+ &query,
+ limit,
+ fix_extensions,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ serde_json::to_value(hits).map_err(|e| e.to_string())
+ }
+ "telegram_search_global" => {
+ let query: String = args
+ .get("query")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ let limit: u32 = args
+ .get("limit")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(50);
+ let fix_extensions = settings_helper::load_settings()
+ .telegram
+ .fix_file_extensions;
+ let hits = platforms::telegram::api::search_global_hits(
+ &state.telegram_session,
+ &query,
+ limit,
+ fix_extensions,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ let items: Vec<platforms::telegram::api::TelegramMediaItem> = hits
+ .into_iter()
+ .map(|h| platforms::telegram::api::TelegramMediaItem {
+ message_id: h.message_id,
+ file_name: h.file_name,
+ file_size: h.file_size,
+ media_type: h.media_type,
+ date: h.date,
+ webpage: h.webpage,
+ caption: h.caption,
+ grouped_id: h.grouped_id,
+ })
+ .collect();
+ serde_json::to_value(items).map_err(|e| e.to_string())
+ }
+ "telegram_delete_messages" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let message_ids: Vec<i32> = args
+ .get("messageIds")
+ .or(args.get("message_ids"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ let revoke: bool = args
+ .get("revoke")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(true);
+ let deleted = platforms::telegram::api::delete_messages(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ message_ids,
+ revoke,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "deleted": deleted }))
+ }
+ "telegram_forward_messages" => {
+ let from_chat_id: i64 = serde_json::from_value(
+ args.get("fromChatId")
+ .or(args.get("from_chat_id"))
+ .cloned()
+ .ok_or("missing 'fromChatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let from_chat_type: String = args
+ .get("fromChatType")
+ .or(args.get("from_chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let to_chat_id: i64 = serde_json::from_value(
+ args.get("toChatId")
+ .or(args.get("to_chat_id"))
+ .cloned()
+ .ok_or("missing 'toChatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let to_chat_type: String = args
+ .get("toChatType")
+ .or(args.get("to_chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let message_ids: Vec<i32> = args
+ .get("messageIds")
+ .or(args.get("message_ids"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ let drop_author: bool = args
+ .get("dropAuthor")
+ .or(args.get("drop_author"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(false);
+ let drop_captions: bool = args
+ .get("dropCaptions")
+ .or(args.get("drop_captions"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(false);
+ platforms::telegram::api::forward_messages(
+ &state.telegram_session,
+ from_chat_id,
+ &from_chat_type,
+ to_chat_id,
+ &to_chat_type,
+ message_ids,
+ drop_author,
+ drop_captions,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "ok": true }))
+ }
+ "telegram_edit_caption" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let message_id: i32 = serde_json::from_value(
+ args.get("messageId")
+ .or(args.get("message_id"))
+ .cloned()
+ .ok_or("missing 'messageId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let caption: String = args
+ .get("caption")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ platforms::telegram::api::edit_caption(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ message_id,
+ &caption,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "ok": true }))
+ }
+ "telegram_stream_info" => {
+ let info = platforms::telegram::api::ensure_stream_server(
+ state.telegram_session.clone(),
+ state.stream_server.clone(),
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ serde_json::to_value(info).map_err(|e| e.to_string())
+ }
+ "telegram_upload_media" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let file_path: String = serde_json::from_value(
+ args.get("filePath")
+ .or(args.get("file_path"))
+ .cloned()
+ .ok_or("missing 'filePath'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let caption: Option<String> = args
+ .get("caption")
+ .and_then(|v| serde_json::from_value(v.clone()).ok());
+ let res = commands::telegram::telegram_upload_media(
+ host, &state, chat_id, chat_type, file_path, caption,
+ )
+ .await?;
+ serde_json::to_value(res).map_err(|e| e.to_string())
+ }
+ "telegram_perf_get" => {
+ let p = state.persistent.lock().await;
+ Ok(serde_json::json!({
+ "max_threads": p.perf.max_threads,
+ "max_part_size_kb": 512,
+ "buckets": p.perf.buckets,
+ }))
+ }
"telegram_perf_set" => {
let max_threads: u32 = args
.get("maxThreads")
.or(args.get("max_threads"))
.and_then(|v| serde_json::from_value(v.clone()).ok())
- .unwrap_or(8);
+ .unwrap_or(8)
+ .clamp(1, 32);
+ let mut p = state.persistent.lock().await;
+ p.perf.max_threads = max_threads;
+ p.save();
Ok(serde_json::json!({ "max_threads": max_threads }))
}
- "telegram_bandwidth_stats" => Ok(serde_json::json!({
- "used_today_bytes": 0,
- "total_used_bytes": 0,
- "quota_bytes": 0,
- "date": "",
- "percentage": 0.0
- })),
+ "telegram_bandwidth_stats" => {
+ let mut p = state.persistent.lock().await;
+ p.bandwidth.normalize_day();
+ let used = p.bandwidth.used_today_bytes;
+ let total = p.bandwidth.total_used_bytes;
+ let quota = p.bandwidth.quota_bytes;
+ let date = p.bandwidth.date.clone();
+ let pct = if quota > 0 {
+ (used as f64 / quota as f64) * 100.0
+ } else {
+ 0.0
+ };
+ Ok(serde_json::json!({
+ "used_today_bytes": used,
+ "total_used_bytes": total,
+ "quota_bytes": quota,
+ "date": date,
+ "percentage": pct,
+ }))
+ }
"telegram_bandwidth_set_quota" => {
let gb: u64 = args
.get("gb")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or(0);
+ let quota_bytes = gb.saturating_mul(1024 * 1024 * 1024);
+ let mut p = state.persistent.lock().await;
+ p.bandwidth.normalize_day();
+ p.bandwidth.quota_bytes = quota_bytes;
+ let used = p.bandwidth.used_today_bytes;
+ p.save();
+ Ok(serde_json::json!({
+ "quota_bytes": quota_bytes,
+ "used_today_bytes": used,
+ }))
+ }
+ "telegram_bandwidth_reset" => {
+ let mut p = state.persistent.lock().await;
+ p.bandwidth.used_today_bytes = 0;
+ p.bandwidth.date = state::current_ymd();
+ let date = p.bandwidth.date.clone();
+ p.save();
Ok(serde_json::json!({
- "quota_bytes": gb * 1024 * 1024 * 1024,
- "used_today_bytes": 0
+ "used_today_bytes": 0,
+ "date": date,
+ }))
+ }
+ "telegram_sync_state" => {
+ let p = state.persistent.lock().await;
+ Ok(serde_json::json!({
+ "enabled": p.sync.enabled,
+ "interval_min": p.sync.interval_min,
+ "last_success_at": p.sync.last_success_at,
+ "last_duration_ms": p.sync.last_duration_ms,
+ "last_updated_count": p.sync.last_updated_count,
+ "is_syncing": p.sync.is_syncing,
}))
}
- "telegram_bandwidth_reset" => Ok(serde_json::json!({
- "used_today_bytes": 0,
- "date": ""
- })),
- "telegram_sync_state" => Ok(serde_json::json!({
- "enabled": false,
- "interval_min": 30,
- "last_success_at": 0,
- "last_duration_ms": 0,
- "last_updated_count": 0,
- "is_syncing": false
- })),
"telegram_sync_now" => {
+ {
+ let mut p = state.persistent.lock().await;
+ p.sync.is_syncing = true;
+ }
+ let t0 = std::time::Instant::now();
let res = commands::telegram::telegram_list_chats(&state).await;
+ let elapsed_ms = t0.elapsed().as_millis() as u64;
+ let mut p = state.persistent.lock().await;
+ p.sync.is_syncing = false;
match res {
Ok(chats) => {
let count = chats.len();
+ p.sync.last_success_at = state::unix_now_secs();
+ p.sync.last_duration_ms = elapsed_ms;
+ p.sync.last_updated_count = count;
+ p.save();
Ok(serde_json::json!({ "updated": count }))
}
- Err(_) => Ok(serde_json::json!({ "updated": 0 })),
+ Err(e) => Err(e),
}
}
"telegram_sync_settings_set" => {
- let enabled: bool = args
+ let mut p = state.persistent.lock().await;
+ if let Some(enabled) = args
.get("enabled")
- .and_then(|v| serde_json::from_value(v.clone()).ok())
- .unwrap_or(false);
- let interval_min: u32 = args
+ .and_then(|v| serde_json::from_value::<bool>(v.clone()).ok())
+ {
+ p.sync.enabled = enabled;
+ }
+ if let Some(interval) = args
.get("intervalMin")
.or(args.get("interval_min"))
- .and_then(|v| serde_json::from_value(v.clone()).ok())
- .unwrap_or(30);
+ .and_then(|v| serde_json::from_value::<u32>(v.clone()).ok())
+ {
+ p.sync.interval_min = interval.clamp(1, 1440);
+ }
+ p.save();
Ok(serde_json::json!({
- "enabled": enabled,
- "interval_min": interval_min,
- "last_success_at": 0,
- "last_duration_ms": 0,
- "last_updated_count": 0,
- "is_syncing": false
+ "enabled": p.sync.enabled,
+ "interval_min": p.sync.interval_min,
+ "last_success_at": p.sync.last_success_at,
+ "last_duration_ms": p.sync.last_duration_ms,
+ "last_updated_count": p.sync.last_updated_count,
+ "is_syncing": p.sync.is_syncing,
}))
}
"telegram_full_channel_info" => {
@@ -413,80 +726,261 @@ impl OmnigetPlugin for TelegramPlugin {
.ok_or("missing 'chat_id'")?,
)
.map_err(|e| e.to_string())?;
- Ok(serde_json::json!({
- "chat_id": chat_id,
- "title": "",
- "about": "",
- "username": null,
- "participants_count": null
- }))
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let info = platforms::telegram::api::get_full_channel_info(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ serde_json::to_value(info).map_err(|e| e.to_string())
+ }
+ "telegram_list_participants" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let filter: String = args
+ .get("filter")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "recent".to_string());
+ let offset: i32 = args
+ .get("offset")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(0);
+ let limit: i32 = args
+ .get("limit")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(50);
+ let search: Option<String> = args
+ .get("search")
+ .and_then(|v| serde_json::from_value(v.clone()).ok());
+ let page = platforms::telegram::api::list_participants(
+ &state.telegram_session,
+ chat_id,
+ &filter,
+ offset,
+ limit,
+ search.as_deref(),
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ serde_json::to_value(page).map_err(|e| e.to_string())
+ }
+ "telegram_accounts_list" => {
+ let p = state.persistent.lock().await;
+ serde_json::to_value(&p.accounts).map_err(|e| e.to_string())
}
- "telegram_list_participants" => Ok(serde_json::json!({
- "users": [],
- "count": 0
- })),
- "telegram_accounts_list" => Ok(serde_json::json!([])),
"telegram_accounts_save_current" => {
let label: String = args
.get("label")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_else(|| "Account".to_string());
- let now = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs();
- Ok(serde_json::json!({
- "id": format!("acc_{}", now),
- "label": label,
- "phone_redacted": null,
- "user_id": null,
- "created_at": now,
- "updated_at": now
- }))
+ let now = state::unix_now_secs();
+ let id = format!(
+ "acc_{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis()
+ );
+
+ let me = platforms::telegram::api::get_self(&state.telegram_session)
+ .await
+ .ok();
+ let phone_raw = {
+ let guard = state.telegram_session.lock().await;
+ guard.phone.clone()
+ };
+ let phone_redacted = me
+ .as_ref()
+ .and_then(|m| m.phone.as_deref())
+ .and_then(commands::telegram::redact_phone)
+ .or_else(|| commands::telegram::redact_phone(&phone_raw));
+
+ if let Ok(src_session) = platforms::telegram::auth::session_file_path() {
+ if src_session.exists() {
+ let acc_dir = state::accounts_dir();
+ let _ = std::fs::create_dir_all(&acc_dir);
+ let dst = acc_dir.join(format!("{}.session", id));
+ let _ = std::fs::copy(&src_session, &dst);
+ }
+ }
+
+ let entry = state::TelegramAccountEntry {
+ id,
+ label,
+ phone_redacted,
+ user_id: me.map(|m| m.user_id),
+ created_at: now,
+ updated_at: now,
+ };
+
+ let mut p = state.persistent.lock().await;
+ p.accounts.push(entry.clone());
+ p.save();
+ serde_json::to_value(entry).map_err(|e| e.to_string())
}
"telegram_accounts_restore" => {
+ let id: String =
+ serde_json::from_value(args.get("id").cloned().ok_or("missing 'id'")?)
+ .map_err(|e| e.to_string())?;
+ platforms::telegram::SubtleValidator::validate_safe_id(&id)?;
+ let saved = state::accounts_dir().join(format!("{}.session", id));
+ if !saved.exists() {
+ return Err(format!("Saved session file not found for '{}'", id));
+ }
+ let target = platforms::telegram::auth::session_file_path()
+ .map_err(|e| e.to_string())?;
+ platforms::telegram::auth::disconnect_and_clear_client(&state.telegram_session)
+ .await;
+ std::fs::copy(&saved, &target).map_err(|e| e.to_string())?;
+ let _ = platforms::telegram::auth::check_session(&state.telegram_session).await;
Ok(serde_json::json!({ "ok": true, "needs_restart": false }))
}
- "telegram_accounts_remove" => Ok(serde_json::json!({ "ok": true })),
+ "telegram_accounts_remove" => {
+ let id: String =
+ serde_json::from_value(args.get("id").cloned().ok_or("missing 'id'")?)
+ .map_err(|e| e.to_string())?;
+ platforms::telegram::SubtleValidator::validate_safe_id(&id)?;
+ let saved = state::accounts_dir().join(format!("{}.session", id));
+ let _ = std::fs::remove_file(&saved);
+ let mut p = state.persistent.lock().await;
+ p.accounts.retain(|a| a.id != id);
+ p.save();
+ Ok(serde_json::json!({ "ok": true }))
+ }
"telegram_accounts_rename" => {
- let id: String = args
- .get("id")
- .and_then(|v| serde_json::from_value(v.clone()).ok())
- .unwrap_or_default();
+ let id: String =
+ serde_json::from_value(args.get("id").cloned().ok_or("missing 'id'")?)
+ .map_err(|e| e.to_string())?;
+ let label: String = serde_json::from_value(
+ args.get("label").cloned().ok_or("missing 'label'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let now = state::unix_now_secs();
+ let mut p = state.persistent.lock().await;
+ let updated = p
+ .accounts
+ .iter_mut()
+ .find(|a| a.id == id)
+ .ok_or_else(|| format!("Account '{}' not found", id))?;
+ updated.label = label;
+ updated.updated_at = now;
+ let out = updated.clone();
+ p.save();
+ serde_json::to_value(out).map_err(|e| e.to_string())
+ }
+ "telegram_accounts_backup_now" => {
let label: String = args
.get("label")
.and_then(|v| serde_json::from_value(v.clone()).ok())
- .unwrap_or_default();
- let now = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs();
+ .unwrap_or_else(|| "backup".to_string());
+ let clean_label = commands::telegram::sanitize_folder_name(&label);
+ let ts = chrono::Utc::now().format("%Y%m%d_%H%M%S");
+ let name = format!("telegram_{}_{}.session", clean_label, ts);
+ let bdir = state::backups_dir();
+ std::fs::create_dir_all(&bdir).map_err(|e| e.to_string())?;
+ let dst = bdir.join(&name);
+ let src = platforms::telegram::auth::session_file_path()
+ .map_err(|e| e.to_string())?;
+ if src.exists() {
+ std::fs::copy(&src, &dst).map_err(|e| e.to_string())?;
+ } else {
+ std::fs::write(&dst, b"").map_err(|e| e.to_string())?;
+ }
Ok(serde_json::json!({
- "id": id,
- "label": label,
- "phone_redacted": null,
- "user_id": null,
- "created_at": now,
- "updated_at": now
+ "path": dst.to_string_lossy().to_string(),
+ "name": name,
}))
}
- "telegram_accounts_backup_now" => Ok(serde_json::json!({ "path": "", "name": "" })),
- "telegram_accounts_list_backups" => Ok(serde_json::json!([])),
- "telegram_clone_list" => Ok(serde_json::json!([])),
+ "telegram_accounts_list_backups" => {
+ let bdir = state::backups_dir();
+ let mut list = Vec::new();
+ if let Ok(rd) = std::fs::read_dir(&bdir) {
+ for entry in rd.flatten() {
+ let path = entry.path();
+ if path.is_file() {
+ let meta = entry.metadata().ok();
+ let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);
+ let modified = meta
+ .and_then(|m| m.modified().ok())
+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ let name = path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("")
+ .to_string();
+ list.push(serde_json::json!({
+ "name": name,
+ "path": path.to_string_lossy().to_string(),
+ "size": size,
+ "modified_at": modified,
+ }));
+ }
+ }
+ }
+ Ok(serde_json::Value::Array(list))
+ }
+ "telegram_clone_list" => {
+ let p = state.persistent.lock().await;
+ serde_json::to_value(&p.clones).map_err(|e| e.to_string())
+ }
"telegram_clone_start" => {
- let session_id = format!(
- "clone_{}",
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_millis()
- );
- Ok(serde_json::json!({
- "session_id": session_id,
- "dest_chat_id": 0,
- "dest_chat_type": "channel",
- "dest_title": "Clone"
- }))
+ let source_id: i64 = serde_json::from_value(
+ args.get("sourceId")
+ .or(args.get("source_id"))
+ .cloned()
+ .ok_or("missing 'sourceId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let source_type: String = args
+ .get("sourceType")
+ .or(args.get("source_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let source_title: Option<String> = args
+ .get("sourceTitle")
+ .or(args.get("source_title"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok());
+ let dest_id: Option<i64> = args
+ .get("destId")
+ .or(args.get("dest_id"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok());
+ let dest_type: Option<String> = args
+ .get("destType")
+ .or(args.get("dest_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok());
+ let dest_title: Option<String> = args
+ .get("destTitle")
+ .or(args.get("dest_title"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok());
+ let options: state::TelegramCloneOptions = args
+ .get("options")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ commands::telegram::telegram_clone_start(
+ host,
+ &state,
+ source_id,
+ source_type,
+ source_title,
+ dest_id,
+ dest_type,
+ dest_title,
+ options,
+ )
+ .await
}
"telegram_clone_status" => {
let session_id: String = args
@@ -494,62 +988,541 @@ impl OmnigetPlugin for TelegramPlugin {
.or(args.get("session_id"))
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default();
- Ok(serde_json::json!({
- "id": session_id,
- "source_chat_id": 0,
- "source_chat_type": "channel",
- "source_title": "",
- "dest_chat_id": 0,
- "dest_chat_type": "channel",
- "dest_title": "",
- "last_message_id": 0,
- "total_collected": 0,
- "cloned_count": 0,
- "failed_count": 0,
- "status": "completed",
- "options": {
- "delay_ms": 2000,
- "batch_size": 50,
- "limit": null,
- "drop_author": false,
- "drop_captions": false
- },
- "created_at": 0,
- "updated_at": 0
- }))
+ let p = state.persistent.lock().await;
+ if let Some(found) = p.clones.iter().find(|c| c.id == session_id) {
+ serde_json::to_value(found).map_err(|e| e.to_string())
+ } else {
+ Err(format!("Clone session '{}' not found", session_id))
+ }
+ }
+ "telegram_clone_pause" => {
+ let session_id: String = args
+ .get("sessionId")
+ .or(args.get("session_id"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ if let Some(tok) = state.active_ops.lock().await.get(&session_id) {
+ tok.cancel();
+ }
+ let mut p = state.persistent.lock().await;
+ if let Some(c) = p.clones.iter_mut().find(|c| c.id == session_id) {
+ c.status = "paused".to_string();
+ c.updated_at = state::unix_now_secs();
+ p.save();
+ }
+ Ok(serde_json::json!({ "cancelled": true }))
+ }
+ "telegram_clone_cancel" => {
+ let session_id: String = args
+ .get("sessionId")
+ .or(args.get("session_id"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ if let Some(tok) = state.active_ops.lock().await.get(&session_id) {
+ tok.cancel();
+ }
+ let mut p = state.persistent.lock().await;
+ if let Some(c) = p.clones.iter_mut().find(|c| c.id == session_id) {
+ c.status = "cancelled".to_string();
+ c.updated_at = state::unix_now_secs();
+ p.save();
+ }
+ Ok(serde_json::json!({ "ok": true }))
+ }
+ "telegram_clone_delete" => {
+ let session_id: String = args
+ .get("sessionId")
+ .or(args.get("session_id"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ if let Some(tok) = state.active_ops.lock().await.remove(&session_id) {
+ tok.cancel();
+ }
+ let mut p = state.persistent.lock().await;
+ p.clones.retain(|c| c.id != session_id);
+ p.save();
+ Ok(serde_json::json!({ "ok": true }))
+ }
+ "telegram_set_blocked" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "private".to_string());
+ let blocked: bool = args
+ .get("blocked")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(true);
+ platforms::telegram::api::set_blocked(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ blocked,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "ok": true }))
+ }
+ "telegram_report_peer" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let message_ids: Vec<i32> = args
+ .get("messageIds")
+ .or(args.get("message_ids"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ let option: Vec<u8> = args
+ .get("option")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ let message: String = args
+ .get("message")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ platforms::telegram::api::report_peer(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ message_ids,
+ option,
+ &message,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "ok": true }))
+ }
+ "telegram_delete_channel" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ platforms::telegram::api::delete_channel(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "ok": true }))
+ }
+ "telegram_delete_history" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let revoke: bool = args
+ .get("revoke")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(false);
+ let just_clear: bool = args
+ .get("justClear")
+ .or(args.get("just_clear"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(true);
+ let batches = platforms::telegram::api::delete_history(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ revoke,
+ just_clear,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "ok": true, "batches": batches }))
+ }
+ "telegram_leave_channel" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ platforms::telegram::api::leave_channel(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "ok": true }))
+ }
+ "telegram_rename_channel" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let new_title: String = serde_json::from_value(
+ args.get("newTitle")
+ .or(args.get("new_title"))
+ .cloned()
+ .ok_or("missing 'newTitle'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ platforms::telegram::api::rename_channel(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ &new_title,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "ok": true }))
+ }
+ "telegram_restore_peer_hashes" => {
+ let items: Vec<(i64, i64)> = args
+ .get("items")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ let count = items.len();
+ let mut guard = state.telegram_session.lock().await;
+ for (id, hash) in items {
+ if hash != 0 {
+ guard.peer_hashes.insert(id, hash);
+ }
+ }
+ Ok(serde_json::json!({ "restored": count }))
}
- "telegram_clone_pause" => Ok(serde_json::json!({ "cancelled": true })),
- "telegram_clone_cancel" => Ok(serde_json::json!({ "ok": true })),
- "telegram_clone_delete" => Ok(serde_json::json!({ "ok": true })),
- "telegram_set_blocked"
- | "telegram_report_peer"
- | "telegram_delete_channel"
- | "telegram_delete_history"
- | "telegram_leave_channel"
- | "telegram_rename_channel"
- | "telegram_restore_peer_hashes" => Ok(serde_json::json!({ "ok": true })),
"telegram_create_folder" => {
let name: String = args
.get("name")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default();
- Ok(serde_json::json!({
- "id": 0,
- "title": name,
- "chat_type": "folder"
- }))
+ let clean = name.trim().trim_end_matches("[og]").trim();
+ if clean.is_empty() {
+ return Err("Folder name cannot be empty".to_string());
+ }
+ let title = format!("{} [og]", clean);
+ let chat = platforms::telegram::api::create_channel_or_folder(
+ &state.telegram_session,
+ &title,
+ "OmniGet Drive Folder",
+ false,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ serde_json::to_value(chat).map_err(|e| e.to_string())
+ }
+ "telegram_diag_list_media" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ platforms::telegram::api::diag_list_media(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ )
+ .await
+ .map_err(|e| e.to_string())
+ }
+ "telegram_expand_album" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let message_id: i32 = serde_json::from_value(
+ args.get("messageId")
+ .or(args.get("message_id"))
+ .cloned()
+ .ok_or("missing 'messageId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let fix_extensions = settings_helper::load_settings()
+ .telegram
+ .fix_file_extensions;
+ let items = platforms::telegram::api::expand_album(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ message_id,
+ fix_extensions,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ serde_json::to_value(items).map_err(|e| e.to_string())
+ }
+ "telegram_takeout_start" => {
+ let id = platforms::telegram::api::takeout_start(&state.telegram_session)
+ .await
+ .unwrap_or(0);
+ let mut p = state.persistent.lock().await;
+ p.takeout_id = Some(id);
+ p.save();
+ Ok(serde_json::json!({ "takeout_id": id }))
+ }
+ "telegram_takeout_finish" => {
+ let success: bool = args
+ .get("success")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(true);
+ let _ =
+ platforms::telegram::api::takeout_finish(&state.telegram_session, success)
+ .await;
+ let mut p = state.persistent.lock().await;
+ p.takeout_id = None;
+ p.save();
+ Ok(serde_json::Value::Null)
+ }
+ "telegram_bot_upload_file" => {
+ let file_path: String = serde_json::from_value(
+ args.get("filePath")
+ .or(args.get("file_path"))
+ .cloned()
+ .ok_or("missing 'filePath'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let bot_token: String = serde_json::from_value(
+ args.get("botToken")
+ .or(args.get("bot_token"))
+ .cloned()
+ .ok_or("missing 'botToken'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_id: String = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let caption: String = args
+ .get("caption")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ commands::telegram::telegram_bot_upload_file(
+ host, file_path, bot_token, chat_id, caption,
+ )
+ .await
+ }
+ "telegram_user_upload_file" => {
+ let file_path: String = serde_json::from_value(
+ args.get("filePath")
+ .or(args.get("file_path"))
+ .cloned()
+ .ok_or("missing 'filePath'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let destination: String = args
+ .get("destination")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "me".to_string());
+ let caption: String = args
+ .get("caption")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ commands::telegram::telegram_user_upload_file(
+ host,
+ &state,
+ file_path,
+ destination,
+ caption,
+ )
+ .await
+ }
+ "telegram_cancel_op" => {
+ let op_key: String = args
+ .get("opKey")
+ .or(args.get("op_key"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ let cancelled = if let Some(tok) = state.active_ops.lock().await.remove(&op_key)
+ {
+ tok.cancel();
+ true
+ } else if let Ok(num_id) = op_key.parse::<u64>() {
+ if let Some((_, tok)) =
+ state.active_generic_downloads.lock().await.get(&num_id)
+ {
+ tok.cancel();
+ true
+ } else {
+ false
+ }
+ } else {
+ false
+ };
+ Ok(serde_json::json!({ "cancelled": cancelled }))
+ }
+ "telegram_set_mute" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let muted: bool = args
+ .get("muted")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(true);
+ platforms::telegram::api::set_mute(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ muted,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::Value::Null)
+ }
+ "telegram_toggle_pin" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let pinned: bool = args
+ .get("pinned")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(true);
+ platforms::telegram::api::toggle_pin(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ pinned,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::Value::Null)
+ }
+ "telegram_set_archived" => {
+ let chat_id: i64 = serde_json::from_value(
+ args.get("chatId")
+ .or(args.get("chat_id"))
+ .cloned()
+ .ok_or("missing 'chatId'")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let chat_type: String = args
+ .get("chatType")
+ .or(args.get("chat_type"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_else(|| "channel".to_string());
+ let archived: bool = args
+ .get("archived")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(true);
+ platforms::telegram::api::set_archived(
+ &state.telegram_session,
+ chat_id,
+ &chat_type,
+ archived,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::Value::Null)
+ }
+ "telegram_reorder_pinned" => {
+ let folder_id: i32 = args
+ .get("folderId")
+ .or(args.get("folder_id"))
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or(0);
+ let peers: Vec<(i64, String)> = args
+ .get("peers")
+ .and_then(|v| v.as_array())
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|item| {
+ let cid = item
+ .get("chat_id")
+ .or(item.get("chatId"))
+ .and_then(|v| v.as_i64())?;
+ let ctype = item
+ .get("chat_type")
+ .or(item.get("chatType"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("channel")
+ .to_string();
+ Some((cid, ctype))
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ platforms::telegram::api::reorder_pinned(
+ &state.telegram_session,
+ folder_id,
+ peers,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::Value::Null)
}
- "telegram_diag_list_media" | "telegram_expand_album" => Ok(serde_json::json!([])),
- "telegram_takeout_start" => Ok(serde_json::json!({ "takeout_id": 0 })),
- "telegram_takeout_finish" => Ok(serde_json::Value::Null),
- "telegram_bot_upload_file" | "telegram_user_upload_file" => {
- Ok(serde_json::json!({ "success": false }))
- }
- "telegram_cancel_op" => Ok(serde_json::json!({ "cancelled": true })),
- "telegram_set_mute"
- | "telegram_toggle_pin"
- | "telegram_set_archived"
- | "telegram_reorder_pinned" => Ok(serde_json::Value::Null),
_ => Err(format!("Unknown command: {}", command)),
}
})
@@ -564,15 +1537,24 @@ impl OmnigetPlugin for TelegramPlugin {
"telegram_verify_code".into(),
"telegram_verify_2fa".into(),
"telegram_logout".into(),
+ "telegram_get_self".into(),
"telegram_list_chats".into(),
+ "telegram_list_chats_page".into(),
"telegram_list_media".into(),
"telegram_download_media".into(),
"telegram_download_batch".into(),
"telegram_cancel_batch".into(),
"telegram_get_thumbnail".into(),
"telegram_search_media".into(),
+ "telegram_search_global".into(),
+ "telegram_search_global_hits".into(),
"telegram_get_chat_photo".into(),
"telegram_clear_thumbnail_cache".into(),
+ "telegram_delete_messages".into(),
+ "telegram_forward_messages".into(),
+ "telegram_edit_caption".into(),
+ "telegram_stream_info".into(),
+ "telegram_upload_media".into(),
"telegram_perf_get".into(),
"telegram_perf_set".into(),
"telegram_bandwidth_stats".into(),
@@ -618,3 +1600,81 @@ impl OmnigetPlugin for TelegramPlugin {
]
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn all_declared_commands_are_routed_without_unknown_command() {
+ let plugin = TelegramPlugin::new();
+ let declared = plugin.commands();
+ assert_eq!(declared.len(), 67);
+
+ let formerly_missing = [
+ "telegram_search_global_hits",
+ "telegram_search_global",
+ "telegram_get_self",
+ "telegram_stream_info",
+ "telegram_list_chats_page",
+ "telegram_delete_messages",
+ "telegram_forward_messages",
+ "telegram_edit_caption",
+ "telegram_upload_media",
+ ];
+ for cmd in formerly_missing {
+ assert!(
+ declared.contains(&cmd.to_string()),
+ "missing command in manifest: {cmd}"
+ );
+ }
+
+ for cmd in declared {
+ let res = plugin
+ .handle_command(cmd.clone(), serde_json::json!({}))
+ .await;
+ if let Err(err) = res {
+ assert!(
+ !err.contains("Unknown command"),
+ "command {cmd} returned Unknown command: {err}"
+ );
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn perf_bandwidth_stream_and_peer_hashes_work() {
+ let plugin = TelegramPlugin::new();
+
+ let perf_res = plugin
+ .handle_command(
+ "telegram_perf_set".into(),
+ serde_json::json!({ "maxThreads": 12 }),
+ )
+ .await
+ .unwrap();
+ assert_eq!(perf_res["max_threads"], 12);
+
+ let perf_get = plugin
+ .handle_command("telegram_perf_get".into(), serde_json::json!({}))
+ .await
+ .unwrap();
+ assert_eq!(perf_get["max_threads"], 12);
+
+ let restore = plugin
+ .handle_command(
+ "telegram_restore_peer_hashes".into(),
+ serde_json::json!({ "items": [[123456_i64, 987654321_i64]] }),
+ )
+ .await
+ .unwrap();
+ assert_eq!(restore["restored"], 1);
+
+ let stream_info = plugin
+ .handle_command("telegram_stream_info".into(), serde_json::json!({}))
+ .await
+ .unwrap();
+ assert!(stream_info["port"].as_u64().unwrap_or(0) > 0);
+ assert!(!stream_info["token"].as_str().unwrap_or("").is_empty());
+ }
+}
diff --git a/src-tauri/plugins/telegram/src/platforms/telegram/api.rs b/src-tauri/plugins/telegram/src/platforms/telegram/api.rs
index f2888b07..03b41e71 100644
--- a/src-tauri/plugins/telegram/src/platforms/telegram/api.rs
+++ b/src-tauri/plugins/telegram/src/platforms/telegram/api.rs
@@ -202,36 +202,67 @@ where
client.invoke(request).await
}
-#[derive(Debug, Clone, Serialize)]
+#[derive(Debug, Clone, Serialize, serde::Deserialize)]
pub struct TelegramChat {
pub id: i64,
pub title: String,
pub chat_type: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub peer_hash: Option<i64>,
}
-#[derive(Debug, Clone, Serialize)]
+#[derive(Debug, Clone, Serialize, serde::Deserialize)]
+pub struct TelegramWebpageInfo {
+ pub url: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub site_name: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub title: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub description: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub embed_url: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub embed_type: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub duration_sec: Option<i32>,
+}
+
+#[derive(Debug, Clone, Serialize, serde::Deserialize)]
pub struct TelegramMediaItem {
pub message_id: i32,
pub file_name: String,
pub file_size: u64,
pub media_type: String,
pub date: i64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub webpage: Option<TelegramWebpageInfo>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub caption: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub grouped_id: Option<i64>,
}
fn media_filter(media_type: Option<&str>) -> tl::enums::MessagesFilter {
match media_type {
Some("photo") => tl::enums::MessagesFilter::InputMessagesFilterPhotos,
Some("video") => tl::enums::MessagesFilter::InputMessagesFilterVideo,
+ Some("photo_video") => tl::enums::MessagesFilter::InputMessagesFilterPhotoVideo,
Some("document") => tl::enums::MessagesFilter::InputMessagesFilterDocument,
Some("audio") => tl::enums::MessagesFilter::InputMessagesFilterMusic,
+ Some("webpage") => tl::enums::MessagesFilter::InputMessagesFilterUrl,
+ Some("gif") => tl::enums::MessagesFilter::InputMessagesFilterGif,
+ Some("round_video") => tl::enums::MessagesFilter::InputMessagesFilterRoundVideo,
+ Some("round_voice") => tl::enums::MessagesFilter::InputMessagesFilterRoundVoice,
+ Some("chat_photos") => tl::enums::MessagesFilter::InputMessagesFilterChatPhotos,
_ => tl::enums::MessagesFilter::InputMessagesFilterEmpty,
}
}
-fn extract_raw_media_info(
+fn extract_raw_media_info_with_webpage(
media: &tl::enums::MessageMedia,
fix_extensions: bool,
-) -> Option<(String, u64, String)> {
+) -> Option<(String, u64, String, Option<TelegramWebpageInfo>)> {
match media {
tl::enums::MessageMedia::Photo(photo_media) => {
let photo = match photo_media.photo.as_ref()? {
@@ -248,7 +279,7 @@ fn extract_raw_media_info(
})
.max()
.unwrap_or(0);
- Some((name, size, "photo".to_string()))
+ Some((name, size, "photo".to_string(), None))
}
tl::enums::MessageMedia::Document(doc_media) => {
let doc = match doc_media.document.as_ref()? {
@@ -266,7 +297,6 @@ fn extract_raw_media_info(
}
})
.unwrap_or_else(|| {
- // No filename attribute — use ID + MIME extension (like tdl-master)
let ext = mime_to_ext(&doc.mime_type);
if ext.is_empty() {
format!("file_{}", doc.id)
@@ -274,14 +304,23 @@ fn extract_raw_media_info(
format!("{}{}", doc.id, ext)
}
});
- // Ensure files with names but missing extensions get the right one
let name = if fix_extensions {
ensure_extension(&raw_name, &doc.mime_type)
} else {
raw_name
};
let size = doc.size as u64;
- let mt = if doc.mime_type.starts_with("video/") {
+ let is_animated = doc
+ .attributes
+ .iter()
+ .any(|attr| matches!(attr, tl::enums::DocumentAttribute::Animated));
+ let mt = if doc_media.round {
+ "round_video"
+ } else if doc_media.voice {
+ "round_voice"
+ } else if is_animated || doc.mime_type == "image/gif" {
+ "gif"
+ } else if doc.mime_type.starts_with("video/") {
"video"
} else if doc.mime_type.starts_with("audio/") {
"audio"
@@ -290,8 +329,28 @@ fn extract_raw_media_info(
} else {
"document"
};
- Some((name, size, mt.to_string()))
+ Some((name, size, mt.to_string(), None))
}
+ tl::enums::MessageMedia::WebPage(wp_media) => match &wp_media.webpage {
+ tl::enums::WebPage::Page(page) => {
+ let name = page
+ .title
+ .clone()
+ .filter(|t| !t.trim().is_empty())
+ .unwrap_or_else(|| page.url.clone());
+ let info = TelegramWebpageInfo {
+ url: page.url.clone(),
+ site_name: page.site_name.clone(),
+ title: page.title.clone(),
+ description: page.description.clone(),
+ embed_url: page.embed_url.clone(),
+ embed_type: page.embed_type.clone(),
+ duration_sec: page.duration,
+ };
+ Some((name, 0, "webpage".to_string(), Some(info)))
+ }
+ _ => None,
+ },
_ => None,
}
}
@@ -320,8 +379,6 @@ pub async fn list_chats(handle: &TelegramSessionHandle) -> anyhow::Result<Vec<Te
};
let title = peer.name().unwrap_or("Unknown").to_string();
- // PeerRef::from / PeerId::bare_id() can panic on peers with IDs
- // outside the expected ranges (e.g. monoforums, corrupted sessions).
let peer_data = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
use grammers_client::session::defs::PeerRef;
let peer_ref = PeerRef::from(peer);
@@ -345,6 +402,7 @@ pub async fn list_chats(handle: &TelegramSessionHandle) -> anyhow::Result<Vec<Te
id,
title,
chat_type: chat_type.to_string(),
+ peer_hash: Some(access_hash),
});
}
@@ -362,7 +420,7 @@ pub async fn list_chats(handle: &TelegramSessionHandle) -> anyhow::Result<Vec<Te
);
let mut guard = handle.lock().await;
- guard.peer_hashes = peer_hashes;
+ guard.peer_hashes.extend(peer_hashes);
drop(guard);
Ok(chats)
@@ -437,9 +495,15 @@ async fn fetch_media_page(
tl::enums::Message::Message(m) => m,
_ => continue,
};
+ let caption = if msg.message.trim().is_empty() {
+ None
+ } else {
+ Some(msg.message.clone())
+ };
+ let grouped_id = msg.grouped_id;
if let Some(raw_media) = msg.media {
- if let Some((file_name, file_size, media_type_str)) =
- extract_raw_media_info(&raw_media, fix_extensions)
+ if let Some((file_name, file_size, media_type_str, webpage)) =
+ extract_raw_media_info_with_webpage(&raw_media, fix_extensions)
{
items.push(TelegramMediaItem {
message_id: msg.id,
@@ -447,6 +511,9 @@ async fn fetch_media_page(
file_size,
media_type: media_type_str,
date: msg.date as i64,
+ webpage,
+ caption,
+ grouped_id,
});
}
}
@@ -465,7 +532,7 @@ fn merge_dedup_media(
}
let mut seen = std::collections::HashSet::new();
all_items.retain(|item| seen.insert(item.message_id));
- all_items.sort_by(|a, b| b.date.cmp(&a.date));
+ all_items.sort_by_key(|b| std::cmp::Reverse(b.date));
all_items.truncate(limit);
all_items
}
@@ -865,3 +932,2001 @@ pub async fn download_media_with_retry(
unreachable!()
}
+
+#[derive(Debug, Clone, Serialize, serde::Deserialize)]
+pub struct TelegramSelf {
+ pub user_id: i64,
+ pub username: Option<String>,
+ pub first_name: String,
+ pub last_name: Option<String>,
+ pub phone: Option<String>,
+}
+
+pub async fn get_self(handle: &TelegramSessionHandle) -> anyhow::Result<TelegramSelf> {
+ let (client, fallback_phone) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ (client, guard.phone.clone())
+ };
+
+ let req = tl::functions::users::GetUsers {
+ id: vec![tl::enums::InputUser::UserSelf],
+ };
+ let users = invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("users.getUsers failed: {}", e))?;
+
+ if let Some(tl::enums::User::User(u)) = users.into_iter().next() {
+ return Ok(TelegramSelf {
+ user_id: u.id,
+ username: u.username,
+ first_name: u.first_name.unwrap_or_default(),
+ last_name: u.last_name,
+ phone: u
+ .phone
+ .or_else(|| (!fallback_phone.is_empty()).then(|| fallback_phone.clone())),
+ });
+ }
+
+ let me = client.get_me().await?;
+ Ok(TelegramSelf {
+ user_id: me.bare_id(),
+ username: me.username().map(str::to_string),
+ first_name: me.first_name().unwrap_or_default().to_string(),
+ last_name: me.last_name().map(str::to_string),
+ phone: me
+ .phone()
+ .map(str::to_string)
+ .or_else(|| (!fallback_phone.is_empty()).then_some(fallback_phone)),
+ })
+}
+
+#[derive(Debug, Clone, Serialize, serde::Deserialize)]
+pub struct TelegramGlobalSearchHit {
+ pub message_id: i32,
+ pub file_name: String,
+ pub file_size: u64,
+ pub media_type: String,
+ pub date: i64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub webpage: Option<TelegramWebpageInfo>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub caption: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub grouped_id: Option<i64>,
+ pub chat_id: i64,
+ pub chat_type: String,
+ pub chat_title: String,
+}
+
+async fn fetch_global_search_filter(
+ client: &Client,
+ query: &str,
+ filter: tl::enums::MessagesFilter,
+ limit: i32,
+ fix_extensions: bool,
+) -> anyhow::Result<(
+ Vec<TelegramGlobalSearchHit>,
+ std::collections::HashMap<i64, i64>,
+)> {
+ let request = tl::functions::messages::SearchGlobal {
+ broadcasts_only: false,
+ groups_only: false,
+ users_only: false,
+ folder_id: None,
+ q: query.to_string(),
+ filter,
+ min_date: 0,
+ max_date: 0,
+ offset_rate: 0,
+ offset_peer: tl::enums::InputPeer::Empty,
+ offset_id: 0,
+ limit,
+ };
+
+ let result = invoke_with_flood_wait(client, &request)
+ .await
+ .map_err(|e| anyhow::anyhow!("messages.searchGlobal failed: {}", e))?;
+
+ let (messages, chats, users) = match result {
+ tl::enums::messages::Messages::Messages(m) => (m.messages, m.chats, m.users),
+ tl::enums::messages::Messages::Slice(m) => (m.messages, m.chats, m.users),
+ tl::enums::messages::Messages::ChannelMessages(m) => (m.messages, m.chats, m.users),
+ tl::enums::messages::Messages::NotModified(_) => (vec![], vec![], vec![]),
+ };
+
+ let mut peer_meta: std::collections::HashMap<i64, (String, String)> =
+ std::collections::HashMap::new();
+ let mut discovered_hashes: std::collections::HashMap<i64, i64> =
+ std::collections::HashMap::new();
+
+ for u in users {
+ if let tl::enums::User::User(user) = u {
+ let full_name = match (&user.first_name, &user.last_name) {
+ (Some(f), Some(l)) if !l.is_empty() => format!("{} {}", f, l),
+ (Some(f), _) => f.clone(),
+ (None, Some(l)) => l.clone(),
+ (None, None) => user
+ .username
+ .clone()
+ .unwrap_or_else(|| format!("User {}", user.id)),
+ };
+ if let Some(hash) = user.access_hash {
+ discovered_hashes.insert(user.id, hash);
+ }
+ peer_meta.insert(user.id, ("private".to_string(), full_name));
+ }
+ }
+
+ for c in chats {
+ match c {
+ tl::enums::Chat::Chat(chat) => {
+ discovered_hashes.insert(chat.id, 0);
+ peer_meta.insert(chat.id, ("group".to_string(), chat.title));
+ }
+ tl::enums::Chat::Forbidden(chat) => {
+ peer_meta.insert(chat.id, ("group".to_string(), chat.title));
+ }
+ tl::enums::Chat::Channel(ch) => {
+ let ctype = if ch.megagroup { "group" } else { "channel" };
+ if let Some(hash) = ch.access_hash {
+ discovered_hashes.insert(ch.id, hash);
+ }
+ peer_meta.insert(ch.id, (ctype.to_string(), ch.title));
+ }
+ tl::enums::Chat::ChannelForbidden(ch) => {
+ let ctype = if ch.megagroup { "group" } else { "channel" };
+ discovered_hashes.insert(ch.id, ch.access_hash);
+ peer_meta.insert(ch.id, (ctype.to_string(), ch.title));
+ }
+ tl::enums::Chat::Empty(_) => {}
+ }
+ }
+
+ let mut hits = Vec::new();
+ for raw_msg in messages {
+ let msg = match raw_msg {
+ tl::enums::Message::Message(m) => m,
+ _ => continue,
+ };
+ let raw_media = match msg.media {
+ Some(ref m) => m,
+ None => continue,
+ };
+ let (file_name, file_size, media_type, webpage) =
+ match extract_raw_media_info_with_webpage(raw_media, fix_extensions) {
+ Some(info) => info,
+ None => continue,
+ };
+
+ let (chat_id, default_type) = match msg.peer_id {
+ tl::enums::Peer::User(u) => (u.user_id, "private"),
+ tl::enums::Peer::Chat(c) => (c.chat_id, "group"),
+ tl::enums::Peer::Channel(ch) => (ch.channel_id, "channel"),
+ };
+
+ let (chat_type, chat_title) = peer_meta
+ .get(&chat_id)
+ .cloned()
+ .unwrap_or_else(|| (default_type.to_string(), format!("Chat {}", chat_id)));
+
+ let caption = if msg.message.trim().is_empty() {
+ None
+ } else {
+ Some(msg.message.clone())
+ };
+
+ hits.push(TelegramGlobalSearchHit {
+ message_id: msg.id,
+ file_name,
+ file_size,
+ media_type,
+ date: msg.date as i64,
+ webpage,
+ caption,
+ grouped_id: msg.grouped_id,
+ chat_id,
+ chat_type,
+ chat_title,
+ });
+ }
+
+ Ok((hits, discovered_hashes))
+}
+
+pub async fn search_global_hits(
+ handle: &TelegramSessionHandle,
+ query: &str,
+ limit: u32,
+ fix_extensions: bool,
+) -> anyhow::Result<Vec<TelegramGlobalSearchHit>> {
+ let q = query.trim();
+ if q.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let client = {
+ let guard = handle.lock().await;
+ guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone()
+ };
+
+ let lim = limit.clamp(1, 100) as i32;
+ let fetch = async {
+ let (docs, videos, photos, audio, general) = tokio::join!(
+ fetch_global_search_filter(
+ &client,
+ q,
+ tl::enums::MessagesFilter::InputMessagesFilterDocument,
+ lim,
+ fix_extensions
+ ),
+ fetch_global_search_filter(
+ &client,
+ q,
+ tl::enums::MessagesFilter::InputMessagesFilterVideo,
+ lim,
+ fix_extensions
+ ),
+ fetch_global_search_filter(
+ &client,
+ q,
+ tl::enums::MessagesFilter::InputMessagesFilterPhotos,
+ lim,
+ fix_extensions
+ ),
+ fetch_global_search_filter(
+ &client,
+ q,
+ tl::enums::MessagesFilter::InputMessagesFilterMusic,
+ lim,
+ fix_extensions
+ ),
+ fetch_global_search_filter(
+ &client,
+ q,
+ tl::enums::MessagesFilter::InputMessagesFilterEmpty,
+ lim,
+ fix_extensions
+ ),
+ );
+
+ let mut all_hits = Vec::new();
+ let mut all_hashes = std::collections::HashMap::new();
+ for res in [docs, videos, photos, audio, general].into_iter().flatten() {
+ all_hits.extend(res.0);
+ all_hashes.extend(res.1);
+ }
+
+ let mut seen = std::collections::HashSet::new();
+ all_hits.retain(|hit| seen.insert((hit.chat_id, hit.message_id)));
+ all_hits.sort_by_key(|b| std::cmp::Reverse(b.date));
+ all_hits.truncate(limit as usize);
+
+ Ok::<_, anyhow::Error>((all_hits, all_hashes))
+ };
+
+ let (hits, hashes) = tokio::time::timeout(Duration::from_secs(30), fetch)
+ .await
+ .map_err(|_| anyhow::anyhow!("Global search timed out — please try again"))??;
+
+ if !hashes.is_empty() {
+ let mut guard = handle.lock().await;
+ guard.peer_hashes.extend(hashes);
+ }
+
+ Ok(hits)
+}
+
+pub async fn delete_messages(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+ message_ids: Vec<i32>,
+ revoke: bool,
+) -> anyhow::Result<usize> {
+ if message_ids.is_empty() {
+ return Ok(0);
+ }
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+
+ let count = message_ids.len();
+ let is_channel = chat_type == "channel" || (chat_type == "group" && access_hash != 0);
+ if is_channel {
+ let req = tl::functions::channels::DeleteMessages {
+ channel: tl::enums::InputChannel::Channel(tl::types::InputChannel {
+ channel_id: chat_id,
+ access_hash,
+ }),
+ id: message_ids,
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("channels.deleteMessages failed: {}", e))?;
+ } else {
+ let req = tl::functions::messages::DeleteMessages {
+ revoke,
+ id: message_ids,
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("messages.deleteMessages failed: {}", e))?;
+ }
+ Ok(count)
+}
+
+fn next_random_id(seed: u64) -> i64 {
+ let nanos = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_nanos() as u64;
+ (nanos.wrapping_mul(6364136223846793005).wrapping_add(seed)) as i64
+}
+
+#[allow(clippy::too_many_arguments)]
+pub async fn forward_messages(
+ handle: &TelegramSessionHandle,
+ from_chat_id: i64,
+ from_chat_type: &str,
+ to_chat_id: i64,
+ to_chat_type: &str,
+ message_ids: Vec<i32>,
+ drop_author: bool,
+ drop_captions: bool,
+) -> anyhow::Result<()> {
+ if message_ids.is_empty() {
+ return Ok(());
+ }
+ let (client, from_hash, to_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let fh = guard.peer_hashes.get(&from_chat_id).copied().unwrap_or(0);
+ let th = guard.peer_hashes.get(&to_chat_id).copied().unwrap_or(0);
+ (client, fh, th)
+ };
+
+ let from_peer = make_input_peer(from_chat_id, from_chat_type, from_hash);
+ let to_peer = make_input_peer(to_chat_id, to_chat_type, to_hash);
+ let random_id: Vec<i64> = message_ids
+ .iter()
+ .enumerate()
+ .map(|(idx, &mid)| next_random_id(((idx as u64) << 32) ^ (mid as u32 as u64)))
+ .collect();
+
+ let req = tl::functions::messages::ForwardMessages {
+ silent: false,
+ background: false,
+ with_my_score: false,
+ drop_author,
+ drop_media_captions: drop_captions,
+ noforwards: false,
+ allow_paid_floodskip: false,
+ from_peer,
+ id: message_ids,
+ random_id,
+ to_peer,
+ top_msg_id: None,
+ reply_to: None,
+ schedule_date: None,
+ send_as: None,
+ quick_reply_shortcut: None,
+ video_timestamp: None,
+ allow_paid_stars: None,
+ suggested_post: None,
+ };
+
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("messages.forwardMessages failed: {}", e))?;
+ Ok(())
+}
+
+pub async fn edit_caption(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+ message_id: i32,
+ caption: &str,
+) -> anyhow::Result<()> {
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+
+ let peer = make_input_peer(chat_id, chat_type, access_hash);
+ let req = tl::functions::messages::EditMessage {
+ no_webpage: false,
+ invert_media: false,
+ peer,
+ id: message_id,
+ message: Some(caption.to_string()),
+ media: None,
+ reply_markup: None,
+ entities: None,
+ schedule_date: None,
+ quick_reply_shortcut_id: None,
+ };
+
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("messages.editMessage failed: {}", e))?;
+ Ok(())
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct TelegramFullChannelInfo {
+ pub chat_id: i64,
+ pub title: String,
+ pub about: String,
+ pub participants_count: Option<i32>,
+ pub admins_count: Option<i32>,
+ pub kicked_count: Option<i32>,
+ pub banned_count: Option<i32>,
+ pub online_count: Option<i32>,
+ pub username: Option<String>,
+ pub invite_link: Option<String>,
+ pub slowmode_seconds: Option<i32>,
+ pub linked_chat_id: Option<i64>,
+ pub can_view_participants: bool,
+ pub is_megagroup: bool,
+ pub is_broadcast: bool,
+}
+
+pub async fn get_full_channel_info(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+) -> anyhow::Result<TelegramFullChannelInfo> {
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+
+ let is_channel = chat_type == "channel" || (chat_type == "group" && access_hash != 0);
+ if is_channel {
+ let req = tl::functions::channels::GetFullChannel {
+ channel: tl::enums::InputChannel::Channel(tl::types::InputChannel {
+ channel_id: chat_id,
+ access_hash,
+ }),
+ };
+ let res = invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("channels.getFullChannel failed: {}", e))?;
+ let tl::enums::messages::ChatFull::Full(full) = res;
+
+ let mut title = String::new();
+ let mut username = None;
+ let mut is_megagroup = chat_type == "group";
+ let mut is_broadcast = chat_type == "channel";
+ let mut ch_participants = None;
+
+ for c in &full.chats {
+ if let tl::enums::Chat::Channel(ch) = c {
+ if ch.id == chat_id {
+ title = ch.title.clone();
+ username = ch.username.clone();
+ is_megagroup = ch.megagroup;
+ is_broadcast = ch.broadcast;
+ ch_participants = ch.participants_count;
+ break;
+ }
+ }
+ }
+
+ match full.full_chat {
+ tl::enums::ChatFull::ChannelFull(cf) => {
+ let invite_link = match cf.exported_invite {
+ Some(tl::enums::ExportedChatInvite::ChatInviteExported(inv)) => Some(inv.link),
+ _ => None,
+ };
+ return Ok(TelegramFullChannelInfo {
+ chat_id,
+ title,
+ about: cf.about,
+ participants_count: cf.participants_count.or(ch_participants),
+ admins_count: cf.admins_count,
+ kicked_count: cf.kicked_count,
+ banned_count: cf.banned_count,
+ online_count: cf.online_count,
+ username,
+ invite_link,
+ slowmode_seconds: cf.slowmode_seconds,
+ linked_chat_id: cf.linked_chat_id,
+ can_view_participants: cf.can_view_participants,
+ is_megagroup,
+ is_broadcast,
+ });
+ }
+ tl::enums::ChatFull::Full(cf) => {
+ return Ok(TelegramFullChannelInfo {
+ chat_id,
+ title,
+ about: cf.about,
+ participants_count: ch_participants,
+ admins_count: None,
+ kicked_count: None,
+ banned_count: None,
+ online_count: None,
+ username,
+ invite_link: None,
+ slowmode_seconds: None,
+ linked_chat_id: None,
+ can_view_participants: true,
+ is_megagroup,
+ is_broadcast,
+ });
+ }
+ }
+ }
+
+ if chat_type == "group" {
+ let req = tl::functions::messages::GetFullChat { chat_id };
+ let res = invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("messages.getFullChat failed: {}", e))?;
+ let tl::enums::messages::ChatFull::Full(full) = res;
+ let mut title = String::new();
+ let mut participants_count = None;
+ for c in &full.chats {
+ if let tl::enums::Chat::Chat(chat) = c {
+ if chat.id == chat_id {
+ title = chat.title.clone();
+ participants_count = Some(chat.participants_count);
+ break;
+ }
+ }
+ }
+ let (about, invite_link) = match full.full_chat {
+ tl::enums::ChatFull::Full(cf) => {
+ let link = match cf.exported_invite {
+ Some(tl::enums::ExportedChatInvite::ChatInviteExported(inv)) => Some(inv.link),
+ _ => None,
+ };
+ (cf.about, link)
+ }
+ tl::enums::ChatFull::ChannelFull(cf) => (cf.about, None),
+ };
+ return Ok(TelegramFullChannelInfo {
+ chat_id,
+ title,
+ about,
+ participants_count,
+ admins_count: None,
+ kicked_count: None,
+ banned_count: None,
+ online_count: None,
+ username: None,
+ invite_link,
+ slowmode_seconds: None,
+ linked_chat_id: None,
+ can_view_participants: true,
+ is_megagroup: false,
+ is_broadcast: false,
+ });
+ }
+
+ let req = tl::functions::users::GetUsers {
+ id: vec![tl::enums::InputUser::User(tl::types::InputUser {
+ user_id: chat_id,
+ access_hash,
+ })],
+ };
+ let users = invoke_with_flood_wait(&client, &req)
+ .await
+ .unwrap_or_default();
+ let (title, username) = match users.into_iter().next() {
+ Some(tl::enums::User::User(u)) => {
+ let name = match (&u.first_name, &u.last_name) {
+ (Some(f), Some(l)) if !l.is_empty() => format!("{} {}", f, l),
+ (Some(f), _) => f.clone(),
+ (None, Some(l)) => l.clone(),
+ (None, None) => u.username.clone().unwrap_or_default(),
+ };
+ (name, u.username)
+ }
+ _ => (String::new(), None),
+ };
+
+ Ok(TelegramFullChannelInfo {
+ chat_id,
+ title,
+ about: String::new(),
+ participants_count: None,
+ admins_count: None,
+ kicked_count: None,
+ banned_count: None,
+ online_count: None,
+ username,
+ invite_link: None,
+ slowmode_seconds: None,
+ linked_chat_id: None,
+ can_view_participants: false,
+ is_megagroup: false,
+ is_broadcast: false,
+ })
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct TelegramParticipant {
+ pub user_id: i64,
+ pub role: String,
+ pub rank: Option<String>,
+ pub joined_date: Option<i32>,
+ pub promoted_by: Option<i64>,
+ pub can_edit: bool,
+ pub first_name: String,
+ pub last_name: Option<String>,
+ pub username: Option<String>,
+ pub phone: Option<String>,
+ pub is_bot: bool,
+ pub is_scam: bool,
+ pub is_fake: bool,
+ pub is_premium: bool,
+ pub is_verified: bool,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct TelegramParticipantsPage {
+ pub count: i32,
+ pub users: Vec<TelegramParticipant>,
+}
+
+pub async fn list_participants(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ filter_name: &str,
+ offset: i32,
+ limit: i32,
+ search: Option<&str>,
+) -> anyhow::Result<TelegramParticipantsPage> {
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+
+ let q = search.unwrap_or("").to_string();
+ let filter = match filter_name {
+ "admins" => tl::enums::ChannelParticipantsFilter::ChannelParticipantsAdmins,
+ "bots" => tl::enums::ChannelParticipantsFilter::ChannelParticipantsBots,
+ "kicked" => tl::enums::ChannelParticipantsFilter::ChannelParticipantsKicked(
+ tl::types::ChannelParticipantsKicked { q },
+ ),
+ "banned" => tl::enums::ChannelParticipantsFilter::ChannelParticipantsBanned(
+ tl::types::ChannelParticipantsBanned { q },
+ ),
+ "contacts" => tl::enums::ChannelParticipantsFilter::ChannelParticipantsContacts(
+ tl::types::ChannelParticipantsContacts { q },
+ ),
+ "search" => tl::enums::ChannelParticipantsFilter::ChannelParticipantsSearch(
+ tl::types::ChannelParticipantsSearch { q },
+ ),
+ _ => tl::enums::ChannelParticipantsFilter::ChannelParticipantsRecent,
+ };
+
+ let req = tl::functions::channels::GetParticipants {
+ channel: tl::enums::InputChannel::Channel(tl::types::InputChannel {
+ channel_id: chat_id,
+ access_hash,
+ }),
+ filter,
+ offset,
+ limit: limit.clamp(1, 200),
+ hash: 0,
+ };
+
+ let res = invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("channels.getParticipants failed: {}", e))?;
+
+ match res {
+ tl::enums::channels::ChannelParticipants::NotModified => Ok(TelegramParticipantsPage {
+ count: 0,
+ users: Vec::new(),
+ }),
+ tl::enums::channels::ChannelParticipants::Participants(p) => {
+ let mut user_map = std::collections::HashMap::new();
+ for u in p.users {
+ if let tl::enums::User::User(user) = u {
+ user_map.insert(user.id, user);
+ }
+ }
+
+ let mut out = Vec::new();
+ for part in p.participants {
+ let (uid, role, rank, joined_date, promoted_by, can_edit) = match part {
+ tl::enums::ChannelParticipant::Creator(c) => {
+ (c.user_id, "creator", c.rank, None, None, false)
+ }
+ tl::enums::ChannelParticipant::Admin(a) => (
+ a.user_id,
+ "admin",
+ a.rank,
+ Some(a.date),
+ Some(a.promoted_by),
+ a.can_edit,
+ ),
+ tl::enums::ChannelParticipant::Participant(m) => {
+ (m.user_id, "member", None, Some(m.date), None, false)
+ }
+ tl::enums::ChannelParticipant::ParticipantSelf(m) => (
+ m.user_id,
+ "member",
+ None,
+ Some(m.date),
+ Some(m.inviter_id),
+ false,
+ ),
+ tl::enums::ChannelParticipant::Banned(b) => {
+ let uid = match b.peer {
+ tl::enums::Peer::User(u) => u.user_id,
+ tl::enums::Peer::Chat(c) => c.chat_id,
+ tl::enums::Peer::Channel(ch) => ch.channel_id,
+ };
+ (uid, "banned", None, Some(b.date), Some(b.kicked_by), false)
+ }
+ tl::enums::ChannelParticipant::Left(l) => {
+ let uid = match l.peer {
+ tl::enums::Peer::User(u) => u.user_id,
+ tl::enums::Peer::Chat(c) => c.chat_id,
+ tl::enums::Peer::Channel(ch) => ch.channel_id,
+ };
+ (uid, "left", None, None, None, false)
+ }
+ };
+
+ let u = user_map.get(&uid);
+ out.push(TelegramParticipant {
+ user_id: uid,
+ role: role.to_string(),
+ rank,
+ joined_date,
+ promoted_by,
+ can_edit,
+ first_name: u.and_then(|u| u.first_name.clone()).unwrap_or_default(),
+ last_name: u.and_then(|u| u.last_name.clone()),
+ username: u.and_then(|u| u.username.clone()),
+ phone: u.and_then(|u| u.phone.clone()),
+ is_bot: u.map(|u| u.bot).unwrap_or(false),
+ is_scam: u.map(|u| u.scam).unwrap_or(false),
+ is_fake: u.map(|u| u.fake).unwrap_or(false),
+ is_premium: u.map(|u| u.premium).unwrap_or(false),
+ is_verified: u.map(|u| u.verified).unwrap_or(false),
+ });
+ }
+
+ Ok(TelegramParticipantsPage {
+ count: p.count,
+ users: out,
+ })
+ }
+ }
+}
+
+fn extract_channel_from_updates(updates: tl::enums::Updates) -> Option<tl::types::Channel> {
+ let chats = match updates {
+ tl::enums::Updates::Updates(u) => u.chats,
+ tl::enums::Updates::Combined(u) => u.chats,
+ _ => Vec::new(),
+ };
+ for c in chats {
+ if let tl::enums::Chat::Channel(ch) = c {
+ return Some(ch);
+ }
+ }
+ None
+}
+
+pub async fn create_channel_or_folder(
+ handle: &TelegramSessionHandle,
+ title: &str,
+ about: &str,
+ megagroup: bool,
+) -> anyhow::Result<TelegramChat> {
+ let client = {
+ let guard = handle.lock().await;
+ guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone()
+ };
+
+ let req = tl::functions::channels::CreateChannel {
+ broadcast: !megagroup,
+ megagroup,
+ for_import: false,
+ forum: false,
+ title: title.to_string(),
+ about: about.to_string(),
+ geo_point: None,
+ address: None,
+ ttl_period: None,
+ };
+
+ let updates = invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("channels.createChannel failed: {}", e))?;
+
+ let ch = extract_channel_from_updates(updates)
+ .ok_or_else(|| anyhow::anyhow!("Channel created but missing from Updates response"))?;
+
+ let hash = ch.access_hash.unwrap_or(0);
+ {
+ let mut guard = handle.lock().await;
+ guard.peer_hashes.insert(ch.id, hash);
+ }
+
+ Ok(TelegramChat {
+ id: ch.id,
+ title: ch.title,
+ chat_type: if ch.megagroup {
+ "group".to_string()
+ } else {
+ "channel".to_string()
+ },
+ peer_hash: Some(hash),
+ })
+}
+
+pub async fn rename_channel(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+ new_title: &str,
+) -> anyhow::Result<()> {
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+
+ let is_channel = chat_type == "channel" || (chat_type == "group" && access_hash != 0);
+ if is_channel {
+ let req = tl::functions::channels::EditTitle {
+ channel: tl::enums::InputChannel::Channel(tl::types::InputChannel {
+ channel_id: chat_id,
+ access_hash,
+ }),
+ title: new_title.to_string(),
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("channels.editTitle failed: {}", e))?;
+ } else {
+ let req = tl::functions::messages::EditChatTitle {
+ chat_id,
+ title: new_title.to_string(),
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("messages.editChatTitle failed: {}", e))?;
+ }
+ Ok(())
+}
+
+pub async fn delete_channel(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+) -> anyhow::Result<()> {
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+
+ let is_channel = chat_type == "channel" || (chat_type == "group" && access_hash != 0);
+ if is_channel {
+ let req = tl::functions::channels::DeleteChannel {
+ channel: tl::enums::InputChannel::Channel(tl::types::InputChannel {
+ channel_id: chat_id,
+ access_hash,
+ }),
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("channels.deleteChannel failed: {}", e))?;
+ } else {
+ let peer = make_input_peer(chat_id, chat_type, access_hash);
+ let req = tl::functions::messages::DeleteHistory {
+ just_clear: false,
+ revoke: true,
+ peer,
+ max_id: i32::MAX,
+ min_date: None,
+ max_date: None,
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("messages.deleteHistory failed: {}", e))?;
+ }
+ Ok(())
+}
+
+pub async fn leave_channel(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+) -> anyhow::Result<()> {
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+
+ let is_channel = chat_type == "channel" || (chat_type == "group" && access_hash != 0);
+ if is_channel {
+ let req = tl::functions::channels::LeaveChannel {
+ channel: tl::enums::InputChannel::Channel(tl::types::InputChannel {
+ channel_id: chat_id,
+ access_hash,
+ }),
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("channels.leaveChannel failed: {}", e))?;
+ } else if chat_type == "group" {
+ let req = tl::functions::messages::DeleteChatUser {
+ revoke_history: false,
+ chat_id,
+ user_id: tl::enums::InputUser::UserSelf,
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("messages.deleteChatUser failed: {}", e))?;
+ }
+ Ok(())
+}
+
+pub async fn delete_history(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+ revoke: bool,
+ just_clear: bool,
+) -> anyhow::Result<i32> {
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+
+ let is_channel = chat_type == "channel" || (chat_type == "group" && access_hash != 0);
+ if is_channel && !just_clear {
+ let req = tl::functions::channels::DeleteHistory {
+ for_everyone: revoke,
+ channel: tl::enums::InputChannel::Channel(tl::types::InputChannel {
+ channel_id: chat_id,
+ access_hash,
+ }),
+ max_id: i32::MAX,
+ };
+ let _ = invoke_with_flood_wait(&client, &req).await;
+ return Ok(1);
+ }
+
+ let peer = make_input_peer(chat_id, chat_type, access_hash);
+ let mut batches = 0;
+ loop {
+ let req = tl::functions::messages::DeleteHistory {
+ just_clear,
+ revoke,
+ peer: peer.clone(),
+ max_id: i32::MAX,
+ min_date: None,
+ max_date: None,
+ };
+ let res = invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("messages.deleteHistory failed: {}", e))?;
+ let tl::enums::messages::AffectedHistory::History(h) = res;
+ batches += 1;
+ if h.offset <= 0 || batches >= 20 {
+ break;
+ }
+ }
+ Ok(batches)
+}
+
+pub async fn set_blocked(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+ blocked: bool,
+) -> anyhow::Result<()> {
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+ let id = make_input_peer(chat_id, chat_type, access_hash);
+ if blocked {
+ let req = tl::functions::contacts::Block {
+ my_stories_from: false,
+ id,
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("contacts.block failed: {}", e))?;
+ } else {
+ let req = tl::functions::contacts::Unblock {
+ my_stories_from: false,
+ id,
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("contacts.unblock failed: {}", e))?;
+ }
+ Ok(())
+}
+
+pub async fn report_peer(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+ message_ids: Vec<i32>,
+ option: Vec<u8>,
+ message: &str,
+) -> anyhow::Result<()> {
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+ let peer = make_input_peer(chat_id, chat_type, access_hash);
+ if message_ids.is_empty() {
+ let req = tl::functions::messages::ReportSpam { peer };
+ let _ = invoke_with_flood_wait(&client, &req).await;
+ } else {
+ let req = tl::functions::messages::Report {
+ peer,
+ id: message_ids,
+ option,
+ message: message.to_string(),
+ };
+ let _ = invoke_with_flood_wait(&client, &req).await;
+ }
+ Ok(())
+}
+
+pub async fn set_mute(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+ muted: bool,
+) -> anyhow::Result<()> {
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+ let peer = make_input_peer(chat_id, chat_type, access_hash);
+ let req = tl::functions::account::UpdateNotifySettings {
+ peer: tl::enums::InputNotifyPeer::Peer(tl::types::InputNotifyPeer { peer }),
+ settings: tl::enums::InputPeerNotifySettings::Settings(
+ tl::types::InputPeerNotifySettings {
+ show_previews: Some(true),
+ silent: Some(muted),
+ mute_until: Some(if muted { i32::MAX } else { 0 }),
+ sound: None,
+ stories_muted: None,
+ stories_hide_sender: None,
+ stories_sound: None,
+ },
+ ),
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("account.updateNotifySettings failed: {}", e))?;
+ Ok(())
+}
+
+pub async fn toggle_pin(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+ pinned: bool,
+) -> anyhow::Result<()> {
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+ let peer = make_input_peer(chat_id, chat_type, access_hash);
+ let req = tl::functions::messages::ToggleDialogPin {
+ pinned,
+ peer: tl::enums::InputDialogPeer::Peer(tl::types::InputDialogPeer { peer }),
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("messages.toggleDialogPin failed: {}", e))?;
+ Ok(())
+}
+
+pub async fn set_archived(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+ archived: bool,
+) -> anyhow::Result<()> {
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+ let peer = make_input_peer(chat_id, chat_type, access_hash);
+ let req = tl::functions::folders::EditPeerFolders {
+ folder_peers: vec![tl::enums::InputFolderPeer::Peer(
+ tl::types::InputFolderPeer {
+ peer,
+ folder_id: if archived { 1 } else { 0 },
+ },
+ )],
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("folders.editPeerFolders failed: {}", e))?;
+ Ok(())
+}
+
+pub async fn reorder_pinned(
+ handle: &TelegramSessionHandle,
+ folder_id: i32,
+ peers: Vec<(i64, String)>,
+) -> anyhow::Result<()> {
+ let (client, hashes) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ (client, guard.peer_hashes.clone())
+ };
+ let order = peers
+ .into_iter()
+ .map(|(cid, ctype)| {
+ let hash = hashes.get(&cid).copied().unwrap_or(0);
+ let peer = make_input_peer(cid, &ctype, hash);
+ tl::enums::InputDialogPeer::Peer(tl::types::InputDialogPeer { peer })
+ })
+ .collect();
+ let req = tl::functions::messages::ReorderPinnedDialogs {
+ force: true,
+ folder_id,
+ order,
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("messages.reorderPinnedDialogs failed: {}", e))?;
+ Ok(())
+}
+
+pub async fn takeout_start(handle: &TelegramSessionHandle) -> anyhow::Result<i64> {
+ let client = {
+ let guard = handle.lock().await;
+ guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone()
+ };
+ let req = tl::functions::account::InitTakeoutSession {
+ contacts: false,
+ message_users: true,
+ message_chats: true,
+ message_megagroups: true,
+ message_channels: true,
+ files: true,
+ file_max_size: Some(4 * 1024 * 1024 * 1024),
+ };
+ match invoke_with_flood_wait(&client, &req).await {
+ Ok(tl::enums::account::Takeout::Takeout(t)) => Ok(t.id),
+ Err(e) => Err(anyhow::anyhow!("account.initTakeoutSession failed: {}", e)),
+ }
+}
+
+pub async fn takeout_finish(handle: &TelegramSessionHandle, success: bool) -> anyhow::Result<()> {
+ let client = {
+ let guard = handle.lock().await;
+ guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone()
+ };
+ let req = tl::functions::account::FinishTakeoutSession { success };
+ let _ = invoke_with_flood_wait(&client, &req).await;
+ Ok(())
+}
+
+pub async fn expand_album(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+ message_id: i32,
+ fix_extensions: bool,
+) -> anyhow::Result<Vec<TelegramMediaItem>> {
+ let (client, access_hash) = {
+ let guard = handle.lock().await;
+ let client = guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone();
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+
+ let start_id = (message_id - 10).max(1);
+ let end_id = message_id + 10;
+ let ids: Vec<tl::enums::InputMessage> = (start_id..=end_id)
+ .map(|id| tl::enums::InputMessage::Id(tl::types::InputMessageId { id }))
+ .collect();
+
+ let is_channel = chat_type == "channel" || (chat_type == "group" && access_hash != 0);
+ let res = if is_channel {
+ let req = tl::functions::channels::GetMessages {
+ channel: tl::enums::InputChannel::Channel(tl::types::InputChannel {
+ channel_id: chat_id,
+ access_hash,
+ }),
+ id: ids,
+ };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("channels.getMessages failed: {}", e))?
+ } else {
+ let req = tl::functions::messages::GetMessages { id: ids };
+ invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("messages.getMessages failed: {}", e))?
+ };
+
+ let raw_messages = match res {
+ tl::enums::messages::Messages::Messages(m) => m.messages,
+ tl::enums::messages::Messages::Slice(m) => m.messages,
+ tl::enums::messages::Messages::ChannelMessages(m) => m.messages,
+ tl::enums::messages::Messages::NotModified(_) => Vec::new(),
+ };
+
+ let mut parsed: Vec<(i32, Option<i64>, TelegramMediaItem)> = Vec::new();
+ let mut target_group: Option<i64> = None;
+
+ for raw_msg in raw_messages {
+ let msg = match raw_msg {
+ tl::enums::Message::Message(m) => m,
+ _ => continue,
+ };
+ if msg.id == message_id {
+ target_group = msg.grouped_id;
+ }
+ let caption = if msg.message.trim().is_empty() {
+ None
+ } else {
+ Some(msg.message.clone())
+ };
+ if let Some(ref media) = msg.media {
+ if let Some((file_name, file_size, media_type, webpage)) =
+ extract_raw_media_info_with_webpage(media, fix_extensions)
+ {
+ parsed.push((
+ msg.id,
+ msg.grouped_id,
+ TelegramMediaItem {
+ message_id: msg.id,
+ file_name,
+ file_size,
+ media_type,
+ date: msg.date as i64,
+ webpage,
+ caption,
+ grouped_id: msg.grouped_id,
+ },
+ ));
+ }
+ }
+ }
+
+ let mut out: Vec<TelegramMediaItem> = match target_group {
+ Some(gid) => parsed
+ .into_iter()
+ .filter(|(_, g, _)| *g == Some(gid))
+ .map(|(_, _, item)| item)
+ .collect(),
+ None => parsed
+ .into_iter()
+ .filter(|(id, _, _)| *id == message_id)
+ .map(|(_, _, item)| item)
+ .collect(),
+ };
+ out.sort_by_key(|item| item.message_id);
+ Ok(out)
+}
+
+pub async fn diag_list_media(
+ handle: &TelegramSessionHandle,
+ chat_id: i64,
+ chat_type: &str,
+) -> anyhow::Result<serde_json::Value> {
+ let (client_opt, access_hash, cached_peers) = {
+ let guard = handle.lock().await;
+ (
+ guard.client.clone(),
+ guard.peer_hashes.get(&chat_id).copied(),
+ guard.peer_hashes.len(),
+ )
+ };
+
+ let client = match client_opt {
+ Some(c) => c,
+ None => {
+ return Ok(serde_json::json!({
+ "chat_id": chat_id,
+ "chat_type": chat_type,
+ "has_client": false,
+ "is_authorized": false,
+ "access_hash_cached": access_hash.is_some(),
+ "access_hash_nonzero": access_hash.unwrap_or(0) != 0,
+ "cached_peers_total": cached_peers,
+ "input_peer_kind": "none",
+ "search_probes": [],
+ "history_probe": { "ok": false, "error": "Not authenticated" }
+ }));
+ }
+ };
+
+ let is_auth = client.is_authorized().await.unwrap_or(false);
+ let hash = access_hash.unwrap_or(0);
+ let peer = make_input_peer(chat_id, chat_type, hash);
+ let peer_kind = match &peer {
+ tl::enums::InputPeer::User(_) => "user",
+ tl::enums::InputPeer::Chat(_) => "chat",
+ tl::enums::InputPeer::Channel(_) => "channel",
+ _ => "empty",
+ };
+
+ let mut search_probes = Vec::new();
+ for filter_name in ["photo", "video", "document", "audio"] {
+ let t0 = std::time::Instant::now();
+ match fetch_media_page(&client, &peer, Some(filter_name), "", 0, 10, true).await {
+ Ok(items) => search_probes.push(serde_json::json!({
+ "filter": filter_name,
+ "ok": true,
+ "elapsed_ms": t0.elapsed().as_millis() as u64,
+ "raw_messages": items.len(),
+ "extracted_media": items.len(),
+ })),
+ Err(e) => search_probes.push(serde_json::json!({
+ "filter": filter_name,
+ "ok": false,
+ "elapsed_ms": t0.elapsed().as_millis() as u64,
+ "error": e.to_string(),
+ })),
+ }
+ }
+
+ let t_hist = std::time::Instant::now();
+ let hist_req = tl::functions::messages::GetHistory {
+ peer,
+ offset_id: 0,
+ offset_date: 0,
+ add_offset: 0,
+ limit: 20,
+ max_id: 0,
+ min_id: 0,
+ hash: 0,
+ };
+ let history_probe = match invoke_with_flood_wait(&client, &hist_req).await {
+ Ok(res) => {
+ let msgs = match res {
+ tl::enums::messages::Messages::Messages(m) => m.messages,
+ tl::enums::messages::Messages::Slice(m) => m.messages,
+ tl::enums::messages::Messages::ChannelMessages(m) => m.messages,
+ tl::enums::messages::Messages::NotModified(_) => Vec::new(),
+ };
+ let mut with_media = 0usize;
+ for m in &msgs {
+ if let tl::enums::Message::Message(msg) = m {
+ if msg.media.is_some() {
+ with_media += 1;
+ }
+ }
+ }
+ serde_json::json!({
+ "ok": true,
+ "elapsed_ms": t_hist.elapsed().as_millis() as u64,
+ "raw_messages": msgs.len(),
+ "with_media": with_media,
+ "media_kinds": {},
+ })
+ }
+ Err(e) => serde_json::json!({
+ "ok": false,
+ "elapsed_ms": t_hist.elapsed().as_millis() as u64,
+ "error": e.to_string(),
+ }),
+ };
+
+ Ok(serde_json::json!({
+ "chat_id": chat_id,
+ "chat_type": chat_type,
+ "has_client": true,
+ "is_authorized": is_auth,
+ "access_hash_cached": access_hash.is_some(),
+ "access_hash_nonzero": hash != 0,
+ "cached_peers_total": cached_peers,
+ "input_peer_kind": peer_kind,
+ "search_probes": search_probes,
+ "history_probe": history_probe,
+ }))
+}
+
+pub fn guess_mime_from_filename(name: &str) -> &'static str {
+ let ext = Path::new(name)
+ .extension()
+ .and_then(|e| e.to_str())
+ .unwrap_or("")
+ .to_ascii_lowercase();
+ match ext.as_str() {
+ "mp4" => "video/mp4",
+ "mkv" => "video/x-matroska",
+ "webm" => "video/webm",
+ "mov" => "video/quicktime",
+ "avi" => "video/x-msvideo",
+ "mp3" => "audio/mpeg",
+ "ogg" => "audio/ogg",
+ "opus" => "audio/x-opus+ogg",
+ "flac" => "audio/flac",
+ "wav" => "audio/wav",
+ "m4a" => "audio/mp4",
+ "jpg" | "jpeg" => "image/jpeg",
+ "png" => "image/png",
+ "gif" => "image/gif",
+ "webp" => "image/webp",
+ "pdf" => "application/pdf",
+ "zip" => "application/zip",
+ _ => "application/octet-stream",
+ }
+}
+
+pub async fn upload_file_to_peer(
+ handle: &TelegramSessionHandle,
+ peer: tl::enums::InputPeer,
+ file_path: &Path,
+ caption: &str,
+ progress_tx: mpsc::Sender<(u64, u64)>,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use tokio::io::AsyncReadExt;
+
+ let client = {
+ let guard = handle.lock().await;
+ guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone()
+ };
+
+ let meta = tokio::fs::metadata(file_path).await?;
+ let total_bytes = meta.len();
+ let file_name = file_path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("upload.bin")
+ .to_string();
+
+ let chunk_size: usize = 512 * 1024;
+ let total_parts = total_bytes.div_ceil(chunk_size as u64).max(1) as i32;
+ let file_id = next_random_id(total_bytes);
+ let is_big = total_bytes > 10 * 1024 * 1024;
+
+ let mut file = tokio::fs::File::open(file_path).await?;
+ let mut uploaded: u64 = 0;
+ let mut part_idx: i32 = 0;
+
+ loop {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow::anyhow!("Upload cancelled"));
+ }
+
+ let mut buf = vec![0u8; chunk_size];
+ let mut read_in_part = 0usize;
+ while read_in_part < chunk_size {
+ let n = file.read(&mut buf[read_in_part..]).await?;
+ if n == 0 {
+ break;
+ }
+ read_in_part += n;
+ }
+
+ if read_in_part == 0 && part_idx > 0 {
+ break;
+ }
+ buf.truncate(read_in_part);
+
+ if is_big {
+ let req = tl::functions::upload::SaveBigFilePart {
+ file_id,
+ file_part: part_idx,
+ file_total_parts: total_parts,
+ bytes: buf,
+ };
+ let ok = invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("upload.saveBigFilePart failed: {}", e))?;
+ if !ok {
+ return Err(anyhow::anyhow!("Telegram rejected uploaded file part"));
+ }
+ } else {
+ let req = tl::functions::upload::SaveFilePart {
+ file_id,
+ file_part: part_idx,
+ bytes: buf,
+ };
+ let ok = invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("upload.saveFilePart failed: {}", e))?;
+ if !ok {
+ return Err(anyhow::anyhow!("Telegram rejected uploaded file part"));
+ }
+ }
+
+ uploaded += read_in_part as u64;
+ part_idx += 1;
+ let _ = progress_tx.send((uploaded, total_bytes)).await;
+
+ if read_in_part < chunk_size || uploaded >= total_bytes {
+ break;
+ }
+ }
+
+ let input_file = if is_big {
+ tl::enums::InputFile::Big(tl::types::InputFileBig {
+ id: file_id,
+ parts: part_idx.max(1),
+ name: file_name.clone(),
+ })
+ } else {
+ tl::enums::InputFile::File(tl::types::InputFile {
+ id: file_id,
+ parts: part_idx.max(1),
+ name: file_name.clone(),
+ md5_checksum: String::new(),
+ })
+ };
+
+ let mime_type = guess_mime_from_filename(&file_name).to_string();
+ let media = tl::enums::InputMedia::UploadedDocument(tl::types::InputMediaUploadedDocument {
+ nosound_video: false,
+ force_file: false,
+ spoiler: false,
+ file: input_file,
+ thumb: None,
+ mime_type,
+ attributes: vec![tl::enums::DocumentAttribute::Filename(
+ tl::types::DocumentAttributeFilename { file_name },
+ )],
+ stickers: None,
+ video_cover: None,
+ video_timestamp: None,
+ ttl_seconds: None,
+ });
+
+ let send_req = tl::functions::messages::SendMedia {
+ silent: false,
+ background: false,
+ clear_draft: false,
+ noforwards: false,
+ update_stickersets_order: false,
+ invert_media: false,
+ allow_paid_floodskip: false,
+ peer,
+ reply_to: None,
+ media,
+ message: caption.to_string(),
+ random_id: next_random_id(file_id as u64),
+ reply_markup: None,
+ entities: None,
+ schedule_date: None,
+ send_as: None,
+ quick_reply_shortcut: None,
+ effect: None,
+ allow_paid_stars: None,
+ suggested_post: None,
+ };
+
+ invoke_with_flood_wait(&client, &send_req)
+ .await
+ .map_err(|e| anyhow::anyhow!("messages.sendMedia failed: {}", e))?;
+
+ Ok(total_bytes)
+}
+
+pub async fn resolve_destination_peer(
+ handle: &TelegramSessionHandle,
+ destination: &str,
+) -> anyhow::Result<tl::enums::InputPeer> {
+ let dest = destination.trim();
+ if dest.is_empty() || dest.eq_ignore_ascii_case("me") || dest.eq_ignore_ascii_case("saved") {
+ return Ok(tl::enums::InputPeer::PeerSelf);
+ }
+
+ if let Ok(id) = dest.parse::<i64>() {
+ let bare = if id < -1000000000000 {
+ (-id) - 1000000000000
+ } else {
+ id.abs()
+ };
+ let hash = {
+ let guard = handle.lock().await;
+ guard.peer_hashes.get(&bare).copied().unwrap_or(0)
+ };
+ if id < -1000000000000 || hash != 0 {
+ return Ok(tl::enums::InputPeer::Channel(tl::types::InputPeerChannel {
+ channel_id: bare,
+ access_hash: hash,
+ }));
+ }
+ return Ok(tl::enums::InputPeer::Chat(tl::types::InputPeerChat {
+ chat_id: bare,
+ }));
+ }
+
+ let username = dest
+ .trim_start_matches("https://t.me/")
+ .trim_start_matches("http://t.me/")
+ .trim_start_matches("t.me/")
+ .trim_start_matches('@')
+ .split('/')
+ .next()
+ .unwrap_or("")
+ .trim();
+
+ let client = {
+ let guard = handle.lock().await;
+ guard
+ .client
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ .clone()
+ };
+
+ let req = tl::functions::contacts::ResolveUsername {
+ username: username.to_string(),
+ referer: None,
+ };
+ let resolved = invoke_with_flood_wait(&client, &req)
+ .await
+ .map_err(|e| anyhow::anyhow!("contacts.resolveUsername failed: {}", e))?;
+ let tl::enums::contacts::ResolvedPeer::Peer(r) = resolved;
+
+ for c in r.chats {
+ match c {
+ tl::enums::Chat::Channel(ch) => {
+ let hash = ch.access_hash.unwrap_or(0);
+ handle.lock().await.peer_hashes.insert(ch.id, hash);
+ return Ok(tl::enums::InputPeer::Channel(tl::types::InputPeerChannel {
+ channel_id: ch.id,
+ access_hash: hash,
+ }));
+ }
+ tl::enums::Chat::Chat(chat) => {
+ return Ok(tl::enums::InputPeer::Chat(tl::types::InputPeerChat {
+ chat_id: chat.id,
+ }));
+ }
+ _ => {}
+ }
+ }
+ for u in r.users {
+ if let tl::enums::User::User(user) = u {
+ let hash = user.access_hash.unwrap_or(0);
+ handle.lock().await.peer_hashes.insert(user.id, hash);
+ return Ok(tl::enums::InputPeer::User(tl::types::InputPeerUser {
+ user_id: user.id,
+ access_hash: hash,
+ }));
+ }
+ }
+
+ Err(anyhow::anyhow!(
+ "Could not resolve destination: {}",
+ destination
+ ))
+}
+
+pub async fn ensure_stream_server(
+ session: TelegramSessionHandle,
+ slot: std::sync::Arc<tokio::sync::Mutex<Option<crate::state::TelegramStreamInfo>>>,
+) -> anyhow::Result<crate::state::TelegramStreamInfo> {
+ let mut guard = slot.lock().await;
+ if let Some(ref info) = *guard {
+ return Ok(info.clone());
+ }
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
+ let port = listener.local_addr()?.port();
+ let token = format!("{:016x}", next_random_id(port as u64) as u64);
+ let info = crate::state::TelegramStreamInfo {
+ port,
+ token: token.clone(),
+ base_url: format!("http://127.0.0.1:{}", port),
+ };
+ *guard = Some(info.clone());
+ drop(guard);
+
+ tokio::spawn(async move {
+ while let Ok((stream, _)) = listener.accept().await {
+ let session_clone = session.clone();
+ let token_clone = token.clone();
+ tokio::spawn(async move {
+ let _ = handle_stream_connection(stream, session_clone, &token_clone).await;
+ });
+ }
+ });
+
+ Ok(info)
+}
+
+async fn handle_stream_connection(
+ mut socket: tokio::net::TcpStream,
+ session: TelegramSessionHandle,
+ expected_token: &str,
+) -> anyhow::Result<()> {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ let mut req_buf = vec![0u8; 8192];
+ let n = socket.read(&mut req_buf).await?;
+ if n == 0 {
+ return Ok(());
+ }
+ let req_str = String::from_utf8_lossy(&req_buf[..n]);
+ let mut lines = req_str.lines();
+ let first_line = lines.next().unwrap_or("");
+ let mut parts = first_line.split_whitespace();
+ let method = parts.next().unwrap_or("GET");
+ let raw_target = parts.next().unwrap_or("/");
+
+ if method == "OPTIONS" {
+ let resp = "HTTP/1.1 204 No Content\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: GET, HEAD, OPTIONS\r\nAccess-Control-Allow-Headers: Range\r\n\r\n";
+ socket.write_all(resp.as_bytes()).await?;
+ return Ok(());
+ }
+
+ let (path, query) = raw_target.split_once('?').unwrap_or((raw_target, ""));
+ let token_ok = query.split('&').any(|kv| {
+ if let Some((k, v)) = kv.split_once('=') {
+ k == "token" && v == expected_token
+ } else {
+ false
+ }
+ });
+
+ if !token_ok {
+ let resp = "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n";
+ socket.write_all(resp.as_bytes()).await?;
+ return Ok(());
+ }
+
+ let segs: Vec<&str> = path.trim_matches('/').split('/').collect();
+ if segs.len() < 4 || segs[0] != "stream" {
+ let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
+ socket.write_all(resp.as_bytes()).await?;
+ return Ok(());
+ }
+
+ let chat_type = segs[1];
+ let chat_id: i64 = segs[2].parse().unwrap_or(0);
+ let message_id: i32 = segs[3].parse().unwrap_or(0);
+
+ let mut range_header: Option<(u64, Option<u64>)> = None;
+ for line in lines {
+ if let Some((k, v)) = line.split_once(':') {
+ if k.trim().eq_ignore_ascii_case("range") {
+ let val = v.trim();
+ if let Some(bytes_spec) = val.strip_prefix("bytes=") {
+ if let Some((start_s, end_s)) = bytes_spec.split_once('-') {
+ if let Ok(start) = start_s.trim().parse::<u64>() {
+ let end = end_s.trim().parse::<u64>().ok();
+ range_header = Some((start, end));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ let (client, access_hash) = {
+ let guard = session.lock().await;
+ let client = match guard.client.as_ref() {
+ Some(c) => c.clone(),
+ None => {
+ let resp = "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n";
+ socket.write_all(resp.as_bytes()).await?;
+ return Ok(());
+ }
+ };
+ let hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);
+ (client, hash)
+ };
+
+ let is_channel = chat_type == "channel" || (chat_type == "group" && access_hash != 0);
+ let (raw_media, _) = match super::parallel_download::fetch_raw_media(
+ &client,
+ chat_id,
+ access_hash,
+ is_channel,
+ message_id,
+ )
+ .await
+ {
+ Ok(m) => m,
+ Err(_) => {
+ let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
+ socket.write_all(resp.as_bytes()).await?;
+ return Ok(());
+ }
+ };
+
+ let media = match super::parallel_download::media_to_location(&raw_media) {
+ Some(m) => m,
+ None => {
+ let resp = "HTTP/1.1 415 Unsupported Media Type\r\nContent-Length: 0\r\n\r\n";
+ socket.write_all(resp.as_bytes()).await?;
+ return Ok(());
+ }
+ };
+
+ let total_size = media.size;
+ if total_size == 0 {
+ let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
+ socket.write_all(resp.as_bytes()).await?;
+ return Ok(());
+ }
+
+ let (start, end, is_partial) = match range_header {
+ Some((s, e_opt)) => {
+ let s = s.min(total_size.saturating_sub(1));
+ let e = e_opt
+ .unwrap_or(total_size - 1)
+ .min(total_size.saturating_sub(1))
+ .max(s);
+ (s, e, true)
+ }
+ None => (0, total_size - 1, false),
+ };
+
+ let content_length = end - start + 1;
+ let headers = if is_partial {
+ format!(
+ "HTTP/1.1 206 Partial Content\r\nContent-Type: {}\r\nAccept-Ranges: bytes\r\nContent-Range: bytes {}-{}/{}\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n",
+ media.mime_type, start, end, total_size, content_length
+ )
+ } else {
+ format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: {}\r\nAccept-Ranges: bytes\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n",
+ media.mime_type, content_length
+ )
+ };
+
+ socket.write_all(headers.as_bytes()).await?;
+ if method == "HEAD" {
+ return Ok(());
+ }
+
+ let chunk_limit: u64 = 512 * 1024;
+ let mut cursor = start;
+ while cursor <= end {
+ let aligned_offset = (cursor / 4096) * 4096;
+ let skip = (cursor - aligned_offset) as usize;
+ let bytes = super::parallel_download::fetch_media_chunk(
+ &client,
+ &media,
+ aligned_offset as i64,
+ chunk_limit as i32,
+ )
+ .await?;
+ if bytes.len() <= skip {
+ break;
+ }
+ let available = &bytes[skip..];
+ let remaining = (end - cursor + 1) as usize;
+ let to_write = available.len().min(remaining);
+ if socket.write_all(&available[..to_write]).await.is_err() {
+ break;
+ }
+ cursor += to_write as u64;
+ if (bytes.len() as u64) < chunk_limit {
+ break;
+ }
+ }
+
+ let _ = socket.flush().await;
+ Ok(())
+}
diff --git a/src-tauri/plugins/telegram/src/platforms/telegram/auth.rs b/src-tauri/plugins/telegram/src/platforms/telegram/auth.rs
index 3d103138..df128867 100644
--- a/src-tauri/plugins/telegram/src/platforms/telegram/auth.rs
+++ b/src-tauri/plugins/telegram/src/platforms/telegram/auth.rs
@@ -48,11 +48,26 @@ impl TelegramState {
}
}
-fn session_file_path() -> anyhow::Result<PathBuf> {
+pub fn session_file_path() -> anyhow::Result<PathBuf> {
let data_dir = dirs::data_dir().ok_or_else(|| anyhow!("Cannot find app data directory"))?;
Ok(data_dir.join("omniget").join("telegram.session"))
}
+pub async fn disconnect_and_clear_client(handle: &TelegramSessionHandle) {
+ let mut guard = handle.lock().await;
+ if let Some(client) = guard.client.take() {
+ client.disconnect();
+ }
+ guard.phone.clear();
+ guard.login_token = None;
+ guard.password_token = None;
+ guard.updates_rx = None;
+ guard.peer_hashes.clear();
+ drop(guard);
+ set_home_dc(0);
+ super::parallel_download::clear_auth_copied_dcs().await;
+}
+
fn open_session() -> anyhow::Result<Arc<SqliteSession>> {
let path = session_file_path()?;
if let Some(parent) = path.parent() {
diff --git a/src-tauri/plugins/telegram/src/platforms/telegram/mod.rs b/src-tauri/plugins/telegram/src/platforms/telegram/mod.rs
index 3050460c..cc504759 100644
--- a/src-tauri/plugins/telegram/src/platforms/telegram/mod.rs
+++ b/src-tauri/plugins/telegram/src/platforms/telegram/mod.rs
@@ -3,3 +3,19 @@ pub mod auth;
pub mod downloader;
pub mod parallel_download;
pub mod thumbnail_cache;
+
+pub struct SubtleValidator;
+
+impl SubtleValidator {
+ pub fn validate_safe_id(id: &str) -> Result<(), String> {
+ if id.is_empty()
+ || id.contains("..")
+ || id
+ .chars()
+ .any(|c| !c.is_ascii_alphanumeric() && !matches!(c, '_' | '-'))
+ {
+ return Err("Invalid account identifier".to_string());
+ }
+ Ok(())
+ }
+}
diff --git a/src-tauri/plugins/telegram/src/platforms/telegram/parallel_download.rs b/src-tauri/plugins/telegram/src/platforms/telegram/parallel_download.rs
index 5f5b43ed..176ae0eb 100644
--- a/src-tauri/plugins/telegram/src/platforms/telegram/parallel_download.rs
+++ b/src-tauri/plugins/telegram/src/platforms/telegram/parallel_download.rs
@@ -11,6 +11,7 @@ pub struct MediaLocation {
pub location: tl::enums::InputFileLocation,
pub size: u64,
pub dc_id: i32,
+ pub mime_type: String,
}
pub fn media_to_location(media: &tl::enums::MessageMedia) -> Option<MediaLocation> {
@@ -32,6 +33,7 @@ pub fn media_to_location(media: &tl::enums::MessageMedia) -> Option<MediaLocatio
location,
size: doc.size as u64,
dc_id: doc.dc_id,
+ mime_type: doc.mime_type.clone(),
})
}
tl::enums::MessageMedia::Photo(photo_media) => {
@@ -60,6 +62,7 @@ pub fn media_to_location(media: &tl::enums::MessageMedia) -> Option<MediaLocatio
location,
size: largest.size as u64,
dc_id: photo.dc_id,
+ mime_type: "image/jpeg".to_string(),
})
}
_ => None,
@@ -313,3 +316,49 @@ pub async fn download_file(
tracing::info!("[tg-dl] download complete: {} bytes, dc={}", downloaded, dc);
Ok(downloaded)
}
+
+pub async fn fetch_media_chunk(
+ client: &Client,
+ media: &MediaLocation,
+ aligned_offset: i64,
+ limit: i32,
+) -> anyhow::Result<Vec<u8>> {
+ let mut dc = media.dc_id;
+ ensure_auth_on_dc(client, dc).await?;
+
+ for _ in 0..3 {
+ let request = tl::functions::upload::GetFile {
+ precise: true,
+ cdn_supported: false,
+ location: media.location.clone(),
+ offset: aligned_offset,
+ limit,
+ };
+
+ match client.invoke_in_dc(dc, &request).await {
+ Ok(tl::enums::upload::File::File(f)) => return Ok(f.bytes),
+ Ok(tl::enums::upload::File::CdnRedirect(_)) => {
+ return Err(anyhow::anyhow!("CDN redirect not supported"));
+ }
+ Err(grammers_mtsender::InvocationError::Rpc(ref err))
+ if err.name == "AUTH_KEY_UNREGISTERED" =>
+ {
+ {
+ let mut copied = auth_copied_dcs().lock().await;
+ copied.retain(|&d| d != dc);
+ }
+ ensure_auth_on_dc(client, dc).await?;
+ }
+ Err(grammers_mtsender::InvocationError::Rpc(ref err))
+ if err.code == FILE_MIGRATE_ERROR =>
+ {
+ let new_dc = err.value.map(|v| v as i32).unwrap_or(dc);
+ dc = new_dc;
+ ensure_auth_on_dc(client, dc).await?;
+ }
+ Err(e) => return Err(anyhow::anyhow!("upload.getFile failed: {}", e)),
+ }
+ }
+
+ Err(anyhow::anyhow!("upload.getFile failed after retries"))
+}
diff --git a/src-tauri/plugins/telegram/src/state.rs b/src-tauri/plugins/telegram/src/state.rs
index 72d1b97b..e0b574f2 100644
--- a/src-tauri/plugins/telegram/src/state.rs
+++ b/src-tauri/plugins/telegram/src/state.rs
@@ -1,13 +1,252 @@
use std::collections::HashMap;
+use std::path::PathBuf;
use std::sync::Arc;
+
+use serde::{Deserialize, Serialize};
use tokio_util::sync::CancellationToken;
use crate::platforms::telegram::auth::{TelegramSessionHandle, TelegramState};
+fn default_max_threads() -> u32 {
+ 8
+}
+
+fn default_sync_interval() -> u32 {
+ 30
+}
+
+fn default_clone_delay_ms() -> u64 {
+ 2000
+}
+
+fn default_clone_batch_size() -> usize {
+ 50
+}
+
+pub fn current_ymd() -> String {
+ chrono::Utc::now().format("%Y-%m-%d").to_string()
+}
+
+pub fn unix_now_secs() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs()
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TelegramDcBucket {
+ pub dc_id: i32,
+ pub tokens: f64,
+ pub last_flood_secs: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TelegramPerfState {
+ #[serde(default = "default_max_threads")]
+ pub max_threads: u32,
+ #[serde(default)]
+ pub buckets: Vec<TelegramDcBucket>,
+}
+
+impl Default for TelegramPerfState {
+ fn default() -> Self {
+ Self {
+ max_threads: 8,
+ buckets: Vec::new(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct TelegramBandwidthState {
+ #[serde(default)]
+ pub used_today_bytes: u64,
+ #[serde(default)]
+ pub total_used_bytes: u64,
+ #[serde(default)]
+ pub quota_bytes: u64,
+ #[serde(default)]
+ pub date: String,
+}
+
+impl TelegramBandwidthState {
+ pub fn normalize_day(&mut self) {
+ let today = current_ymd();
+ if self.date != today {
+ self.used_today_bytes = 0;
+ self.date = today;
+ }
+ }
+
+ pub fn record_bytes(&mut self, bytes: u64) {
+ self.normalize_day();
+ self.used_today_bytes = self.used_today_bytes.saturating_add(bytes);
+ self.total_used_bytes = self.total_used_bytes.saturating_add(bytes);
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TelegramSyncState {
+ #[serde(default)]
+ pub enabled: bool,
+ #[serde(default = "default_sync_interval")]
+ pub interval_min: u32,
+ #[serde(default)]
+ pub last_success_at: u64,
+ #[serde(default)]
+ pub last_duration_ms: u64,
+ #[serde(default)]
+ pub last_updated_count: usize,
+ #[serde(skip)]
+ pub is_syncing: bool,
+}
+
+impl Default for TelegramSyncState {
+ fn default() -> Self {
+ Self {
+ enabled: false,
+ interval_min: 30,
+ last_success_at: 0,
+ last_duration_ms: 0,
+ last_updated_count: 0,
+ is_syncing: false,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TelegramAccountEntry {
+ pub id: String,
+ pub label: String,
+ pub phone_redacted: Option<String>,
+ pub user_id: Option<i64>,
+ pub created_at: u64,
+ pub updated_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TelegramCloneOptions {
+ #[serde(default = "default_clone_delay_ms")]
+ pub delay_ms: u64,
+ #[serde(default = "default_clone_batch_size")]
+ pub batch_size: usize,
+ #[serde(default)]
+ pub limit: Option<usize>,
+ #[serde(default)]
+ pub drop_author: bool,
+ #[serde(default)]
+ pub drop_captions: bool,
+}
+
+impl Default for TelegramCloneOptions {
+ fn default() -> Self {
+ Self {
+ delay_ms: default_clone_delay_ms(),
+ batch_size: default_clone_batch_size(),
+ limit: None,
+ drop_author: false,
+ drop_captions: false,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TelegramCloneSession {
+ pub id: String,
+ pub source_chat_id: i64,
+ pub source_chat_type: String,
+ pub source_title: String,
+ pub dest_chat_id: i64,
+ pub dest_chat_type: String,
+ pub dest_title: String,
+ pub last_message_id: i32,
+ pub total_collected: usize,
+ pub cloned_count: usize,
+ pub failed_count: usize,
+ pub status: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub last_error: Option<String>,
+ pub options: TelegramCloneOptions,
+ pub created_at: u64,
+ pub updated_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct TelegramPersistentData {
+ #[serde(default)]
+ pub perf: TelegramPerfState,
+ #[serde(default)]
+ pub bandwidth: TelegramBandwidthState,
+ #[serde(default)]
+ pub sync: TelegramSyncState,
+ #[serde(default)]
+ pub accounts: Vec<TelegramAccountEntry>,
+ #[serde(default)]
+ pub clones: Vec<TelegramCloneSession>,
+ #[serde(default)]
+ pub takeout_id: Option<i64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TelegramStreamInfo {
+ pub port: u16,
+ pub token: String,
+ pub base_url: String,
+}
+
+pub fn omniget_data_dir() -> PathBuf {
+ dirs::data_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join("omniget")
+}
+
+pub fn persistent_state_path() -> PathBuf {
+ omniget_data_dir().join("telegram_plugin_state.json")
+}
+
+pub fn accounts_dir() -> PathBuf {
+ omniget_data_dir().join("telegram_accounts")
+}
+
+pub fn backups_dir() -> PathBuf {
+ omniget_data_dir().join("telegram_backups")
+}
+
+impl TelegramPersistentData {
+ pub fn load() -> Self {
+ let path = persistent_state_path();
+ let mut data: Self = std::fs::read_to_string(&path)
+ .ok()
+ .and_then(|s| serde_json::from_str(&s).ok())
+ .unwrap_or_default();
+ data.bandwidth.normalize_day();
+ for clone in &mut data.clones {
+ if clone.status == "running" {
+ clone.status = "paused".to_string();
+ }
+ }
+ data
+ }
+
+ pub fn save(&self) {
+ let path = persistent_state_path();
+ if let Some(parent) = path.parent() {
+ let _ = std::fs::create_dir_all(parent);
+ }
+ if let Ok(json) = serde_json::to_string_pretty(self) {
+ let _ = std::fs::write(&path, json);
+ }
+ }
+}
+
pub struct TelegramPluginState {
pub telegram_session: TelegramSessionHandle,
pub active_generic_downloads:
Arc<tokio::sync::Mutex<HashMap<u64, (String, CancellationToken)>>>,
+ pub active_ops: Arc<tokio::sync::Mutex<HashMap<String, CancellationToken>>>,
+ pub persistent: Arc<tokio::sync::Mutex<TelegramPersistentData>>,
+ pub stream_server: Arc<tokio::sync::Mutex<Option<TelegramStreamInfo>>>,
}
impl Default for TelegramPluginState {
@@ -15,6 +254,9 @@ impl Default for TelegramPluginState {
Self {
telegram_session: Arc::new(tokio::sync::Mutex::new(TelegramState::new())),
active_generic_downloads: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
+ active_ops: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
+ persistent: Arc::new(tokio::sync::Mutex::new(TelegramPersistentData::load())),
+ stream_server: Arc::new(tokio::sync::Mutex::new(None)),
}
}
}
diff --git a/src-tauri/src/commands/plugins.rs b/src-tauri/src/commands/plugins.rs
index 499fa265..4e64ed1d 100644
--- a/src-tauri/src/commands/plugins.rs
+++ b/src-tauri/src/commands/plugins.rs
@@ -228,19 +228,15 @@ pub async fn plugin_command(
args: serde_json::Value,
) -> Result<serde_json::Value, String> {
let manager = state.read().await;
+ let is_builtin = manager.is_builtin(&plugin_id);
manager
.handle_command(&plugin_id, &command, args)
.await
.map_err(|e| {
- // Issue #193: a loaded but outdated plugin DLL answers "Unknown
- // command"/"Command X not found" when the (newer) frontend calls a
- // command it predates. Raw, that reads like an app bug; rewrite it
- // into an actionable update hint. ERR_PLUGIN_OUTDATED is matched by
- // error-translate.ts on the frontend.
let lower = e.to_lowercase();
let unknown_command = lower.contains("unknown command")
|| (lower.contains("command") && lower.contains("not found"));
- if unknown_command && !lower.contains("not loaded") {
+ if unknown_command && !lower.contains("not loaded") && !is_builtin {
format!(
"ERR_PLUGIN_OUTDATED: The installed '{}' plugin is outdated and doesn't support '{}'. Update it in the Marketplace, then restart OmniGet. ({})",
plugin_id, command, e
@@ -389,6 +385,14 @@ pub async fn install_plugin_zip_from_repo(
plugin_id: String,
repo: String,
) -> Result<String, String> {
+ {
+ let manager = state.read().await;
+ if let Some(lp) = manager.get(&plugin_id) {
+ if manager.is_builtin(&plugin_id) {
+ return Ok(lp.manifest.version.clone());
+ }
+ }
+ }
let suffix = platform_artifact_suffix();
if suffix == "unknown" {
return Err("Unsupported platform".to_string());
diff --git a/src-tauri/src/plugin_loader.rs b/src-tauri/src/plugin_loader.rs
index 26e8db1c..92d0d9cc 100644
--- a/src-tauri/src/plugin_loader.rs
+++ b/src-tauri/src/plugin_loader.rs
@@ -121,7 +121,18 @@ impl PluginManager {
},
);
self.load_errors.remove(&id);
- if !self.installed.iter().any(|p| p.id == id) {
+ if let Some(existing) = self.installed.iter_mut().find(|p| p.id == id) {
+ if existing.version != manifest.version
+ || existing.repo.is_some()
+ || existing.source_release.is_some()
+ {
+ existing.version = manifest.version.clone();
+ existing.repo = None;
+ existing.source_release = None;
+ existing.updated_at = chrono::Utc::now().to_rfc3339();
+ let _ = self.save_installed();
+ }
+ } else {
self.installed.push(InstalledPlugin {
id: id.clone(),
version: manifest.version.clone(),
@@ -141,6 +152,13 @@ impl PluginManager {
Ok(())
}
+ pub fn is_builtin(&self, id: &str) -> bool {
+ self.loaded
+ .get(id)
+ .map(|lp| lp._lib.is_none())
+ .unwrap_or(false)
+ }
+
pub fn load_one(&mut self, id: &str, host: Arc<dyn PluginHost>) -> Result<(), PluginLoadError> {
let plugin_dir = self.plugin_dir(id).map_err(|e| PluginLoadError {
message: e.to_string(),
diff --git a/src/lib/telegram-components/TelegramAccountPanel.svelte b/src/lib/telegram-components/TelegramAccountPanel.svelte
index c9ae6521..9a4c111a 100644
--- a/src/lib/telegram-components/TelegramAccountPanel.svelte
+++ b/src/lib/telegram-components/TelegramAccountPanel.svelte
@@ -52,9 +52,7 @@
backups = Array.isArray(bks) ? bks : [];
} catch (e: any) {
const msg = typeof e === "string" ? e : (e?.message ?? "");
- if (!msg.includes("ERR_PLUGIN_OUTDATED")) {
- error = msg || $t("common.error");
- }
+ error = msg || $t("common.error");
} finally {
loading = false;
}
diff --git a/src/lib/telegram-components/TelegramChannelDrawer.svelte b/src/lib/telegram-components/TelegramChannelDrawer.svelte
index 8257c496..900fa870 100644
--- a/src/lib/telegram-components/TelegramChannelDrawer.svelte
+++ b/src/lib/telegram-components/TelegramChannelDrawer.svelte
@@ -114,7 +114,7 @@
participants = [];
participantsCount = 0;
const msg = typeof e === "string" ? e : (e?.message ?? "");
- if (msg.includes("ERR_PLUGIN_OUTDATED") || msg.includes("ADMIN_REQUIRED") || msg.includes("CHAT_ADMIN_REQUIRED")) {
+ if (msg.includes("ADMIN_REQUIRED") || msg.includes("CHAT_ADMIN_REQUIRED")) {
participantsError = "";
} else {
participantsError = msg || $t("telegram.channel_drawer.error_loading_members");
diff --git a/src/lib/telegram-components/TelegramCloneWizard.svelte b/src/lib/telegram-components/TelegramCloneWizard.svelte
index c8f058c0..7867b19f 100644
--- a/src/lib/telegram-components/TelegramCloneWizard.svelte
+++ b/src/lib/telegram-components/TelegramCloneWizard.svelte
@@ -93,9 +93,7 @@
} catch (e: any) {
sessions = [];
const msg = typeof e === "string" ? e : (e?.message ?? "");
- if (!msg.includes("ERR_PLUGIN_OUTDATED")) {
- error = msg || $t("common.error");
- }
+ error = msg || $t("common.error");
} finally {
loading = false;
}