kellemar's picture
Upload folder using huggingface_hub
5a616ce verified
Raw History Blame Contribute Delete
48.8 kB
import asyncio
import gradio as gr # Added Gradio import
from telethon import TelegramClient, functions
from telethon.errors import SessionPasswordNeededError, FloodWaitError, PhoneCodeInvalidError, PasswordHashInvalidError # Added specific exceptions
from telethon.tl.types import PeerUser, PeerChat, PeerChannel, DialogFilter
import getpass # Still needed for 2FA password (though Gradio will handle input)
import os
import json # Import the json module
import re # For sanitizing filenames
import time # For handling rate limits
from datetime import datetime, timezone # Import timezone
from telethon.tl.types import InputPeerUser
import csv
CONFIG_FILE = 'config.json'
BASE_OUTPUT_DIR = 'folder_downloads' # Base directory to store folder downloads
# Dictionary to store fetched filter objects for later peer retrieval - Needs careful state management with Gradio
# fetched_filters = {} # Will be managed via gr.State
# --- Configuration Functions (Mostly unchanged) ---
def load_config():
"""Loads configuration from the JSON file."""
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
print(f"Warning: Error reading {CONFIG_FILE}. Will re-prompt for details.")
return {}
except Exception as e:
print(f"Warning: Could not load config file {CONFIG_FILE}: {e}")
return {}
return {}
def save_config(config_data):
"""Saves configuration to the JSON file."""
try:
with open(CONFIG_FILE, 'w') as f:
json.dump(config_data, f, indent=4)
# No print here, output goes to Gradio UI
except Exception as e:
# Log error to Gradio UI
print(f"Error saving config file {CONFIG_FILE}: {e}") # Keep console print for now
return f"Error saving config file: {e}"
return "Configuration saved."
def sanitize_filename(name):
"""Removes invalid characters for filenames."""
name = str(name) # Ensure it's a string
name = re.sub(r'[^\w\-\s]', '', name)
name = name.replace(' ', '_')
name = re.sub(r'_+', '_', name)
name = name.strip('_')
return name[:100] if name else "unnamed_chat"
# --- Refactored Core Logic for Gradio ---
# Placeholder for client state - managed by Gradio
# client = None
# sent_code_info = None # Store phone_code_hash
async def connect_and_authenticate(api_id_str, api_hash, phone_number):
"""Attempts to connect and initiate authentication."""
# Use client and sent_code_info carefully - Gradio State is preferred
client = None
sent_code_info = None
if not api_id_str or not api_hash or not phone_number:
yield "API ID, API Hash, and Phone Number are required."
yield (None, None, None, "Error") # Yield final state tuple
return
if not api_id_str.isdigit():
yield "Invalid API ID. Please enter a number."
yield (None, None, None, "Error")
return
api_id = int(api_id_str)
safe_phone = ''.join(filter(str.isalnum, phone_number))
session_file = f'{safe_phone}_session'
client = TelegramClient(session_file, api_id, api_hash)
sent_code_info = None # Reset sent code info
yield "Connecting to Telegram..."
try:
await client.connect()
except Exception as e:
yield f"Failed to connect: {e}"
yield (None, None, None, "Error")
return # Use bare return after yielding final state
if await client.is_user_authorized():
yield "Already authorized."
# Save config if details were manually entered
config = load_config()
if str(config.get('api_id')) != api_id_str or config.get('api_hash') != api_hash or config.get('phone_number') != phone_number:
config['api_id'] = api_id_str
config['api_hash'] = api_hash
config['phone_number'] = phone_number
save_status = save_config(config)
yield save_status
yield (client, None, None, "Authorized") # Yield final state
return
else:
yield "Authorization needed. Sending code..."
try:
sent_code_info = await client.send_code_request(phone_number)
yield "Code sent. Please enter the code below."
yield (client, sent_code_info, None, "NeedCode") # Yield final state
return
except FloodWaitError as fwe:
yield f"Rate limit hit. Please wait {fwe.seconds} seconds and try connecting again."
if client and client.is_connected():
await client.disconnect()
yield (None, None, None, "Error")
return
except Exception as e:
yield f"Error sending code: {e}"
if client and client.is_connected():
await client.disconnect()
yield (None, None, None, "Error")
return
async def submit_telegram_code(current_client, current_sent_code_info, phone_number, code):
"""Submits the Telegram code."""
if not current_client or not code:
yield "Connection not established or code missing."
yield (current_client, current_sent_code_info, "Error")
return
try:
await current_client.sign_in(phone_number, code, phone_code_hash=getattr(current_sent_code_info, 'phone_code_hash', None))
yield "Signed in successfully!"
# Save config since authentication succeeded
config = load_config()
config['api_id'] = str(current_client.api_id)
config['api_hash'] = current_client.api_hash
config['phone_number'] = phone_number
save_status = save_config(config)
yield save_status
yield (current_client, None, "Authorized") # Yield final state
return
except PhoneCodeInvalidError:
yield "Invalid code. Please try again."
yield (current_client, current_sent_code_info, "NeedCode")
return
except SessionPasswordNeededError:
yield "Two-factor authentication enabled. Please enter your password."
yield (current_client, None, "NeedPassword")
return
except FloodWaitError as fwe:
yield f"Rate limit hit. Waiting {fwe.seconds} seconds..."
await asyncio.sleep(fwe.seconds)
yield "Wait finished. Please try submitting the code again."
yield (current_client, current_sent_code_info, "NeedCode")
return
except Exception as e:
yield f"Error during sign in: {e}"
# Consider disconnecting or letting user retry
yield (current_client, current_sent_code_info, "NeedCode") # Let user retry
return
async def submit_telegram_password(current_client, password):
"""Submits the Telegram 2FA password."""
if not current_client or not password:
yield "Connection not established or password missing."
yield (current_client, "Error")
return
try:
await current_client.sign_in(password=password)
yield "Signed in successfully with password!"
# Config should have been saved during connect/code phases if needed
yield (current_client, "Authorized")
return
except PasswordHashInvalidError:
yield "Invalid password. Please try again."
yield (current_client, "NeedPassword")
return
except FloodWaitError as fwe:
yield f"Rate limit hit. Waiting {fwe.seconds} seconds..."
await asyncio.sleep(fwe.seconds)
yield "Wait finished. Please try submitting the password again."
yield (current_client, "NeedPassword")
return
except Exception as e:
yield f"Failed 2FA sign in: {e}"
# Consider disconnecting or letting user retry
yield (current_client, "NeedPassword") # Let user retry
return
async def get_folders(current_client):
"""Fetches chat folders and returns a list for display and fetched filter objects."""
if not current_client or not await current_client.is_user_authorized():
yield "Client not connected or authorized." # Yield message first
yield ([], {}, "Client not connected or authorized.") # Then yield state tuple
return # Bare return
yield "Fetching chat folders..."
folders_for_display = []
local_fetched_filters = {} # Store filters locally for this call
try:
# Add default folders (optional, might not be needed if only downloading custom)
# folders_for_display.append({"id": 0, "title": "All Chats"}) # ID 0 not usable?
# folders_for_display.append({"id": 1, "title": "Archived Chats"}) # ID 1 not usable?
result = await current_client(functions.messages.GetDialogFiltersRequest())
for f in result.filters:
if isinstance(f, DialogFilter):
# Get the title from TextWithEntities if present
if hasattr(f, 'title') and hasattr(f.title, 'text'):
folder_title = f.title.text
else:
folder_title = getattr(f, 'title', '') # Use getattr for safety
# Telethon sometimes returns non-string titles directly
if not isinstance(folder_title, str):
folder_title = f"Folder_{f.id}" # Fallback
if f.id >= 2: # Only custom folders seem reliably usable for peer lists
display_text = f"{folder_title} (ID: {f.id})"
folders_for_display.append((display_text, f.id)) # Tuple for Gradio Dropdown (display_text, value)
local_fetched_filters[f.id] = f
if not local_fetched_filters:
yield "No custom chat folders found."
yield ([], {}, "No custom folders.") # Yield tuple
return # Add return
else:
yield f"Found {len(local_fetched_filters)} custom folder(s)."
# Sort by ID for consistency
try:
# Safer sorting in case title format is unexpected
folders_for_display.sort(key=lambda x: int(re.search(r'\(ID:\s*(\d+)\)', x[0]).group(1)) if re.search(r'\(ID:\s*(\d+)\)', x[0]) else f.id)
except Exception:
pass # Ignore sorting errors if regex fails
yield (folders_for_display, local_fetched_filters, "Folders fetched.") # Yield tuple
return # Add return
except FloodWaitError as fwe:
yield f"Rate limit hit fetching folders. Waiting {fwe.seconds} seconds..."
await asyncio.sleep(fwe.seconds)
yield "Wait finished. Try fetching folders again."
yield ([], {}, "Rate limit error.") # Yield tuple
return # Add return
except Exception as e:
yield f"An error occurred while fetching folders: {e}"
yield ([], {}, f"Error fetching folders: {e}") # Yield tuple
return # Add return
async def export_folder_peers(current_client, folder_id, folder_title, current_fetched_filters):
"""Exports peers from the selected folder to a CSV file."""
if not current_client or not folder_id or not current_fetched_filters:
yield "Client not ready, folder not selected, or filter data missing."
return
selected_filter_object = current_fetched_filters.get(int(folder_id))
if selected_filter_object and hasattr(selected_filter_object, 'include_peers') and selected_filter_object.include_peers:
yield f"Exporting included users/chats for folder '{folder_title}'..."
sanitized_title = sanitize_filename(folder_title)
# Ensure BASE_OUTPUT_DIR exists
os.makedirs(BASE_OUTPUT_DIR, exist_ok=True)
# Place CSV inside the base output dir
csv_filename = os.path.join(BASE_OUTPUT_DIR, f"folder_{sanitized_title}_users_chats.csv")
peers_exported_count = 0
try:
with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Type', 'ID', 'Username', 'Display Name', 'Full Name', 'Phone'])
for peer_input in selected_filter_object.include_peers:
try:
# Using get_input_entity to handle various peer types potentially more robustly
input_peer = await current_client.get_input_entity(peer_input)
# Then get the full entity details
entity = await current_client.get_entity(input_peer)
entity_type = type(entity).__name__
username = getattr(entity, 'username', '') or ''
display_name = getattr(entity, 'title', None) or getattr(entity, 'username', None) or getattr(entity, 'first_name', f"ID: {entity.id}")
if not display_name and hasattr(entity, 'first_name'): # Handle users better
display_name = entity.first_name + (f" {entity.last_name}" if getattr(entity, 'last_name', None) else "")
full_name = (getattr(entity, 'first_name', '') or '') + ' ' + (getattr(entity, 'last_name', '') or '')
full_name = full_name.strip()
phone = getattr(entity, 'phone', '') or ''
writer.writerow([
entity_type,
entity.id,
username,
display_name,
full_name if full_name else display_name, # Use display_name if full_name is empty
phone
])
peers_exported_count += 1
# Yield progress? Maybe too noisy.
# yield f" - Exported: {display_name}"
except ValueError:
yield f" - Warning: Could not resolve peer: {peer_input}. Might be inaccessible."
except FloodWaitError as fwe_peer:
yield f" ! Rate limit hit exporting peer {peer_input}. Waiting {fwe_peer.seconds} seconds..."
await asyncio.sleep(fwe_peer.seconds + 2)
yield f" ! Retrying peer export for {peer_input}..."
# Simple retry logic (could be improved)
try:
input_peer = await current_client.get_input_entity(peer_input)
entity = await current_client.get_entity(input_peer)
# ... (repeat export logic - better to refactor into a function)
yield f" - Successfully exported after wait: {getattr(entity, 'title', entity.id)}"
except Exception as e_retry:
yield f" - Warning: Still could not process peer {peer_input} after retry: {e_retry}"
except Exception as e_peer:
yield f" - Warning: Error processing peer {peer_input}: {e_peer}"
if peers_exported_count > 0:
yield f"Successfully exported details for {peers_exported_count} users/chats to {csv_filename}"
else:
yield f"No exportable users/chats found or processed in folder '{folder_title}'. CSV not created or is empty."
# No need to delete, as we only create if count > 0 (or handle empty file if created initially)
if os.path.exists(csv_filename):
try:
# Check if file is truly empty (besides header)
if os.path.getsize(csv_filename) <= 100: # Allow for header size
os.remove(csv_filename)
yield f"Removed empty/header-only file: {csv_filename}"
except OSError:
pass # Ignore if removal fails
except IOError as e_csv:
yield f"Error writing CSV file {csv_filename}: {e_csv}"
elif selected_filter_object:
yield f"Folder '{folder_title}' does not seem to contain specific included peers."
else:
yield f"Could not find filter details for folder ID {folder_id}."
async def download_messages_for_folder(current_client, folder_id, folder_title, current_fetched_filters, message_limit_str):
"""Downloads messages for all peers included in the selected folder."""
if not current_client or not folder_id or not current_fetched_filters:
yield "Client not ready, folder not selected, or filter data missing."
return
selected_filter_object = current_fetched_filters.get(int(folder_id))
if not selected_filter_object or not hasattr(selected_filter_object, 'include_peers') or not selected_filter_object.include_peers:
yield f"No specific peers found to download for folder '{folder_title}'. Export skipped or folder doesn't define included peers."
return
try:
message_limit = int(message_limit_str) if message_limit_str and message_limit_str.isdigit() else None
limit_text = f" (Limit: {message_limit})" if message_limit else " (Limit: All)"
yield f"Starting download for folder '{folder_title}'{limit_text}..."
except ValueError:
yield "Invalid Message Limit. Please enter a number or leave blank for all."
message_limit = None
limit_text = " (Limit: All)"
yield f"Proceeding with Limit: All..."
sanitized_folder_title = sanitize_filename(folder_title)
folder_output_dir = os.path.join(BASE_OUTPUT_DIR, sanitized_folder_title)
os.makedirs(folder_output_dir, exist_ok=True)
yield f"Output directory: {folder_output_dir}"
download_count = 0
error_count = 0
for peer_input in selected_filter_object.include_peers:
entity = None
entity_display_name = f"Peer {peer_input}" # Default name
try:
# Resolve peer first
input_peer = await current_client.get_input_entity(peer_input)
entity = await current_client.get_entity(input_peer)
entity_display_name = getattr(entity, 'title', None) or getattr(entity, 'username', None) or getattr(entity, 'first_name', f"ID: {entity.id}")
if not entity_display_name and hasattr(entity, 'first_name'):
entity_display_name = entity.first_name + (f" {entity.last_name}" if getattr(entity, 'last_name', None) else "")
sanitized_entity_name = sanitize_filename(entity_display_name if entity_display_name else f"chat_{entity.id}")
output_filename = f"{sanitized_entity_name}_messages.txt"
output_filepath = os.path.join(folder_output_dir, output_filename)
yield f" -> Downloading messages for: {entity_display_name} (ID: {entity.id})..."
messages_data = []
msg_count = 0
download_start_time = time.time()
async for message in current_client.iter_messages(entity, limit=message_limit):
sender = await message.get_sender()
sender_name = "Unknown/Channel"
sender_id_str = "N/A"
if sender:
sender_id_str = str(sender.id)
sender_name = getattr(sender, 'username', None) or \
(getattr(sender, 'first_name', '') + (' ' + getattr(sender, 'last_name', '') if getattr(sender, 'last_name', None) else '')).strip() or \
f"User ID {sender.id}" # Fallback sender name
timestamp_str = "Invalid Date"
if message.date:
# Convert to local timezone for display if desired, otherwise keep UTC
# local_dt = message.date.astimezone()
# timestamp_str = local_dt.strftime('%Y-%m-%d %H:%M:%S %Z')
timestamp_str = message.date.strftime('%Y-%m-%d %H:%M:%S UTC')
text = message.text or "[Media/Other]"
# Include message ID for reference
message_info = f"[{timestamp_str} MID: {message.id}] {sender_name} (UID: {sender_id_str}):\n{text}\n{'-'*20}"
messages_data.append(message_info)
msg_count += 1
# Progress update within a chat download (optional, can be slow)
# if msg_count % 100 == 0:
# yield f" Downloaded {msg_count} messages for {entity_display_name}..."
download_end_time = time.time()
duration = download_end_time - download_start_time
if messages_data:
yield f" -> Finished downloading {len(messages_data)} messages for {entity_display_name} in {duration:.2f}s."
yield f" -> Saving messages to {output_filepath}..."
try:
with open(output_filepath, 'w', encoding='utf-8') as f:
f.write(f"Messages from: {entity_display_name}\n")
f.write(f"Entity ID: {entity.id}\n")
f.write(f"Total messages downloaded (limit={message_limit if message_limit else 'All'}): {len(messages_data)}\n")
f.write("="*40 + "\n\n")
for msg_info in reversed(messages_data): # Save oldest first
f.write(msg_info + '\n\n')
yield f" -> Messages for {entity_display_name} saved successfully."
download_count += 1
except IOError as e_write:
yield f" ! Error writing file {output_filepath}: {e_write}"
error_count += 1
else:
yield f" -> No messages found or downloaded for {entity_display_name}."
# Optionally delete empty file placeholder if created
except FloodWaitError as fwe:
yield f" ! Rate limit hit for {entity_display_name}. Waiting {fwe.seconds} seconds..."
await asyncio.sleep(fwe.seconds + 5) # Wait a bit longer
yield f" ! Skipping further downloads for {entity_display_name} in this run due to rate limit."
error_count += 1
except (ValueError, TypeError) as e_resolve: # Catch potential errors during entity resolution
yield f" ! Error processing entity {entity_display_name}: {e_resolve}"
yield " (Could be a channel you haven't joined, a deleted account, or other access issue)"
error_count += 1
except Exception as e:
entity_id_str = getattr(entity, 'id', 'N/A')
yield f" ! An unexpected error occurred downloading messages for {entity_display_name} (ID: {entity_id_str}): {e}"
error_count += 1
# import traceback
# traceback.print_exc() # For debugging
yield f"\n--- Download Complete for Folder '{folder_title}' ---"
yield f"Successfully downloaded message histories for {download_count} chats/users."
if error_count > 0:
yield f"Encountered errors for {error_count} chats/users."
yield f"Files saved in: {folder_output_dir}"
# --- Gradio Interface Definition ---
# Load initial config
initial_config = load_config()
with gr.Blocks() as demo:
gr.Markdown("# Telegram Chat Exporter")
# State variables
client_state = gr.State(None)
sent_code_state = gr.State(None)
auth_status_state = gr.State("NotConnected") # "NotConnected", "NeedCode", "NeedPassword", "Authorized", "Error"
fetched_filters_state = gr.State({})
folder_list_state = gr.State([]) # Store the list for the dropdown
with gr.Tabs():
with gr.TabItem("1. Connection"):
with gr.Row():
api_id_input = gr.Textbox(label="API ID", value=initial_config.get('api_id', ''), type="text")
api_hash_input = gr.Textbox(label="API Hash", value=initial_config.get('api_hash', ''), type="password")
phone_number_input = gr.Textbox(label="Phone Number (+1234567890)", value=initial_config.get('phone_number', ''), type="text")
connect_button = gr.Button("Connect / Authenticate", variant="primary")
with gr.Group(visible=False) as code_group:
gr.Markdown("Enter the code sent to your Telegram account.")
code_input = gr.Textbox(label="Verification Code", type="text")
submit_code_button = gr.Button("Submit Code")
with gr.Group(visible=False) as password_group:
gr.Markdown("Enter your Telegram 2FA Password.")
password_input = gr.Textbox(label="Password", type="password")
submit_password_button = gr.Button("Submit Password")
with gr.TabItem("2. Select Folder & Download"):
with gr.Row():
fetch_folders_button = gr.Button("Fetch Folders")
folder_dropdown = gr.Dropdown(label="Select Folder", choices=[], interactive=True)
with gr.Row():
message_limit_input = gr.Textbox(label="Message Limit per Chat (leave blank for all)", value="100", type="text") # Default to 100
with gr.Row():
export_peers_button = gr.Button("Export Users/Chats in Folder (CSV)")
#download_button = gr.Button("Download Messages for Folder", variant="primary")
# Add an invisible file component for download triggering
file_output = gr.File(label="Download CSV", visible=False)
output_log = gr.Textbox(label="Log Output", lines=15, interactive=False, autoscroll=True)
# --- Event Handlers ---
async def handle_connect(api_id, api_hash, phone):
"""Handles the connect button click."""
status_updates = []
new_client = None
new_sent_code = None
auth_status = "Error" # Default status
# Collect all yielded items
async for status in connect_and_authenticate(api_id, api_hash, phone):
status_updates.append(status)
# Process yields: last tuple is state, others are logs
final_state_tuple = None
log_output_list = []
for status in status_updates:
if isinstance(status, tuple) and len(status) == 4:
final_state_tuple = status # Keep track of the latest state tuple
elif isinstance(status, str):
log_output_list.append(status) # Collect log messages
# Ignore other types if any
# Unpack the final state tuple if found
if final_state_tuple:
new_client, new_sent_code, _, auth_status = final_state_tuple
else: # Handle cases where the generator might exit unexpectedly
log_output_list.append("Error: Authentication process did not yield final state.")
# Ensure client state reflects potential failure
new_client = None
new_sent_code = None
auth_status = "Error"
log_output = "\n".join(log_output_list)
# Update UI visibility based on auth_status
show_code = auth_status == "NeedCode"
show_password = auth_status == "NeedPassword"
return {
client_state: new_client,
sent_code_state: new_sent_code,
auth_status_state: auth_status,
output_log: log_output,
code_group: gr.update(visible=show_code),
password_group: gr.update(visible=show_password),
connect_button: gr.update(interactive=not (show_code or show_password)), # Disable connect btn when waiting
api_id_input: gr.update(interactive=not (show_code or show_password)),
api_hash_input: gr.update(interactive=not (show_code or show_password)),
phone_number_input: gr.update(interactive=not (show_code or show_password)),
}
connect_button.click(
handle_connect,
inputs=[api_id_input, api_hash_input, phone_number_input],
outputs=[client_state, sent_code_state, auth_status_state, output_log, code_group, password_group,
connect_button, api_id_input, api_hash_input, phone_number_input] # Add button/inputs to outputs
)
async def handle_submit_code(current_client, current_sent_code, phone, code):
"""Handles the submit code button click."""
status_updates = []
new_client = current_client # Start with current client
auth_status = "Error" # Default status
async for status in submit_telegram_code(current_client, current_sent_code, phone, code):
status_updates.append(status)
final_state_tuple = None
log_output_list = []
for status in status_updates:
if isinstance(status, tuple) and len(status) == 3:
final_state_tuple = status
elif isinstance(status, str):
log_output_list.append(str(status))
if final_state_tuple:
# Unpack state, note the middle element (sent_code_info) is ignored here, use current_sent_code below
new_client, _, auth_status = final_state_tuple
else:
log_output_list.append("Error: Code submission process did not yield final state.")
# Keep client as is? Or nullify? Let's assume it might still be valid if Error/NeedCode
auth_status = "Error" # Or maybe NeedCode? Depends on where error occurred. Let's default to Error.
log_output = "\n".join(log_output_list)
show_code = auth_status == "NeedCode"
show_password = auth_status == "NeedPassword"
# Enable connection fields only if authorized or back to square one (error state might require reconnect)
enable_connect_fields = auth_status == "Authorized" or auth_status == "Error"
return {
client_state: new_client,
# Keep sent_code_info if we're still in NeedCode, otherwise clear it
sent_code_state: current_sent_code if auth_status == "NeedCode" else None,
auth_status_state: auth_status,
output_log: log_output,
code_group: gr.update(visible=show_code),
password_group: gr.update(visible=show_password),
code_input: "" ,# Clear code input
# Update connect button interactivity
connect_button: gr.update(interactive=enable_connect_fields),
api_id_input: gr.update(interactive=enable_connect_fields),
api_hash_input: gr.update(interactive=enable_connect_fields),
phone_number_input: gr.update(interactive=enable_connect_fields),
}
submit_code_button.click(
handle_submit_code,
inputs=[client_state, sent_code_state, phone_number_input, code_input],
outputs=[client_state, sent_code_state, auth_status_state, output_log, code_group, password_group, code_input,
connect_button, api_id_input, api_hash_input, phone_number_input] # Add connect fields to outputs
)
async def handle_submit_password(current_client, password):
"""Handles the submit password button click."""
status_updates = []
new_client = current_client
auth_status = "Error"
async for status in submit_telegram_password(current_client, password):
status_updates.append(status)
final_state_tuple = None
log_output_list = []
for status in status_updates:
if isinstance(status, tuple) and len(status) == 2:
final_state_tuple = status
elif isinstance(status, str):
log_output_list.append(str(status))
if final_state_tuple:
new_client, auth_status = final_state_tuple
else:
log_output_list.append("Error: Password submission process did not yield final state.")
auth_status = "Error"
log_output = "\n".join(log_output_list)
show_password = auth_status == "NeedPassword"
# Enable connection fields only if authorized or error requires reconnect
enable_connect_fields = auth_status == "Authorized" or auth_status == "Error"
return {
client_state: new_client,
auth_status_state: auth_status,
output_log: log_output,
password_group: gr.update(visible=show_password),
password_input: "", # Clear password input
# Update connect button interactivity
connect_button: gr.update(interactive=enable_connect_fields),
api_id_input: gr.update(interactive=enable_connect_fields),
api_hash_input: gr.update(interactive=enable_connect_fields),
phone_number_input: gr.update(interactive=enable_connect_fields),
}
submit_password_button.click(
handle_submit_password,
inputs=[client_state, password_input],
outputs=[client_state, auth_status_state, output_log, password_group, password_input,
connect_button, api_id_input, api_hash_input, phone_number_input] # Add connect fields to outputs
)
async def handle_fetch_folders(current_client, current_auth_status):
"""Handles the fetch folders button click."""
if current_auth_status != "Authorized":
# Return directly as this isn't an async generator call issue
return {
output_log: "Please connect and authorize first.",
folder_dropdown: gr.update(choices=[], value=None), # Clear dropdown
fetched_filters_state: {}, # Clear filters state
folder_list_state: [], # Clear folder list state
}
status_updates = []
folders = []
new_fetched_filters = {}
status_msg = "Error" # Default
async for status in get_folders(current_client):
status_updates.append(status)
final_state_tuple = None
log_output_list = []
for status in status_updates:
if isinstance(status, tuple) and len(status) == 3:
final_state_tuple = status
elif isinstance(status, str):
log_output_list.append(str(status))
if final_state_tuple:
folders, new_fetched_filters, status_msg = final_state_tuple
# Add the status message to the log if it wasn't already yielded as a string
if status_msg not in log_output_list and status_msg != "Folders fetched.": # Avoid redundant success message if already logged
log_output_list.append(status_msg)
else:
log_output_list.append("Error: Folder fetching process did not yield final state.")
# Ensure states are cleared on error
folders = []
new_fetched_filters = {}
log_output = "\n".join(log_output_list)
# Ensure folders is a list of tuples/lists suitable for Dropdown
valid_folders = [f for f in folders if isinstance(f, (tuple, list)) and len(f) >= 2] # Check length >= 2
return {
output_log: log_output,
fetched_filters_state: new_fetched_filters,
folder_list_state: valid_folders, # Store the valid list
folder_dropdown: gr.update(choices=valid_folders, value=valid_folders[0][1] if valid_folders else None, interactive=True) # Update choices and select first if available
}
fetch_folders_button.click(
handle_fetch_folders,
inputs=[client_state, auth_status_state],
outputs=[output_log, fetched_filters_state, folder_list_state, folder_dropdown]
)
async def handle_export_peers(current_client, auth_status, folder_id, folder_list, current_filters):
"""Handles the export peers button click. Yields logs and the final CSV file path."""
# Clear previous file output first
yield {output_log: "Starting export...", file_output: None}
if auth_status != "Authorized":
yield {output_log: "Please connect and authorize first."}
return
if not folder_id:
yield {output_log: "Please fetch and select a folder first."}
return
# Find the display title from the folder_list state
folder_title = "Selected Folder" # Default
selected_folder_info = None
for display, f_id in folder_list:
if str(f_id) == str(folder_id):
selected_folder_info = (display, f_id)
# Extract title before the " (ID: ...)" part more robustly
match = re.match(r"^(.*?)\s*\(ID:\s*\d+\)$", display)
folder_title = match.group(1).strip() if match else display # Fallback if format doesn't match
break
if not selected_folder_info:
yield {output_log: f"Could not find details for selected folder ID: {folder_id}"}
return
# Use the core export logic function
# This function will yield status strings and potentially the file path at the end
status_updates = []
final_csv_path = None
try:
async for status_or_path in export_folder_peers(current_client, folder_id, folder_title, current_filters):
if isinstance(status_or_path, str) and os.path.exists(status_or_path) and status_or_path.endswith('.csv'):
# Assume this is the file path yield
final_csv_path = status_or_path
status_updates.append(f"CSV generated: {os.path.basename(final_csv_path)}") # Add short msg to log
# Don't yield the path to the log, yield it to the file component below
elif isinstance(status_or_path, str):
status_updates.append(status_or_path)
yield {output_log: "\n".join(status_updates)} # Update log progressively
else:
# Handle unexpected yield type if necessary
status_updates.append(f"Unexpected status type: {type(status_or_path)}")
yield {output_log: "\n".join(status_updates)}
except Exception as e:
status_updates.append(f"An unexpected error occurred during export: {e}")
# Potentially log traceback here for debugging
yield {output_log: "\n".join(status_updates)}
# Ensure no file path is returned on error
final_csv_path = None
# Final update after loop finishes
if final_csv_path:
yield {output_log: "\n".join(status_updates), file_output: gr.update(value=final_csv_path, visible=True)} # Yield path to file output
else:
# Ensure log shows completion or error state without providing a file
if "error" not in status_updates[-1].lower() and "failed" not in status_updates[-1].lower():
status_updates.append("Export finished, but no CSV file was generated (e.g., no peers found or error saving).")
yield {output_log: "\n".join(status_updates), file_output: None}
# Modify the core export function slightly to yield the path as the *last* item on success
async def export_folder_peers(current_client, folder_id, folder_title, current_fetched_filters):
"""Exports peers, yields status strings, and finally yields the CSV file path on success."""
if not current_client or not folder_id or not current_fetched_filters:
yield "Client not ready, folder not selected, or filter data missing."
return
selected_filter_object = current_fetched_filters.get(int(folder_id))
csv_filename = None # Initialize
if selected_filter_object and hasattr(selected_filter_object, 'include_peers') and selected_filter_object.include_peers:
yield f"Exporting included users/chats for folder '{folder_title}'..."
sanitized_title = sanitize_filename(folder_title)
# Ensure BASE_OUTPUT_DIR exists
os.makedirs(BASE_OUTPUT_DIR, exist_ok=True)
# Place CSV inside the base output dir
csv_filename = os.path.join(BASE_OUTPUT_DIR, f"folder_{sanitized_title}_users_chats_{int(time.time())}.csv") # Add timestamp to avoid clashes
peers_exported_count = 0
try:
with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Type', 'ID', 'Username', 'Display Name', 'Full Name', 'Phone'])
peer_tasks = []
for peer_input in selected_filter_object.include_peers:
peer_tasks.append(process_peer_for_export(current_client, peer_input)) # Refactor processing logic
results = await asyncio.gather(*peer_tasks, return_exceptions=True)
for result in results:
if isinstance(result, Exception):
yield f" - Error processing a peer: {result}" # Log errors from gather
elif isinstance(result, dict) and 'error' in result:
yield f" - Warning: {result['error']}" # Log handled warnings/skips
elif isinstance(result, list):
writer.writerow(result)
peers_exported_count += 1
# else: ignore None results (e.g. from FloodWait recovery placeholder)
# After writing is complete
if peers_exported_count > 0:
yield f"Successfully processed details for {peers_exported_count} users/chats."
yield f"CSV file ready: {csv_filename}"
yield csv_filename # <<< YIELD FILE PATH ON SUCCESS
else:
yield f"No exportable users/chats found or processed successfully in folder '{folder_title}'."
# Clean up empty file
if csv_filename and os.path.exists(csv_filename):
try:
if os.path.getsize(csv_filename) <= 100: # Header only or empty
os.remove(csv_filename)
yield f"Removed empty file: {csv_filename}"
except OSError as e_rem:
yield f"Warning: Could not remove empty file {csv_filename}: {e_rem}"
except IOError as e_csv:
yield f"Error writing CSV file {csv_filename}: {e_csv}"
# Clean up potentially partially written file on error
if csv_filename and os.path.exists(csv_filename):
try:
os.remove(csv_filename)
yield f"Removed partially written file due to error: {csv_filename}"
except OSError as e_rem:
yield f"Warning: Could not remove file {csv_filename} after write error: {e_rem}"
except Exception as e_main:
yield f"An unexpected error occurred during CSV export: {e_main}"
# Clean up potentially partially written file on error
if csv_filename and os.path.exists(csv_filename):
try:
os.remove(csv_filename)
yield f"Removed partially written file due to error: {csv_filename}"
except OSError as e_rem:
yield f"Warning: Could not remove file {csv_filename} after error: {e_rem}"
elif selected_filter_object:
yield f"Folder '{folder_title}' does not seem to contain specific included peers to export."
else:
yield f"Could not find filter details for folder ID {folder_id}."
# No file path yielded if we reach here without success
# Helper for asyncio.gather in export_folder_peers
async def process_peer_for_export(current_client, peer_input):
"""Gets entity details for a single peer, handles errors."""
try:
input_peer = await current_client.get_input_entity(peer_input)
entity = await current_client.get_entity(input_peer)
entity_type = type(entity).__name__
username = getattr(entity, 'username', '') or ''
display_name = getattr(entity, 'title', None) or getattr(entity, 'username', None) or getattr(entity, 'first_name', f"ID: {entity.id}")
if not display_name and hasattr(entity, 'first_name'):
display_name = entity.first_name + (f" {entity.last_name}" if getattr(entity, 'last_name', None) else "")
full_name = (getattr(entity, 'first_name', '') or '') + ' ' + (getattr(entity, 'last_name', '') or '')
full_name = full_name.strip()
phone = getattr(entity, 'phone', '') or ''
return [ # Return data as list for CSV row
entity_type,
entity.id,
username,
display_name,
full_name if full_name else display_name,
phone
]
except ValueError:
return {'error': f"Could not resolve peer: {peer_input}. Might be inaccessible."}
except FloodWaitError as fwe_peer:
# Logged by the handler, maybe just return None or a placeholder?
# Yielding from here is complex with gather. Return error dict.
await asyncio.sleep(fwe_peer.seconds + 1) # Wait here as we can't yield easily
return {'error': f"Rate limit hit for peer {peer_input}. Waited {fwe_peer.seconds}s. Skipped in this batch."}
# Or retry logic could be added here, but makes it more complex
except Exception as e_peer:
return {'error': f"Error processing peer {peer_input}: {e_peer}"}
export_peers_button.click(
handle_export_peers,
inputs=[client_state, auth_status_state, folder_dropdown, folder_list_state, fetched_filters_state],
outputs=[output_log, file_output] # Send logs to log, file path to file component
)
async def handle_download(current_client, auth_status, folder_id, folder_list, current_filters, limit):
"""Handles the download button click."""
# Keep track of log messages
log_updates = []
def update_log(msg):
log_updates.append(msg)
return "\n".join(log_updates) # Return cumulative log
yield update_log("Starting download process...") # Initial message
if auth_status != "Authorized":
yield update_log("Please connect and authorize first.")
return
if not folder_id:
yield update_log("Please fetch and select a folder first.")
return
# Find the display title from the folder_list state
folder_title = "Selected Folder" # Default
selected_folder_info = None
for display, f_id in folder_list:
if str(f_id) == str(folder_id):
selected_folder_info = (display, f_id)
match = re.match(r"^(.*?)\s*\(ID:\s*\d+\)$", display)
folder_title = match.group(1).strip() if match else display
break
if not selected_folder_info:
yield update_log(f"Could not find details for selected folder ID: {folder_id}")
return
# Use the core download logic function which yields status updates
try:
async for status in download_messages_for_folder(current_client, folder_id, folder_title, current_filters, limit):
yield update_log(status) # Yield cumulative log as generator progresses
except Exception as e:
yield update_log(f"An unexpected error occurred during download initiation or iteration: {e}")
# Add traceback logging here if needed for debugging server-side
#download_button.click(
# handle_download,
# inputs=[client_state, auth_status_state, folder_dropdown, folder_list_state, fetched_filters_state, message_limit_input],
# outputs=[output_log] # Only output logs for this button
#)
# --- Main Execution ---
if __name__ == '__main__':
# Remove the old asyncio.run(main()) block
# Make sure BASE_OUTPUT_DIR exists
os.makedirs(BASE_OUTPUT_DIR, exist_ok=True)
print(f"Base output directory: {os.path.abspath(BASE_OUTPUT_DIR)}")
print("Launching Gradio interface...")
# Use share=True if you need to access it from other devices on your network
demo.launch(share=True)
print("Gradio interface closed.")