Initial commit
This commit is contained in:
commit
c22db9f777
5772
Cargo.lock
generated
Normal file
5772
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
46
Cargo.toml
Normal file
46
Cargo.toml
Normal file
@ -0,0 +1,46 @@
|
||||
[package]
|
||||
name = "iroh_sync"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
# Main Iroh crate - use the latest stable version
|
||||
iroh = "0.28"
|
||||
|
||||
# Async runtime and utilities
|
||||
tokio = { version = "1.35", features = ["full"] }
|
||||
tokio-stream = { version = "0.1", features = ["net"] }
|
||||
futures-lite = "2.0"
|
||||
futures-util = "0.3"
|
||||
async-trait = "0.1"
|
||||
|
||||
# Error handling and serialization
|
||||
anyhow = "1.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
bytes = "1.5"
|
||||
|
||||
# File watching
|
||||
notify = "6.1"
|
||||
|
||||
# CLI and logging
|
||||
clap = { version = "4.4", features = ["derive"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
# Other utilities
|
||||
indicatif = "0.17"
|
||||
uuid = { version = "1.0", features = ["v4"] }
|
||||
|
||||
#web dependencies
|
||||
warp = "0.3"
|
||||
tokio-util = { version = "0.7", features = ["io"] }
|
||||
|
||||
|
||||
[[bin]]
|
||||
name = "iroh_sync"
|
||||
path = "src/main.rs"
|
||||
|
||||
[[example]]
|
||||
name = "simple_sync"
|
||||
path = "examples/simple_sync.rs"
|
4
Readme.md
Normal file
4
Readme.md
Normal file
@ -0,0 +1,4 @@
|
||||
Run: Cargo run --release <path-to-folder>
|
||||
Web Interface:
|
||||
Local: http://localhost:3030
|
||||
Mobile: http://YOUR_PC_IP:3030
|
407
src/main.rs
Normal file
407
src/main.rs
Normal file
@ -0,0 +1,407 @@
|
||||
mod sync_dir;
|
||||
|
||||
use std::{env, fs, io, thread, time};
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{Read, stdin, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use futures_lite::AsyncReadExt;
|
||||
use tokio_stream::{Stream, StreamExt};
|
||||
use anyhow;
|
||||
use std::time::Duration;
|
||||
use iroh::base::node_addr::AddrInfoOptions;
|
||||
use iroh::client::Doc;
|
||||
use iroh::client::docs::{LiveEvent, ShareMode};
|
||||
use iroh::docs::store::Query;
|
||||
use iroh::node::Node;
|
||||
use tokio::sync::Mutex;
|
||||
use std::sync::mpsc::{channel, TryRecvError};
|
||||
use iroh::blobs::store::fs::Store;
|
||||
use iroh::docs::{Author, AuthorId, ContentStatus};
|
||||
use iroh::net::key;
|
||||
use iroh::node;
|
||||
use notify::{Event, EventKind, RecursiveMode, Watcher, RecommendedWatcher};
|
||||
use crate::sync_dir::SyncDir;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
// Initialize logging
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env()
|
||||
.add_directive("info".parse().unwrap()))
|
||||
.init();
|
||||
|
||||
let args: Vec<String> = env::args().skip(1).collect();
|
||||
|
||||
// Check if user wants help
|
||||
if args.is_empty() || args[0] == "--help" || args[0] == "-h" {
|
||||
println!("Usage: {} <sync-directory> [ticket] [--web-port PORT] [--skip-diagnostics]", env::args().next().unwrap());
|
||||
println!(" sync-directory: Directory to sync");
|
||||
println!(" ticket: Optional ticket to connect to existing document");
|
||||
println!(" --web-port PORT: Port for web interface (default: 3030)");
|
||||
println!(" --skip-diagnostics: Skip the initial diagnostic checks");
|
||||
println!("\nWeb interface will be available at:");
|
||||
println!(" Local: http://localhost:PORT");
|
||||
println!(" Mobile: http://YOUR_PC_IP:PORT");
|
||||
println!("\nExample: {} ./my-sync-folder --web-port 8080", env::args().next().unwrap());
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let base_path = env::current_dir().unwrap().join(args[0].parse::<String>().unwrap());
|
||||
println!("📁 BASE_PATH: {:?}", base_path);
|
||||
|
||||
// Check if directory exists
|
||||
if !base_path.exists() {
|
||||
println!("❌ ERROR: Directory does not exist: {:?}", base_path);
|
||||
println!("Creating directory...");
|
||||
fs::create_dir_all(&base_path)?;
|
||||
println!("✅ Directory created!");
|
||||
}
|
||||
|
||||
// Parse command line arguments
|
||||
let mut ticket_arg = None;
|
||||
let mut web_port = 3030u16;
|
||||
let mut skip_diagnostics = false;
|
||||
|
||||
let mut i = 1;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--web-port" => {
|
||||
if i + 1 < args.len() {
|
||||
web_port = args[i + 1].parse::<u16>().unwrap_or(3030);
|
||||
i += 2;
|
||||
} else {
|
||||
println!("⚠️ Warning: --web-port requires a port number, using default 3030");
|
||||
i += 1;
|
||||
}
|
||||
},
|
||||
"--skip-diagnostics" => {
|
||||
skip_diagnostics = true;
|
||||
i += 1;
|
||||
},
|
||||
arg if !arg.starts_with("--") && ticket_arg.is_none() => {
|
||||
ticket_arg = Some(arg.to_string());
|
||||
i += 1;
|
||||
},
|
||||
_ => {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("🔧 Creating SyncDir...");
|
||||
|
||||
// Create SyncDir
|
||||
let sync_dir = if let Some(ticket) = ticket_arg {
|
||||
println!("🎫 Using provided ticket: {}", &ticket[..50.min(ticket.len())]); // Show first 50 chars
|
||||
SyncDir::new(base_path.clone(), Some(ticket)).await?
|
||||
} else {
|
||||
println!("📄 Creating new document (no ticket provided)");
|
||||
SyncDir::new(base_path.clone(), None).await?
|
||||
};
|
||||
|
||||
println!("✅ SyncDir created successfully!");
|
||||
println!("🆔 Node ID: {}", sync_dir.node_id());
|
||||
println!("📄 Namespace: {}", sync_dir.namespace_id().await?);
|
||||
|
||||
let sync_dir = Arc::new(Mutex::new(sync_dir));
|
||||
|
||||
println!("📂 Loading local files...");
|
||||
let sync_dir_clone = Arc::clone(&sync_dir);
|
||||
{
|
||||
let sync_dir_lock = sync_dir_clone.lock().await;
|
||||
(*sync_dir_lock).load_local_files().await?;
|
||||
}
|
||||
println!("✅ Local files loaded!");
|
||||
|
||||
// Run diagnostic checks unless skipped
|
||||
if !skip_diagnostics {
|
||||
println!("🔍 Running diagnostic checks...");
|
||||
let sync_dir_lock = sync_dir_clone.lock().await;
|
||||
|
||||
// Check for conflicts
|
||||
(*sync_dir_lock).check_entry_conflicts().await?;
|
||||
|
||||
// Comprehensive listing
|
||||
(*sync_dir_lock).list_all_entries_detailed().await?;
|
||||
|
||||
// Test adding a specific missing file (if it exists)
|
||||
let test_file_path = base_path.join("emptymails/INBOX/new/email_369");
|
||||
if test_file_path.exists() {
|
||||
(*sync_dir_lock).test_add_missing_file("email_369").await?;
|
||||
}
|
||||
|
||||
// Show debug contents
|
||||
println!("📋 Document contents:");
|
||||
(*sync_dir_lock).debug_contents().await?;
|
||||
|
||||
println!("🔧 Adding all missing files...");
|
||||
(*sync_dir_lock).add_missing_files().await?;
|
||||
|
||||
println!("📊 Comparing disk files with document entries...");
|
||||
(*sync_dir_lock).compare_disk_vs_document().await?;
|
||||
|
||||
// Show final debug contents
|
||||
println!("📋 Final document contents:");
|
||||
(*sync_dir_lock).debug_contents().await?;
|
||||
|
||||
drop(sync_dir_lock);
|
||||
println!("✅ Diagnostics complete!");
|
||||
} else {
|
||||
println!("⏩ Skipping diagnostics (--skip-diagnostics flag used)");
|
||||
}
|
||||
|
||||
// Start web interface
|
||||
println!("🌐 Starting web interface on port {}...", web_port);
|
||||
let sync_dir_web = Arc::clone(&sync_dir);
|
||||
let web_handle = tokio::spawn(async move {
|
||||
if let Err(e) = crate::sync_dir::start_web_interface(sync_dir_web, web_port).await {
|
||||
eprintln!("❌ Web interface error: {}", e);
|
||||
}
|
||||
});
|
||||
|
||||
// Subscribe to document events
|
||||
println!("📡 Subscribing to document events...");
|
||||
let mut stream = {
|
||||
let lock = sync_dir.lock().await;
|
||||
lock.subscribe().await?
|
||||
};
|
||||
println!("✅ Subscribed to document events!");
|
||||
|
||||
// Get info for startup summary
|
||||
let (node_id_short, namespace_short, folder_name) = {
|
||||
let lock = sync_dir.lock().await;
|
||||
let node_id = lock.node_id().to_string();
|
||||
let namespace = lock.namespace_id().await?.to_string();
|
||||
let folder = base_path.file_name().unwrap_or_default().to_string_lossy().to_string();
|
||||
(node_id[..8].to_string(), namespace[..8].to_string(), folder)
|
||||
};
|
||||
|
||||
// Print startup summary
|
||||
println!("\n╔══════════════════════════════════════╗");
|
||||
println!("║ 🔄 IROH FILE SYNC ACTIVE ║");
|
||||
println!("╠══════════════════════════════════════╣");
|
||||
println!("║ 🌐 Web Interface: ║");
|
||||
println!("║ Local: http://localhost:{} ║", web_port);
|
||||
println!("║ Mobile: http://YOUR_PC_IP:{} ║", web_port);
|
||||
println!("║ ║");
|
||||
println!("║ 📁 Sync Folder: {:20} ║", folder_name);
|
||||
println!("║ 🆔 Node ID: {}... ║", node_id_short);
|
||||
println!("║ 📄 Document: {}... ║", namespace_short);
|
||||
println!("║ ║");
|
||||
println!("║ 💡 Tips: ║");
|
||||
println!("║ • Find your PC IP: ipconfig ║");
|
||||
println!("║ • Type 'q' + Enter to quit ║");
|
||||
println!("║ • Generate tickets in web UI ║");
|
||||
println!("╚══════════════════════════════════════╝");
|
||||
println!();
|
||||
|
||||
// Handle document events
|
||||
let sync_dir_clone_stream = Arc::clone(&sync_dir);
|
||||
let stream_task = tokio::spawn(async move {
|
||||
while let Some(item) = stream.next().await {
|
||||
match item {
|
||||
Ok(value) => {
|
||||
println!("📡 Remote event: {:?}", value);
|
||||
match value {
|
||||
LiveEvent::InsertRemote { content_status, entry, .. } => {
|
||||
if content_status == ContentStatus::Complete {
|
||||
let sync_dir_lock = sync_dir_clone_stream.lock().await;
|
||||
if let Err(e) = (*sync_dir_lock).write_remote_entry(entry.clone()).await {
|
||||
eprintln!("❌ Failed to write remote entry: {}", e);
|
||||
}
|
||||
drop(sync_dir_lock);
|
||||
} else {
|
||||
let sync_dir_lock = sync_dir_clone_stream.lock().await;
|
||||
if let Err(e) = (*sync_dir_lock).handle_pending_entry(entry.clone()).await {
|
||||
eprintln!("❌ Failed to handle pending entry: {}", e);
|
||||
}
|
||||
drop(sync_dir_lock);
|
||||
}
|
||||
}
|
||||
LiveEvent::ContentReady { .. } => {
|
||||
let sync_dir_lock = sync_dir_clone_stream.lock().await;
|
||||
if let Err(e) = (*sync_dir_lock).process_pending_entries().await {
|
||||
eprintln!("❌ Failed to process pending entries: {}", e);
|
||||
}
|
||||
drop(sync_dir_lock);
|
||||
}
|
||||
LiveEvent::PendingContentReady => {
|
||||
let sync_dir_lock = sync_dir_clone_stream.lock().await;
|
||||
if let Err(e) = (*sync_dir_lock).process_pending_entries().await {
|
||||
eprintln!("❌ Failed to process pending entries: {}", e);
|
||||
}
|
||||
drop(sync_dir_lock);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Err(e) => eprintln!("❌ Stream error: {}", e),
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// File system watcher
|
||||
let sync_dir_clone_watcher = Arc::clone(&sync_dir);
|
||||
let watcher_base_path = base_path.clone();
|
||||
let watcher_task = tokio::spawn(async move {
|
||||
println!("👀 Starting file system watcher...");
|
||||
let (tx, rx) = channel();
|
||||
let mut watcher = RecommendedWatcher::new(
|
||||
move |res: Result<Event, notify::Error>| {
|
||||
if let Ok(event) = res {
|
||||
let _ = tx.send(event);
|
||||
}
|
||||
},
|
||||
notify::Config::default()
|
||||
).unwrap();
|
||||
|
||||
if let Err(e) = watcher.watch(&watcher_base_path, RecursiveMode::Recursive) {
|
||||
eprintln!("❌ Failed to start file watcher: {}", e);
|
||||
return;
|
||||
}
|
||||
|
||||
loop {
|
||||
match rx.try_recv() {
|
||||
Ok(event) => {
|
||||
println!("📁 File event: {:?}", event);
|
||||
let sync_dir_lock = sync_dir_clone_watcher.lock().await;
|
||||
|
||||
for path in event.paths {
|
||||
match event.kind {
|
||||
EventKind::Create(_) => {
|
||||
if let Err(e) = (*sync_dir_lock).handle_local_change(path.clone()).await {
|
||||
if !e.to_string().contains("newer entry exists") {
|
||||
eprintln!("❌ Failed to handle file creation {:?}: {}", path, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
EventKind::Modify(_) => {
|
||||
if let Err(e) = (*sync_dir_lock).handle_local_change(path.clone()).await {
|
||||
if !e.to_string().contains("newer entry exists") {
|
||||
eprintln!("❌ Failed to handle file modification {:?}: {}", path, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
EventKind::Remove(_) => {
|
||||
if let Err(e) = (*sync_dir_lock).handle_local_delete(path.clone()).await {
|
||||
eprintln!("❌ Failed to handle file deletion {:?}: {}", path, e);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
drop(sync_dir_lock);
|
||||
}
|
||||
Err(e) => match e {
|
||||
TryRecvError::Empty => {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
TryRecvError::Disconnected => {
|
||||
println!("📁 File watcher disconnected");
|
||||
break;
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Enhanced input handling with commands
|
||||
println!("🎮 Available commands:");
|
||||
println!(" q - Quit the application");
|
||||
println!(" s - Show current status");
|
||||
println!(" d - Show debug info");
|
||||
println!(" f - Force refresh files");
|
||||
println!(" h - Show help");
|
||||
println!();
|
||||
|
||||
let mut input = String::new();
|
||||
loop {
|
||||
print!("iroh-sync> ");
|
||||
io::stdout().flush().unwrap();
|
||||
|
||||
input.clear();
|
||||
match io::stdin().read_line(&mut input) {
|
||||
Ok(0) => break, // EOF
|
||||
Ok(_) => {
|
||||
match input.trim() {
|
||||
"q" | "quit" | "exit" => {
|
||||
println!("\n🛑 Shutting down...");
|
||||
break;
|
||||
}
|
||||
"s" | "status" => {
|
||||
let lock = sync_dir.lock().await;
|
||||
match lock.get_sync_status().await {
|
||||
Ok(status) => {
|
||||
println!("📊 Status:");
|
||||
println!(" 🆔 Node ID: {}", status.node_id);
|
||||
println!(" 📄 Document: {}", status.namespace_id);
|
||||
println!(" 👥 Connected Peers: {}", status.connected_peers);
|
||||
println!(" 📁 Files: {}", status.total_files);
|
||||
println!(" 📂 Directories: {}", status.total_directories);
|
||||
}
|
||||
Err(e) => println!("❌ Failed to get status: {}", e),
|
||||
}
|
||||
drop(lock);
|
||||
}
|
||||
"d" | "debug" => {
|
||||
let lock = sync_dir.lock().await;
|
||||
if let Err(e) = lock.debug_contents().await {
|
||||
println!("❌ Failed to show debug info: {}", e);
|
||||
}
|
||||
drop(lock);
|
||||
}
|
||||
"f" | "refresh" => {
|
||||
println!("🔄 Force refreshing files...");
|
||||
let lock = sync_dir.lock().await;
|
||||
if let Err(e) = lock.load_local_files().await {
|
||||
println!("❌ Failed to refresh files: {}", e);
|
||||
} else {
|
||||
println!("✅ Files refreshed!");
|
||||
}
|
||||
drop(lock);
|
||||
}
|
||||
"h" | "help" => {
|
||||
println!("🎮 Available commands:");
|
||||
println!(" q, quit, exit - Quit the application");
|
||||
println!(" s, status - Show current sync status");
|
||||
println!(" d, debug - Show debug information");
|
||||
println!(" f, refresh - Force refresh local files");
|
||||
println!(" h, help - Show this help");
|
||||
}
|
||||
"" => {
|
||||
// Empty line, just continue
|
||||
}
|
||||
cmd => {
|
||||
println!("❓ Unknown command: '{}'. Type 'h' for help.", cmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("❌ Failed to read input: {}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
println!("🧹 Cleaning up...");
|
||||
|
||||
// Cancel tasks
|
||||
stream_task.abort();
|
||||
watcher_task.abort();
|
||||
web_handle.abort();
|
||||
|
||||
// Shutdown sync system
|
||||
let sync_dir_clone = Arc::clone(&sync_dir);
|
||||
let sync_dir_lock = sync_dir_clone.lock().await;
|
||||
if let Err(e) = (*sync_dir_lock).shutdown().await {
|
||||
eprintln!("❌ Shutdown error: {}", e);
|
||||
}
|
||||
drop(sync_dir_lock);
|
||||
|
||||
println!("✅ Shutdown complete! Goodbye!");
|
||||
Ok(())
|
||||
}
|
1874
src/sync_dir.rs
Normal file
1874
src/sync_dir.rs
Normal file
File diff suppressed because it is too large
Load Diff
687
web/index.html
Normal file
687
web/index.html
Normal file
@ -0,0 +1,687 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
||||
<title>Iroh File Sync</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
padding: 10px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 420px;
|
||||
margin: 0 auto;
|
||||
background: white;
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 20px 40px rgba(0,0,0,0.1);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.header {
|
||||
background: linear-gradient(45deg, #667eea, #764ba2);
|
||||
color: white;
|
||||
padding: 25px 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
font-size: 28px;
|
||||
font-weight: 700;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.status {
|
||||
font-size: 14px;
|
||||
opacity: 0.9;
|
||||
background: rgba(255,255,255,0.1);
|
||||
padding: 8px 15px;
|
||||
border-radius: 20px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.content {
|
||||
padding: 25px 20px;
|
||||
}
|
||||
|
||||
.section {
|
||||
margin-bottom: 30px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 15px;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.section h3 {
|
||||
color: #333;
|
||||
margin-bottom: 15px;
|
||||
font-size: 18px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.input-group {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
input[type="text"] {
|
||||
width: 100%;
|
||||
padding: 15px;
|
||||
border: 2px solid #e1e5e9;
|
||||
border-radius: 12px;
|
||||
font-size: 16px;
|
||||
transition: all 0.3s;
|
||||
}
|
||||
|
||||
input[type="text"]:focus {
|
||||
outline: none;
|
||||
border-color: #667eea;
|
||||
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
|
||||
}
|
||||
|
||||
.btn {
|
||||
width: 100%;
|
||||
padding: 15px;
|
||||
background: linear-gradient(45deg, #667eea, #764ba2);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.btn:hover, .btn:active {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.btn.secondary {
|
||||
background: linear-gradient(45deg, #6c757d, #5a6268);
|
||||
}
|
||||
|
||||
.file-list {
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
border: 2px solid #e1e5e9;
|
||||
border-radius: 12px;
|
||||
background: white;
|
||||
}
|
||||
|
||||
.file-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 15px;
|
||||
border-bottom: 1px solid #e1e5e9;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.file-item:hover {
|
||||
background: #f8f9fa;
|
||||
}
|
||||
|
||||
.file-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.file-icon {
|
||||
width: 45px;
|
||||
height: 45px;
|
||||
border-radius: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-right: 15px;
|
||||
font-size: 20px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.file-icon.file {
|
||||
background: linear-gradient(45deg, #e3f2fd, #bbdefb);
|
||||
color: #1976d2;
|
||||
}
|
||||
|
||||
.file-icon.folder {
|
||||
background: linear-gradient(45deg, #fff3e0, #ffcc02);
|
||||
color: #f57c00;
|
||||
}
|
||||
|
||||
.file-info {
|
||||
flex-grow: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.file-name {
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
margin-bottom: 5px;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.file-size {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.file-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.btn-small {
|
||||
padding: 8px 12px;
|
||||
font-size: 12px;
|
||||
border-radius: 8px;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.btn-download {
|
||||
background: #28a745;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-download:hover {
|
||||
background: #218838;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
border-radius: 12px;
|
||||
margin-bottom: 15px;
|
||||
font-weight: 500;
|
||||
animation: slideIn 0.3s ease;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from { transform: translateY(-10px); opacity: 0; }
|
||||
to { transform: translateY(0); opacity: 1; }
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background: linear-gradient(45deg, #d4edda, #c3e6cb);
|
||||
color: #155724;
|
||||
border: 2px solid #a5d6a7;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background: linear-gradient(45deg, #f8d7da, #f1b0b7);
|
||||
color: #721c24;
|
||||
border: 2px solid #ef9a9a;
|
||||
}
|
||||
|
||||
.loading {
|
||||
text-align: center;
|
||||
padding: 30px;
|
||||
color: #666;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.upload-area {
|
||||
border: 3px dashed #667eea;
|
||||
border-radius: 15px;
|
||||
padding: 40px 20px;
|
||||
text-align: center;
|
||||
background: linear-gradient(45deg, #f8f9ff, #f0f4ff);
|
||||
margin-bottom: 20px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.upload-area:hover {
|
||||
background: linear-gradient(45deg, #f0f4ff, #e6f3ff);
|
||||
border-color: #5a67d8;
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.upload-area.dragover {
|
||||
background: linear-gradient(45deg, #e6f3ff, #dbeafe);
|
||||
border-color: #3182ce;
|
||||
transform: scale(1.02);
|
||||
}
|
||||
|
||||
.upload-icon {
|
||||
font-size: 48px;
|
||||
margin-bottom: 15px;
|
||||
color: #667eea;
|
||||
}
|
||||
|
||||
.upload-text {
|
||||
font-size: 16px;
|
||||
color: #4a5568;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.upload-hint {
|
||||
font-size: 14px;
|
||||
color: #718096;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.connection-status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: #28a745;
|
||||
}
|
||||
|
||||
.status-dot.disconnected {
|
||||
background: #dc3545;
|
||||
}
|
||||
|
||||
.ticket-display {
|
||||
background: #f8f9fa;
|
||||
border: 2px solid #e1e5e9;
|
||||
border-radius: 12px;
|
||||
padding: 15px;
|
||||
margin-top: 15px;
|
||||
font-family: monospace;
|
||||
font-size: 14px;
|
||||
word-break: break-all;
|
||||
max-height: 120px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.stats {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 15px;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
.stat-item {
|
||||
background: white;
|
||||
padding: 15px;
|
||||
border-radius: 12px;
|
||||
text-align: center;
|
||||
border: 2px solid #e1e5e9;
|
||||
}
|
||||
|
||||
.stat-number {
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
color: #667eea;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.container {
|
||||
margin: 0;
|
||||
border-radius: 0;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.content {
|
||||
padding: 20px 15px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>🔄 Iroh Sync</h1>
|
||||
<div class="status" id="status">
|
||||
<div class="connection-status">
|
||||
<span class="status-dot disconnected" id="statusDot"></span>
|
||||
<span id="statusText">Connecting...</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="stats">
|
||||
<div class="stat-item">
|
||||
<div class="stat-number" id="fileCount">0</div>
|
||||
<div class="stat-label">Files</div>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<div class="stat-number" id="peerCount">0</div>
|
||||
<div class="stat-label">Peers</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<!-- Connection Section -->
|
||||
<div class="section">
|
||||
<h3>🎫 Share & Connect</h3>
|
||||
<button class="btn" onclick="generateTicket()">📋 Generate Sharing Ticket</button>
|
||||
<div class="ticket-display hidden" id="ticketDisplay"></div>
|
||||
|
||||
<div style="margin: 20px 0; text-align: center; color: #666;">or</div>
|
||||
|
||||
<div class="input-group">
|
||||
<input type="text" id="ticketInput" placeholder="Paste ticket from another device...">
|
||||
</div>
|
||||
<button class="btn" onclick="connectToPeer()">🔗 Connect to Peer</button>
|
||||
</div>
|
||||
|
||||
<!-- Upload Section -->
|
||||
<div class="section">
|
||||
<h3>📤 Upload Files</h3>
|
||||
<div class="upload-area" onclick="document.getElementById('fileInput').click()"
|
||||
ondrop="handleDrop(event)" ondragover="handleDragOver(event)" ondragleave="handleDragLeave(event)">
|
||||
<div class="upload-icon">📁</div>
|
||||
<div class="upload-text">Tap to select files</div>
|
||||
<div class="upload-hint">or drag & drop here</div>
|
||||
</div>
|
||||
<input type="file" id="fileInput" style="display: none;" multiple onchange="handleFileSelect(event)">
|
||||
<button class="btn" onclick="uploadSelectedFiles()" id="uploadBtn" disabled>📤 Upload Files</button>
|
||||
</div>
|
||||
|
||||
<!-- Files Section -->
|
||||
<div class="section">
|
||||
<h3>📋 Synced Files</h3>
|
||||
<div class="file-list" id="fileList">
|
||||
<div class="loading">Loading files...</div>
|
||||
</div>
|
||||
<button class="btn secondary" onclick="refreshFiles()" style="margin-top: 15px;">🔄 Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let selectedFiles = [];
|
||||
let connected = false;
|
||||
let currentTicket = '';
|
||||
|
||||
// Initialize
|
||||
window.onload = function() {
|
||||
checkStatus();
|
||||
refreshFiles();
|
||||
setInterval(checkStatus, 3000); // Check status every 3 seconds
|
||||
};
|
||||
|
||||
async function checkStatus() {
|
||||
try {
|
||||
const response = await fetch('/api/status');
|
||||
const status = await response.json();
|
||||
|
||||
const isConnected = status.connected_peers > 0;
|
||||
const statusDot = document.getElementById('statusDot');
|
||||
const statusText = document.getElementById('statusText');
|
||||
|
||||
if (isConnected) {
|
||||
statusDot.className = 'status-dot';
|
||||
statusText.textContent = `Connected (${status.connected_peers} peer${status.connected_peers > 1 ? 's' : ''})`;
|
||||
} else {
|
||||
statusDot.className = 'status-dot disconnected';
|
||||
statusText.textContent = 'Waiting for peers';
|
||||
}
|
||||
|
||||
document.getElementById('fileCount').textContent = status.total_files;
|
||||
document.getElementById('peerCount').textContent = status.connected_peers;
|
||||
|
||||
connected = isConnected;
|
||||
} catch (error) {
|
||||
document.getElementById('statusText').textContent = 'Connection Error';
|
||||
console.error('Status check failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function generateTicket() {
|
||||
try {
|
||||
const response = await fetch('/api/ticket');
|
||||
const ticket = await response.text();
|
||||
currentTicket = ticket.replace(/"/g, ''); // Remove quotes
|
||||
|
||||
const ticketDisplay = document.getElementById('ticketDisplay');
|
||||
ticketDisplay.textContent = currentTicket;
|
||||
ticketDisplay.classList.remove('hidden');
|
||||
|
||||
// Copy to clipboard
|
||||
if (navigator.clipboard) {
|
||||
await navigator.clipboard.writeText(currentTicket);
|
||||
showMessage('Ticket generated and copied to clipboard!', 'success');
|
||||
} else {
|
||||
showMessage('Ticket generated! Copy it manually.', 'success');
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage('Failed to generate ticket: ' + error.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function connectToPeer() {
|
||||
const ticket = document.getElementById('ticketInput').value.trim();
|
||||
if (!ticket) {
|
||||
showMessage('Please enter a ticket', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/connect', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ticket })
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
showMessage('Connected successfully!', 'success');
|
||||
document.getElementById('ticketInput').value = '';
|
||||
setTimeout(() => {
|
||||
checkStatus();
|
||||
refreshFiles();
|
||||
}, 1000);
|
||||
} else {
|
||||
showMessage('Connection failed - check the ticket', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage('Connection error: ' + error.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function handleFileSelect(event) {
|
||||
selectedFiles = Array.from(event.target.files);
|
||||
updateUploadButton();
|
||||
}
|
||||
|
||||
function handleDrop(event) {
|
||||
event.preventDefault();
|
||||
event.target.classList.remove('dragover');
|
||||
selectedFiles = Array.from(event.dataTransfer.files);
|
||||
updateUploadButton();
|
||||
}
|
||||
|
||||
function handleDragOver(event) {
|
||||
event.preventDefault();
|
||||
event.currentTarget.classList.add('dragover');
|
||||
}
|
||||
|
||||
function handleDragLeave(event) {
|
||||
event.currentTarget.classList.remove('dragover');
|
||||
}
|
||||
|
||||
function updateUploadButton() {
|
||||
const btn = document.getElementById('uploadBtn');
|
||||
if (selectedFiles.length > 0) {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = `📤 Upload ${selectedFiles.length} file${selectedFiles.length > 1 ? 's' : ''}`;
|
||||
} else {
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '📤 Upload Files';
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadSelectedFiles() {
|
||||
if (selectedFiles.length === 0) return;
|
||||
|
||||
const btn = document.getElementById('uploadBtn');
|
||||
const originalText = btn.innerHTML;
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '⏳ Uploading...';
|
||||
|
||||
let successCount = 0;
|
||||
let failCount = 0;
|
||||
|
||||
for (let file of selectedFiles) {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const response = await fetch('/api/upload', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
successCount++;
|
||||
} else {
|
||||
failCount++;
|
||||
console.error('Upload failed for:', file.name);
|
||||
}
|
||||
} catch (error) {
|
||||
failCount++;
|
||||
console.error('Upload error for', file.name, ':', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (successCount > 0) {
|
||||
showMessage(`Successfully uploaded ${successCount} file${successCount > 1 ? 's' : ''}!`, 'success');
|
||||
}
|
||||
if (failCount > 0) {
|
||||
showMessage(`Failed to upload ${failCount} file${failCount > 1 ? 's' : ''}`, 'error');
|
||||
}
|
||||
|
||||
selectedFiles = [];
|
||||
document.getElementById('fileInput').value = '';
|
||||
updateUploadButton();
|
||||
setTimeout(refreshFiles, 1000);
|
||||
}
|
||||
|
||||
async function refreshFiles() {
|
||||
const fileList = document.getElementById('fileList');
|
||||
fileList.innerHTML = '<div class="loading">Loading files...</div>';
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/files');
|
||||
const files = await response.json();
|
||||
|
||||
if (files.length === 0) {
|
||||
fileList.innerHTML = '<div class="loading">No files yet - upload some!</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
fileList.innerHTML = files.map(file => `
|
||||
<div class="file-item">
|
||||
<div class="file-icon ${file.is_directory ? 'folder' : 'file'}">
|
||||
${file.is_directory ? '📁' : getFileIcon(file.name)}
|
||||
</div>
|
||||
<div class="file-info">
|
||||
<div class="file-name">${file.name}</div>
|
||||
<div class="file-size">
|
||||
${file.is_directory ? 'Folder' : formatFileSize(file.size)}
|
||||
</div>
|
||||
</div>
|
||||
${!file.is_directory ? `
|
||||
<div class="file-actions">
|
||||
<button class="btn-small btn-download" onclick="downloadFile('${file.path}', '${file.name}')">
|
||||
💾
|
||||
</button>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
`).join('');
|
||||
} catch (error) {
|
||||
fileList.innerHTML = '<div class="loading">Error loading files</div>';
|
||||
console.error('Failed to load files:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function getFileIcon(filename) {
|
||||
const ext = filename.split('.').pop().toLowerCase();
|
||||
const iconMap = {
|
||||
'jpg': '🖼️', 'jpeg': '🖼️', 'png': '🖼️', 'gif': '🖼️',
|
||||
'mp4': '🎬', 'avi': '🎬', 'mov': '🎬',
|
||||
'mp3': '🎵', 'wav': '🎵', 'flac': '🎵',
|
||||
'pdf': '📕', 'doc': '📄', 'docx': '📄',
|
||||
'txt': '📝', 'md': '📝',
|
||||
'zip': '📦', 'rar': '📦', '7z': '📦'
|
||||
};
|
||||
return iconMap[ext] || '📄';
|
||||
}
|
||||
|
||||
async function downloadFile(filePath, fileName) {
|
||||
try {
|
||||
const response = await fetch(`/api/download/${encodeURIComponent(filePath)}`);
|
||||
if (!response.ok) throw new Error('Download failed');
|
||||
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = fileName;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
document.body.removeChild(a);
|
||||
|
||||
showMessage(`Downloaded: ${fileName}`, 'success');
|
||||
} catch (error) {
|
||||
showMessage(`Download failed: ${fileName}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function formatFileSize(bytes) {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
function showMessage(text, type) {
|
||||
const existing = document.querySelector('.message');
|
||||
if (existing) existing.remove();
|
||||
|
||||
const message = document.createElement('div');
|
||||
message.className = `message ${type}`;
|
||||
message.textContent = text;
|
||||
|
||||
const content = document.querySelector('.content');
|
||||
content.insertBefore(message, content.firstChild);
|
||||
|
||||
setTimeout(() => message.remove(), 5000);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
0
web/index.html:Zone.Identifier
Normal file
0
web/index.html:Zone.Identifier
Normal file
Loading…
Reference in New Issue
Block a user