firecloud-cli 0.2.0

Command-line interface for FireCloud P2P messaging and file sharing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// Friend management system for private peer-to-peer communication
use anyhow::{anyhow, Context, Result};
use clap::Subcommand;
use colored::Colorize;
use comfy_table::{presets::UTF8_FULL, Table};
use libp2p::PeerId;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::str::FromStr;
use std::time::Duration;

// Network imports for sending friend requests over libp2p
use firecloud_net::{FireCloudNode, NodeConfig, NodeEvent, MessageResponse};

#[derive(Debug, Subcommand)]
pub enum FriendCommand {
    /// Add a friend by their Peer ID
    Add {
        /// The peer ID of the friend to add
        peer_id: String,
        
        /// Optional nickname for the friend
        #[arg(short, long)]
        name: Option<String>,
    },
    
    /// Accept a friend request
    Accept {
        /// The peer ID to accept as a friend
        peer_id: String,
    },
    
    /// List all friends
    List {
        /// Show detailed information
        #[arg(short, long)]
        detailed: bool,
    },
    
    /// Remove a friend
    Remove {
        /// The peer ID or name of the friend to remove
        friend: String,
    },
    
    /// Show pending friend requests
    Pending,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum FriendStatus {
    /// You sent a request, waiting for acceptance
    RequestSent,
    
    /// You received a request, waiting for your acceptance
    RequestReceived,
    
    /// Mutual friends - both accepted
    Accepted,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Friend {
    pub peer_id: PeerId,
    pub name: Option<String>,
    pub status: FriendStatus,
    pub added_at: chrono::DateTime<chrono::Utc>,
    pub last_seen: Option<chrono::DateTime<chrono::Utc>>,
    pub messages_exchanged: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FriendList {
    pub friends: HashMap<PeerId, Friend>,
}

impl FriendList {
    /// Load friend list from disk
    pub fn load(data_dir: &PathBuf) -> Result<Self> {
        let friends_path = data_dir.join("friends.json");
        
        if !friends_path.exists() {
            return Ok(Self::default());
        }
        
        let data = fs::read_to_string(&friends_path)
            .context("Failed to read friends.json")?;
        
        let friends: FriendList = serde_json::from_str(&data)
            .context("Failed to parse friends.json")?;
        
        Ok(friends)
    }
    
    /// Save friend list to disk
    pub fn save(&self, data_dir: &PathBuf) -> Result<()> {
        fs::create_dir_all(data_dir)
            .context("Failed to create data directory")?;
        
        let friends_path = data_dir.join("friends.json");
        
        let data = serde_json::to_string_pretty(self)
            .context("Failed to serialize friends")?;
        
        fs::write(&friends_path, data)
            .context("Failed to write friends.json")?;
        
        Ok(())
    }
    
    /// Add a friend (sends request)
    pub fn add_friend(&mut self, peer_id: PeerId, name: Option<String>) -> Result<()> {
        if peer_id == self.get_local_peer_id()? {
            anyhow::bail!("Cannot add yourself as a friend");
        }
        
        if let Some(existing) = self.friends.get(&peer_id) {
            match existing.status {
                FriendStatus::RequestSent => {
                    anyhow::bail!("Friend request already sent to this peer");
                }
                FriendStatus::RequestReceived => {
                    // Auto-accept if they already sent us a request
                    self.accept_friend(peer_id)?;
                    return Ok(());
                }
                FriendStatus::Accepted => {
                    anyhow::bail!("Already friends with this peer");
                }
            }
        }
        
        let friend = Friend {
            peer_id,
            name,
            status: FriendStatus::RequestSent,
            added_at: chrono::Utc::now(),
            last_seen: None,
            messages_exchanged: 0,
        };
        
        self.friends.insert(peer_id, friend);
        Ok(())
    }
    
    /// Accept a friend request
    pub fn accept_friend(&mut self, peer_id: PeerId) -> Result<()> {
        let friend = self.friends.get_mut(&peer_id)
            .context("Friend not found in list")?;
        
        match friend.status {
            FriendStatus::RequestReceived | FriendStatus::RequestSent => {
                friend.status = FriendStatus::Accepted;
                Ok(())
            }
            FriendStatus::Accepted => {
                anyhow::bail!("Already accepted this friend");
            }
        }
    }
    
    /// Remove a friend
    pub fn remove_friend(&mut self, peer_id: &PeerId) -> Result<()> {
        self.friends.remove(peer_id)
            .context("Friend not found in list")?;
        Ok(())
    }
    
    /// Check if a peer is an accepted friend
    pub fn is_friend(&self, peer_id: &PeerId) -> bool {
        self.friends.get(peer_id)
            .map(|f| f.status == FriendStatus::Accepted)
            .unwrap_or(false)
    }
    
    /// Get friend by peer ID or name
    pub fn find_friend(&self, identifier: &str) -> Option<&Friend> {
        // Try as peer ID first
        if let Ok(peer_id) = PeerId::from_str(identifier) {
            if let Some(friend) = self.friends.get(&peer_id) {
                return Some(friend);
            }
        }
        
        // Try as name
        self.friends.values()
            .find(|f| f.name.as_ref().map(|n| n == identifier).unwrap_or(false))
    }
    
    /// Get all accepted friends
    pub fn get_accepted_friends(&self) -> Vec<&Friend> {
        self.friends.values()
            .filter(|f| f.status == FriendStatus::Accepted)
            .collect()
    }
    
    /// Get pending received requests
    pub fn get_pending_received(&self) -> Vec<&Friend> {
        self.friends.values()
            .filter(|f| f.status == FriendStatus::RequestReceived)
            .collect()
    }
    
    /// Get pending sent requests
    pub fn get_pending_sent(&self) -> Vec<&Friend> {
        self.friends.values()
            .filter(|f| f.status == FriendStatus::RequestSent)
            .collect()
    }
    
    /// Update last seen time
    pub fn update_last_seen(&mut self, peer_id: &PeerId) {
        if let Some(friend) = self.friends.get_mut(peer_id) {
            friend.last_seen = Some(chrono::Utc::now());
        }
    }
    
    /// Increment message counter
    pub fn increment_messages(&mut self, peer_id: &PeerId) {
        if let Some(friend) = self.friends.get_mut(peer_id) {
            friend.messages_exchanged += 1;
        }
    }
    
    // TODO: Get this from actual node
    fn get_local_peer_id(&self) -> Result<PeerId> {
        // For now, return a placeholder
        // In real implementation, this should come from the running node
        Err(anyhow::anyhow!("Local peer ID not available"))
    }
}

/// Create a temporary node for sending friend requests
/// This node will stay alive briefly to allow confirmation
async fn create_friend_node() -> Result<FireCloudNode> {
    let config = NodeConfig {
        port: 0,  // Random port
        bootstrap_peers: vec![],
        enable_mdns: true,
        bootstrap_relays: vec![],
    };
    
    FireCloudNode::new(config).await
        .context("Failed to create network node")
}

pub async fn handle_friend_command(cmd: FriendCommand, data_dir: PathBuf) -> Result<()> {
    let mut friends = FriendList::load(&data_dir)?;
    
    match cmd {
        FriendCommand::Add { peer_id, name } => {
            let peer_id = PeerId::from_str(&peer_id)
                .context("Invalid peer ID format")?;
            
            // 1. Add to local friends list
            friends.add_friend(peer_id, name.clone())?;
            friends.save(&data_dir)?;
            
            let peer_id_string = peer_id.to_string();
            let display_name = name.as_ref().map(|s| s.as_str()).unwrap_or(&peer_id_string);
            
            // 2. Send friend request over the network
            println!("\n{}", "📡 Sending friend request over network...".cyan());
            
            match create_friend_node().await {
                Ok(mut node) => {
                    // Send the friend request
                    let _request_id = node.send_friend_request(&peer_id, name.clone());
                    
                    println!("{}", "   Network request sent!".green());
                    
                    // Keep the node alive briefly to allow for immediate response
                    let timeout = tokio::time::timeout(Duration::from_secs(3), async {
                        while let Some(event) = node.poll_event().await {
                            if let NodeEvent::MessageResponse { response, .. } = event {
                                if let MessageResponse::FriendRequestReceived { mutual } = response {
                                    if mutual {
                                        println!("{}", "🎉 Mutual friend request detected - auto-accepted!".green().bold());
                                        friends.accept_friend(peer_id)?;
                                        friends.save(&data_dir)?;
                                    }
                                    return Ok::<(), anyhow::Error>(());
                                }
                            }
                        }
                        Ok(())
                    });
                    
                    let _ = timeout.await;
                    
                    println!("\n{}", "✅ Friend request sent!".green().bold());
                    println!("  Peer ID: {}", peer_id.to_string().cyan());
                    println!("  Name: {}", display_name.yellow());
                    println!("\n{}", "Waiting for them to accept your request...".dimmed());
                }
                Err(e) => {
                    println!("{}", format!("⚠️  Network error: {}", e).yellow());
                    println!("{}", "   Request saved locally. Will retry when network is available.".dimmed());
                }
            }
        }
        
        FriendCommand::Accept { peer_id } => {
            let peer_id = PeerId::from_str(&peer_id)
                .context("Invalid peer ID format")?;
            
            // 1. Accept locally
            friends.accept_friend(peer_id)?;
            friends.save(&data_dir)?;
            
            let friend = friends.friends.get(&peer_id).unwrap();
            let display_name = friend.name.clone().unwrap_or_else(|| peer_id.to_string());
            
            // 2. Send acceptance over network
            println!("\n{}", "📡 Sending friend acceptance over network...".cyan());
            
            match create_friend_node().await {
                Ok(mut node) => {
                    let _request_id = node.send_friend_accept(&peer_id);
                    println!("{}", "   Network confirmation sent!".green());
                    
                    // Keep alive briefly for confirmation
                    tokio::time::sleep(Duration::from_secs(2)).await;
                }
                Err(e) => {
                    println!("{}", format!("⚠️  Network error: {}", e).yellow());
                    println!("{}", "   Acceptance saved locally. Will retry when network is available.".dimmed());
                }
            }
            
            println!("\n{}", "✅ Friend request accepted!".green().bold());
            println!("  You are now friends with: {}", display_name.yellow());
            println!("  Peer ID: {}", peer_id.to_string().cyan());
            println!("\n{}", "You can now send private messages and files!".dimmed());
        }
        
        FriendCommand::List { detailed } => {
            let accepted = friends.get_accepted_friends();
            
            if accepted.is_empty() {
                println!("\n{}", "No friends yet.".yellow());
                println!("{}", "Add friends with: firecloud friend add <peer-id>".dimmed());
                return Ok(());
            }
            
            println!("\n{} ({} total)", "Friends".green().bold(), accepted.len());
            
            if detailed {
                for friend in accepted {
                    let display_name = friend.name.clone()
                        .unwrap_or_else(|| format!("{:.8}...", friend.peer_id.to_string()));
                    
                    let last_seen = friend.last_seen
                        .map(|t| format!("{}", humantime::format_duration(
                            chrono::Utc::now().signed_duration_since(t).to_std().unwrap_or_default()
                        )))
                        .unwrap_or_else(|| "Never".to_string());
                    
                    println!("\n  {} {}", "".cyan(), display_name.yellow().bold());
                    println!("    Peer ID: {}", friend.peer_id.to_string().dimmed());
                    println!("    Added: {}", friend.added_at.format("%Y-%m-%d %H:%M").to_string().dimmed());
                    println!("    Last seen: {}", last_seen.dimmed());
                    println!("    Messages: {}", friend.messages_exchanged.to_string().dimmed());
                }
            } else {
                let mut table = Table::new();
                table.load_preset(UTF8_FULL);
                table.set_header(vec!["Name", "Peer ID", "Last Seen", "Messages"]);
                
                for friend in accepted {
                    let display_name = friend.name.clone()
                        .unwrap_or_else(|| format!("{:.8}...", friend.peer_id.to_string()));
                    
                    let peer_id_short = format!("{:.12}...", friend.peer_id.to_string());
                    
                    let last_seen = friend.last_seen
                        .map(|t| {
                            let duration = chrono::Utc::now().signed_duration_since(t);
                            if duration.num_hours() < 1 {
                                format!("{}m ago", duration.num_minutes())
                            } else if duration.num_days() < 1 {
                                format!("{}h ago", duration.num_hours())
                            } else {
                                format!("{}d ago", duration.num_days())
                            }
                        })
                        .unwrap_or_else(|| "Never".to_string());
                    
                    table.add_row(vec![
                        display_name,
                        peer_id_short,
                        last_seen,
                        friend.messages_exchanged.to_string(),
                    ]);
                }
                
                println!("{}", table);
            }
        }
        
        FriendCommand::Remove { friend: identifier } => {
            let friend = friends.find_friend(&identifier)
                .context("Friend not found")?;
            
            let peer_id = friend.peer_id;
            let display_name = friend.name.clone()
                .unwrap_or_else(|| peer_id.to_string());
            
            friends.remove_friend(&peer_id)?;
            friends.save(&data_dir)?;
            
            println!("\n{}", "✅ Friend removed".green().bold());
            println!("  {}", display_name.yellow());
        }
        
        FriendCommand::Pending => {
            let received = friends.get_pending_received();
            let sent = friends.get_pending_sent();
            
            if received.is_empty() && sent.is_empty() {
                println!("\n{}", "No pending friend requests.".yellow());
                return Ok(());
            }
            
            if !received.is_empty() {
                println!("\n{} ({})", "Received Requests".green().bold(), received.len());
                for friend in received {
                    let display_name = friend.name.clone()
                        .unwrap_or_else(|| format!("{:.8}...", friend.peer_id.to_string()));
                    
                    println!("  {} {}", "".cyan(), display_name.yellow());
                    println!("    Peer ID: {}", friend.peer_id.to_string().dimmed());
                    println!("    Accept with: {}", 
                        format!("firecloud friend accept {}", friend.peer_id).cyan());
                }
            }
            
            if !sent.is_empty() {
                println!("\n{} ({})", "Sent Requests".yellow().bold(), sent.len());
                for friend in sent {
                    let display_name = friend.name.clone()
                        .unwrap_or_else(|| format!("{:.8}...", friend.peer_id.to_string()));
                    
                    println!("  {} {}", "".cyan(), display_name.yellow());
                    println!("    Peer ID: {}", friend.peer_id.to_string().dimmed());
                    println!("    {}", "Waiting for acceptance...".dimmed());
                }
            }
        }
    }
    
    Ok(())
}