xmaster 1.6.3

Enterprise-grade X/Twitter CLI — post, reply, like, retweet, DM, search, and more
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
use crate::context::AppContext;
use crate::errors::XmasterError;
use crate::intel::bookmarks::{BookmarkRecord, BookmarkStore};
use crate::output::{self, OutputFormat, Tableable};
use crate::providers::xapi::XApi;
use serde::Serialize;
use std::sync::Arc;

// ---------------------------------------------------------------------------
// Display types
// ---------------------------------------------------------------------------

#[derive(Serialize)]
struct BookmarkList {
    bookmarks: Vec<BookmarkRow>,
    total: usize,
}

#[derive(Serialize)]
struct BookmarkRow {
    id: String,
    author: String,
    text: String,
    likes: i64,
    saved: String,
}

impl Tableable for BookmarkList {
    fn to_table(&self) -> comfy_table::Table {
        let mut table = comfy_table::Table::new();
        table.set_header(vec!["ID", "Author", "Text", "Likes", "Saved"]);
        for b in &self.bookmarks {
            let truncated = if b.text.chars().count() > 60 {
                format!("{}...", crate::utils::safe_truncate(&b.text, 57))
            } else {
                b.text.clone()
            };
            table.add_row(vec![
                &b.id,
                &b.author,
                &truncated,
                &b.likes.to_string(),
                &b.saved,
            ]);
        }
        table
    }
}

#[derive(Serialize)]
struct SyncDisplay {
    new_bookmarks: u32,
    already_stored: u32,
    total_in_db: u32,
    message: String,
}

impl Tableable for SyncDisplay {
    fn to_table(&self) -> comfy_table::Table {
        let mut table = comfy_table::Table::new();
        table.set_header(vec!["Field", "Value"]);
        table.add_row(vec!["New", &self.new_bookmarks.to_string()]);
        table.add_row(vec!["Already stored", &self.already_stored.to_string()]);
        table.add_row(vec!["Total in archive", &self.total_in_db.to_string()]);
        table.add_row(vec!["Status", &self.message]);
        table
    }
}

#[derive(Serialize)]
struct ExportDisplay {
    count: usize,
    output: String,
    message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    content: Option<String>,
}

impl Tableable for ExportDisplay {
    fn to_table(&self) -> comfy_table::Table {
        let mut table = comfy_table::Table::new();
        table.set_header(vec!["Field", "Value"]);
        table.add_row(vec!["Exported", &self.count.to_string()]);
        table.add_row(vec!["Output", &self.output]);
        table.add_row(vec!["Status", &self.message]);
        table
    }
}

#[derive(Serialize)]
struct DigestDisplay {
    period_days: u32,
    count: u32,
    unique_authors: usize,
    link_count: u32,
    text_count: u32,
    top_authors: Vec<AuthorSummary>,
}

#[derive(Serialize)]
struct AuthorSummary {
    username: String,
    count: u32,
}

impl Tableable for DigestDisplay {
    fn to_table(&self) -> comfy_table::Table {
        let mut table = comfy_table::Table::new();
        table.set_header(vec!["Field", "Value"]);
        table.add_row(vec![
            "Period",
            &format!("Last {} days", self.period_days),
        ]);
        table.add_row(vec!["Bookmarks", &self.count.to_string()]);
        table.add_row(vec!["Authors", &self.unique_authors.to_string()]);
        table.add_row(vec!["With links", &self.link_count.to_string()]);
        table.add_row(vec!["Text only", &self.text_count.to_string()]);
        for a in &self.top_authors {
            table.add_row(vec![
                &format!("@{}", a.username),
                &format!("{} bookmarks", a.count),
            ]);
        }
        table
    }
}

#[derive(Serialize)]
struct StatsDisplay {
    total: u32,
    unread: u32,
    with_links: u32,
    with_media: u32,
    top_authors: Vec<(String, u32)>,
    oldest: Option<String>,
    newest: Option<String>,
}

impl Tableable for StatsDisplay {
    fn to_table(&self) -> comfy_table::Table {
        let mut table = comfy_table::Table::new();
        table.set_header(vec!["Field", "Value"]);
        table.add_row(vec!["Total", &self.total.to_string()]);
        table.add_row(vec!["Unread", &self.unread.to_string()]);
        table.add_row(vec!["With links", &self.with_links.to_string()]);
        table.add_row(vec!["With media", &self.with_media.to_string()]);
        if let Some(ref o) = self.oldest {
            table.add_row(vec!["Oldest", o]);
        }
        if let Some(ref n) = self.newest {
            table.add_row(vec!["Newest", n]);
        }
        for (author, count) in &self.top_authors {
            table.add_row(vec![
                &format!("@{author}"),
                &format!("{count} bookmarks"),
            ]);
        }
        table
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn records_to_list(records: Vec<BookmarkRecord>) -> BookmarkList {
    let total = records.len();
    let bookmarks = records
        .into_iter()
        .map(|r| BookmarkRow {
            id: r.tweet_id,
            author: format!("@{}", r.author_username),
            text: r.text,
            likes: r.likes,
            saved: chrono::DateTime::from_timestamp(r.bookmarked_at, 0)
                .map(|dt| dt.format("%Y-%m-%d").to_string())
                .unwrap_or_else(|| r.bookmarked_at.to_string()),
        })
        .collect();
    BookmarkList { bookmarks, total }
}

// ---------------------------------------------------------------------------
// Commands
// ---------------------------------------------------------------------------

pub async fn list(
    ctx: Arc<AppContext>,
    format: OutputFormat,
    count: usize,
    unread: bool,
) -> Result<(), XmasterError> {
    if unread {
        let store = BookmarkStore::open()?;
        let records = store.list_unread(count)?;
        if records.is_empty() {
            return Err(XmasterError::NotFound(
                "No unread bookmarks found. Sync bookmarks first: xmaster bookmarks sync".into(),
            ));
        }
        output::render(format, &records_to_list(records), None);
    } else {
        // Live from X API — bookmarks require OAuth 2.0
        let token = crate::providers::oauth2::ensure_oauth2_token(&ctx.config).await?;
        let api = XApi::new(ctx.clone());
        let user_id = api.get_me().await?.id;
        let per_page = count.min(100);
        let url = format!(
            "https://api.x.com/2/users/{}/bookmarks?max_results={}&tweet.fields=created_at,public_metrics,author_id&expansions=author_id&user.fields=username,name",
            user_id, per_page
        );
        let json = crate::providers::oauth2::oauth2_get(&url, &token).await?;
        let tweets = parse_bookmark_response(&json);

        let records: Vec<BookmarkRecord> = tweets
            .into_iter()
            .map(|t| {
                let metrics = t.public_metrics.as_ref();
                BookmarkRecord {
                    tweet_id: t.id,
                    author_username: t
                        .author_username
                        .unwrap_or_else(|| t.author_id.unwrap_or_default()),
                    author_name: None,
                    text: t.text,
                    created_at: t.created_at.clone(),
                    bookmarked_at: chrono::Utc::now().timestamp(),
                    likes: metrics.map(|m| m.like_count as i64).unwrap_or(0),
                    retweets: metrics.map(|m| m.retweet_count as i64).unwrap_or(0),
                    replies: metrics.map(|m| m.reply_count as i64).unwrap_or(0),
                    has_media: false,
                    has_link: false,
                    tags: String::new(),
                    notes: String::new(),
                    read: false,
                }
            })
            .collect();
        output::render(format, &records_to_list(records), None);
    }
    Ok(())
}

pub async fn sync(
    ctx: Arc<AppContext>,
    format: OutputFormat,
    count: usize,
) -> Result<(), XmasterError> {
    // Bookmarks require OAuth 2.0 — get token (auto-refresh if needed)
    let token = crate::providers::oauth2::ensure_oauth2_token(&ctx.config).await?;

    // Fetch bookmarks via OAuth 2.0
    let user_id = {
        let api = XApi::new(ctx.clone());
        let me = api.get_me().await?;
        me.id
    };
    let per_page = count.min(100); // API max is 100 per request
    let base_url = format!(
        "https://api.x.com/2/users/{}/bookmarks?max_results={}&tweet.fields=created_at,public_metrics,author_id&expansions=author_id&user.fields=username,name",
        user_id, per_page
    );

    // Paginate through all bookmarks until count is reached or no more pages
    let mut tweets = Vec::new();
    let mut next_token: Option<String> = None;
    let mut remaining = count;

    loop {
        let url = match &next_token {
            Some(token_val) => format!("{}&pagination_token={}", base_url, token_val),
            None => base_url.clone(),
        };
        let json = crate::providers::oauth2::oauth2_get(&url, &token).await?;

        let page_tweets = parse_bookmark_response(&json);
        remaining = remaining.saturating_sub(page_tweets.len());
        tweets.extend(page_tweets);

        // Check for next page
        next_token = json
            .get("meta")
            .and_then(|m| m.get("next_token"))
            .and_then(|t| t.as_str())
            .map(|s| s.to_string());

        if next_token.is_none() || remaining == 0 {
            break;
        }
    }

    // Trim to requested count
    tweets.truncate(count);
    let store = BookmarkStore::open()?;
    let result = store.sync(tweets)?;

    let display = SyncDisplay {
        new_bookmarks: result.new_bookmarks,
        already_stored: result.already_stored,
        total_in_db: result.total_in_db,
        message: format!(
            "Synced: {} new, {} already stored. Total: {} in local archive",
            result.new_bookmarks, result.already_stored, result.total_in_db
        ),
    };
    output::render(format, &display, None);

    if format == OutputFormat::Table {
        eprintln!(
            "Search: xmaster bookmarks search \"query\"",
        );
        eprintln!(
            "Export: xmaster bookmarks export -o bookmarks.md",
        );
    }
    Ok(())
}

/// Parse X API v2 bookmarks response into TweetData for the store
fn parse_bookmark_response(json: &serde_json::Value) -> Vec<crate::providers::xapi::TweetData> {
    let mut tweets = Vec::new();
    let empty_arr = Vec::new();
    let data = json.get("data").and_then(|d| d.as_array()).unwrap_or(&empty_arr);

    // Build author lookup from includes.users
    let mut author_map = std::collections::HashMap::new();
    if let Some(includes) = json.get("includes") {
        if let Some(users) = includes.get("users").and_then(|u| u.as_array()) {
            for user in users {
                let id = user.get("id").and_then(|v| v.as_str()).unwrap_or("");
                let username = user.get("username").and_then(|v| v.as_str()).unwrap_or("");
                let name = user.get("name").and_then(|v| v.as_str()).unwrap_or("");
                author_map.insert(id.to_string(), (username.to_string(), name.to_string()));
            }
        }
    }

    for tweet in data {
        let id = tweet.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();
        let text = tweet.get("text").and_then(|v| v.as_str()).unwrap_or("").to_string();
        let author_id = tweet.get("author_id").and_then(|v| v.as_str()).unwrap_or("").to_string();
        let created_at = tweet.get("created_at").and_then(|v| v.as_str()).map(|s| s.to_string());
        let (username, _name) = author_map.get(&author_id).cloned().unwrap_or_default();

        let metrics = tweet.get("public_metrics").map(|m| crate::providers::xapi::TweetMetrics {
            like_count: m.get("like_count").and_then(|v| v.as_u64()).unwrap_or(0),
            retweet_count: m.get("retweet_count").and_then(|v| v.as_u64()).unwrap_or(0),
            reply_count: m.get("reply_count").and_then(|v| v.as_u64()).unwrap_or(0),
            impression_count: m.get("impression_count").and_then(|v| v.as_u64()).unwrap_or(0),
            bookmark_count: m.get("bookmark_count").and_then(|v| v.as_u64()).unwrap_or(0),
        });

        tweets.push(crate::providers::xapi::TweetData {
            id,
            text,
            author_id: Some(author_id),
            author_username: Some(username),
            created_at,
            conversation_id: None,
            referenced_tweets: None,
            public_metrics: metrics,
            author_followers: None,
            media_urls: vec![],
        });
    }
    tweets
}

pub async fn search(format: OutputFormat, query: &str) -> Result<(), XmasterError> {
    let store = BookmarkStore::open()?;
    let records = store.search(query)?;

    if records.is_empty() {
        output::render_error(
            format,
            "no_results",
            &format!("No bookmarks matching '{query}'"),
            "Try a broader search term or sync more bookmarks: xmaster bookmarks sync",
        );
        return Ok(());
    }

    output::render(format, &records_to_list(records), None);
    Ok(())
}

pub async fn export(
    format: OutputFormat,
    output_path: Option<&str>,
    unread: bool,
) -> Result<(), XmasterError> {
    let store = BookmarkStore::open()?;

    let records = if unread {
        store.list_unread(1000)?
    } else {
        store.search("")? // get all
    };

    if records.is_empty() {
        output::render_error(
            format,
            "no_bookmarks",
            "No bookmarks to export",
            "Sync bookmarks first: xmaster bookmarks sync",
        );
        return Ok(());
    }

    let count = records.len();
    let md = BookmarkStore::export_markdown(&records);

    // Write output first, THEN mark as read (so bookmarks aren't lost if write fails)
    let output_desc = match output_path {
        Some(path) => {
            std::fs::write(path, &md)?;
            path.to_string()
        }
        None => {
            if format == OutputFormat::Json {
                // For JSON output, embed markdown in the JSON envelope instead of
                // printing raw markdown before JSON
                let display = ExportDisplay {
                    count,
                    output: "json".to_string(),
                    message: format!("Exported {count} bookmarks (marked as read)"),
                    content: Some(md.clone()),
                };
                // Mark as read only after successful render
                for r in &records {
                    store.mark_read(&r.tweet_id)?;
                }
                output::render(format, &display, None);
                return Ok(());
            }
            // Markdown export goes to stdout. When piped, the agent gets
            // raw markdown (intentional — they asked for export, not JSON).
            print!("{md}");
            "stdout".to_string()
        }
    };

    // Mark exported bookmarks as read only after successful write
    for r in &records {
        store.mark_read(&r.tweet_id)?;
    }

    if output_path.is_some() {
        let display = ExportDisplay {
            count,
            output: output_desc,
            message: format!("Exported {count} bookmarks (marked as read)"),
            content: None,
        };
        output::render(format, &display, None);
    }
    Ok(())
}

pub async fn digest(format: OutputFormat, days: u32) -> Result<(), XmasterError> {
    let store = BookmarkStore::open()?;
    let digest = store.get_digest(days)?;

    if digest.count == 0 {
        output::render_error(
            format,
            "no_bookmarks_in_period",
            &format!("No bookmarks in the last {days} days"),
            "Sync bookmarks first: xmaster bookmarks sync",
        );
        return Ok(());
    }

    let display = DigestDisplay {
        period_days: digest.period_days,
        count: digest.count,
        unique_authors: digest.by_author.len(),
        link_count: digest.link_count,
        text_count: digest.text_count,
        top_authors: digest
            .by_author
            .iter()
            .take(10)
            .map(|a| AuthorSummary {
                username: a.username.clone(),
                count: a.count,
            })
            .collect(),
    };
    output::render(format, &display, None);
    Ok(())
}

pub async fn stats(format: OutputFormat) -> Result<(), XmasterError> {
    let store = BookmarkStore::open()?;
    let stats = store.get_stats()?;

    if stats.total == 0 {
        output::render_error(
            format,
            "no_bookmarks",
            "No bookmarks in local database",
            "Sync bookmarks first: xmaster bookmarks sync -c 200",
        );
        return Ok(());
    }

    let display = StatsDisplay {
        total: stats.total,
        unread: stats.unread,
        with_links: stats.with_links,
        with_media: stats.with_media,
        top_authors: stats.top_authors,
        oldest: stats.oldest,
        newest: stats.newest,
    };
    output::render(format, &display, None);
    Ok(())
}

// ---------------------------------------------------------------------------
// Bookmark folders (OAuth2)
// ---------------------------------------------------------------------------

#[derive(Serialize)]
struct FolderRow {
    id: String,
    name: String,
}

#[derive(Serialize)]
struct FolderListDisplay {
    folders: Vec<FolderRow>,
}

impl Tableable for FolderListDisplay {
    fn to_table(&self) -> comfy_table::Table {
        let mut table = comfy_table::Table::new();
        table.set_header(vec!["ID", "Name"]);
        for f in &self.folders {
            table.add_row(vec![&f.id, &f.name]);
        }
        table
    }
}

/// List the authenticated user's bookmark folders.
/// Wraps GET /2/users/:id/bookmarks/folders (OAuth2 required).
pub async fn folders(
    ctx: Arc<AppContext>,
    format: OutputFormat,
) -> Result<(), XmasterError> {
    let token = crate::providers::oauth2::ensure_oauth2_token(&ctx.config).await?;
    let api = XApi::new(ctx.clone());
    let user_id = api.get_me().await?.id;
    let url = format!(
        "https://api.x.com/2/users/{user_id}/bookmarks/folders"
    );
    let json = crate::providers::oauth2::oauth2_get(&url, &token).await?;
    let data = json
        .get("data")
        .and_then(|d| d.as_array())
        .cloned()
        .unwrap_or_default();

    let folders: Vec<FolderRow> = data
        .into_iter()
        .filter_map(|f| {
            Some(FolderRow {
                id: f.get("id")?.as_str()?.to_string(),
                name: f.get("name")?.as_str()?.to_string(),
            })
        })
        .collect();

    if folders.is_empty() {
        return Err(XmasterError::NotFound("No bookmark folders found.".into()));
    }

    output::render(format, &FolderListDisplay { folders }, None);
    Ok(())
}

/// List bookmarks in a specific folder.
/// Wraps GET /2/users/:id/bookmarks/folders/:folder_id (OAuth2 required).
pub async fn folder(
    ctx: Arc<AppContext>,
    format: OutputFormat,
    folder_id: &str,
    count: usize,
) -> Result<(), XmasterError> {
    let token = crate::providers::oauth2::ensure_oauth2_token(&ctx.config).await?;
    let api = XApi::new(ctx.clone());
    let user_id = api.get_me().await?.id;
    let per_page = count.min(100);
    let url = format!(
        "https://api.x.com/2/users/{user_id}/bookmarks/folders/{folder_id}?max_results={per_page}&tweet.fields=created_at,public_metrics,author_id&expansions=author_id&user.fields=username,name"
    );
    let json = crate::providers::oauth2::oauth2_get(&url, &token).await?;
    let tweets = parse_bookmark_response(&json);

    if tweets.is_empty() {
        return Err(XmasterError::NotFound(format!(
            "No bookmarks in folder {folder_id}"
        )));
    }

    let records: Vec<BookmarkRecord> = tweets
        .into_iter()
        .map(|t| {
            let metrics = t.public_metrics.as_ref();
            BookmarkRecord {
                tweet_id: t.id,
                author_username: t
                    .author_username
                    .unwrap_or_else(|| t.author_id.unwrap_or_default()),
                author_name: None,
                text: t.text,
                created_at: t.created_at.clone(),
                bookmarked_at: chrono::Utc::now().timestamp(),
                likes: metrics.map(|m| m.like_count as i64).unwrap_or(0),
                retweets: metrics.map(|m| m.retweet_count as i64).unwrap_or(0),
                replies: metrics.map(|m| m.reply_count as i64).unwrap_or(0),
                has_media: false,
                has_link: false,
                tags: String::new(),
                notes: String::new(),
                read: false,
            }
        })
        .collect();
    output::render(format, &records_to_list(records), None);
    Ok(())
}