tuitbot-server 0.1.49

HTTP API server for Tuitbot autonomous X growth assistant
Documentation
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
//! Draft Studio API endpoints.
//!
//! Provides the canonical `/api/drafts` routes for the Draft Studio workspace.
//!
//! Provides the canonical `/api/drafts` routes for the Draft Studio workspace,
//! including collection queries, CRUD, autosave with conflict detection,
//! workflow transitions, and revision/activity read endpoints.

use std::sync::Arc;

use axum::extract::{Path, Query, State};
use axum::Json;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tuitbot_core::storage::{provenance, scheduled_content};

use crate::account::{require_mutate, AccountContext};
use crate::error::ApiError;
use crate::state::AppState;

// ---------------------------------------------------------------------------
// Request / response types
// ---------------------------------------------------------------------------

#[derive(Deserialize)]
pub struct DraftListQuery {
    pub status: Option<String>,
    pub tag: Option<i64>,
    pub search: Option<String>,
    pub archived: Option<bool>,
}

#[derive(Serialize)]
pub struct DraftSummary {
    pub id: i64,
    pub title: Option<String>,
    pub content_type: String,
    pub content_preview: String,
    pub status: String,
    pub scheduled_for: Option<String>,
    pub archived_at: Option<String>,
    pub updated_at: String,
    pub created_at: String,
    pub source: String,
}

#[derive(Deserialize)]
pub struct CreateStudioDraftBody {
    #[serde(default = "default_tweet")]
    pub content_type: String,
    #[serde(default = "default_blank_content")]
    pub content: String,
    #[serde(default = "default_manual")]
    pub source: String,
    pub title: Option<String>,
}

fn default_tweet() -> String {
    "tweet".to_string()
}

fn default_blank_content() -> String {
    " ".to_string()
}

fn default_manual() -> String {
    "manual".to_string()
}

#[derive(Deserialize)]
pub struct AutosavePatchBody {
    pub content: String,
    pub content_type: String,
    pub updated_at: String,
}

#[derive(Deserialize)]
pub struct MetaPatchBody {
    pub title: Option<String>,
    pub notes: Option<String>,
}

#[derive(Deserialize)]
pub struct ScheduleBody {
    pub scheduled_for: String,
}

#[derive(Deserialize)]
pub struct CreateRevisionBody {
    #[serde(default = "default_manual_trigger")]
    pub trigger_kind: String,
}

fn default_manual_trigger() -> String {
    "manual".to_string()
}

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

/// Truncate content to ~60 chars for list previews.
/// For threads (JSON blocks), extract the first block's text.
fn content_preview(content: &str, content_type: &str) -> String {
    let text = if content_type == "thread" {
        extract_first_block_text(content)
    } else {
        content.to_string()
    };
    let trimmed = text.trim();
    if trimmed.len() <= 60 {
        trimmed.to_string()
    } else {
        let mut preview = trimmed.chars().take(57).collect::<String>();
        preview.push_str("...");
        preview
    }
}

/// Try to extract the first block's text from thread JSON content.
fn extract_first_block_text(content: &str) -> String {
    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(content) {
        if let Some(blocks) = parsed.get("blocks").and_then(|b| b.as_array()) {
            if let Some(first) = blocks.first() {
                if let Some(text) = first.get("text").and_then(|t| t.as_str()) {
                    return text.to_string();
                }
            }
        }
        // Legacy array format
        if let Some(arr) = parsed.as_array() {
            if let Some(first) = arr.first().and_then(|v| v.as_str()) {
                return first.to_string();
            }
        }
    }
    content.to_string()
}

fn to_summary(item: &scheduled_content::ScheduledContent) -> DraftSummary {
    DraftSummary {
        id: item.id,
        title: item.title.clone(),
        content_type: item.content_type.clone(),
        content_preview: content_preview(&item.content, &item.content_type),
        status: item.status.clone(),
        scheduled_for: item.scheduled_for.clone(),
        archived_at: item.archived_at.clone(),
        updated_at: item.updated_at.clone(),
        created_at: item.created_at.clone(),
        source: item.source.clone(),
    }
}

mod handlers;

pub use handlers::*;

/// `POST /api/drafts/:id/unschedule` — transition scheduled -> draft.
pub async fn unschedule_studio_draft(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<i64>,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;

    let item = scheduled_content::get_by_id_for(&state.db, &ctx.account_id, id)
        .await
        .map_err(ApiError::Storage)?
        .ok_or_else(|| ApiError::NotFound(format!("Draft {id} not found")))?;

    if item.status != "scheduled" {
        return Err(ApiError::BadRequest(format!(
            "Item is in '{}' status, not 'scheduled'",
            item.status
        )));
    }

    // Create revision snapshot before unscheduling
    let _ = scheduled_content::insert_revision_for(
        &state.db,
        &ctx.account_id,
        id,
        &item.content,
        &item.content_type,
        "unschedule",
    )
    .await;

    let unscheduled = scheduled_content::unschedule_draft_for(&state.db, &ctx.account_id, id)
        .await
        .map_err(ApiError::Storage)?;

    if !unscheduled {
        return Err(ApiError::BadRequest(
            "Failed to unschedule — item may have changed status".to_string(),
        ));
    }

    // Log activity
    let _ =
        scheduled_content::insert_activity_for(&state.db, &ctx.account_id, id, "unscheduled", None)
            .await;

    Ok(Json(json!({ "id": id, "status": "draft" })))
}

/// Request body for atomic reschedule.
#[derive(Deserialize)]
pub struct RescheduleBody {
    pub scheduled_for: String,
}

/// `PATCH /api/drafts/:id/reschedule` — atomically change the scheduled time.
pub async fn reschedule_studio_draft(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<i64>,
    Json(body): Json<RescheduleBody>,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;

    let item = scheduled_content::get_by_id_for(&state.db, &ctx.account_id, id)
        .await
        .map_err(ApiError::Storage)?
        .ok_or_else(|| ApiError::NotFound(format!("Draft {id} not found")))?;

    if item.status != "scheduled" {
        return Err(ApiError::BadRequest(format!(
            "Item is in '{}' status, not 'scheduled'",
            item.status
        )));
    }

    let normalized = tuitbot_core::scheduling::validate_and_normalize(
        &body.scheduled_for,
        tuitbot_core::scheduling::DEFAULT_GRACE_SECONDS,
    )
    .map_err(|e| ApiError::BadRequest(e.to_string()))?;

    // Snapshot before reschedule
    let _ = scheduled_content::insert_revision_for(
        &state.db,
        &ctx.account_id,
        id,
        &item.content,
        &item.content_type,
        "reschedule",
    )
    .await;

    let updated =
        scheduled_content::reschedule_draft_for(&state.db, &ctx.account_id, id, &normalized)
            .await
            .map_err(ApiError::Storage)?;

    if !updated {
        return Err(ApiError::BadRequest(
            "Failed to reschedule — item may have changed status".to_string(),
        ));
    }

    // Log activity
    let _ = scheduled_content::insert_activity_for(
        &state.db,
        &ctx.account_id,
        id,
        "rescheduled",
        Some(
            &json!({
                "from": item.scheduled_for,
                "to": normalized
            })
            .to_string(),
        ),
    )
    .await;

    Ok(Json(json!({
        "id": id,
        "status": "scheduled",
        "scheduled_for": normalized
    })))
}

/// `POST /api/drafts/:id/archive` — soft-delete a draft.
pub async fn archive_studio_draft(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<i64>,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;

    scheduled_content::archive_draft_for(&state.db, &ctx.account_id, id)
        .await
        .map_err(ApiError::Storage)?;

    // Log activity
    let _ =
        scheduled_content::insert_activity_for(&state.db, &ctx.account_id, id, "archived", None)
            .await;

    // Fetch to get archived_at
    let item = scheduled_content::get_by_id_for(&state.db, &ctx.account_id, id)
        .await
        .map_err(ApiError::Storage)?;

    let archived_at = item.and_then(|i| i.archived_at).unwrap_or_default();

    Ok(Json(json!({ "id": id, "archived_at": archived_at })))
}

/// `POST /api/drafts/:id/restore` — restore an archived draft.
pub async fn restore_studio_draft(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<i64>,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;

    scheduled_content::restore_draft_for(&state.db, &ctx.account_id, id)
        .await
        .map_err(ApiError::Storage)?;

    // Log activity
    let _ =
        scheduled_content::insert_activity_for(&state.db, &ctx.account_id, id, "restored", None)
            .await;

    Ok(Json(json!({ "id": id })))
}

/// `POST /api/drafts/:id/duplicate` — clone a draft.
pub async fn duplicate_studio_draft(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<i64>,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;

    let new_id = scheduled_content::duplicate_draft_for(&state.db, &ctx.account_id, id)
        .await
        .map_err(ApiError::Storage)?
        .ok_or_else(|| ApiError::NotFound(format!("Draft {id} not found")))?;

    // Copy provenance links from original draft to the duplicate.
    let _ = provenance::copy_links_for(
        &state.db,
        &ctx.account_id,
        "scheduled_content",
        id,
        "scheduled_content",
        new_id,
    )
    .await;

    // Log created activity on the new draft
    let _ = scheduled_content::insert_activity_for(
        &state.db,
        &ctx.account_id,
        new_id,
        "created",
        Some(&json!({ "source": "duplicate", "original_id": id }).to_string()),
    )
    .await;

    Ok(Json(json!({ "id": new_id })))
}

/// `POST /api/drafts/:id/revisions/:rev_id/restore` — restore content from a revision.
///
/// Safety: snapshots the current content as a `pre_restore` revision before
/// overwriting, so restore is always non-lossy.
pub async fn restore_from_revision(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path((id, rev_id)): Path<(i64, i64)>,
) -> Result<Json<scheduled_content::ScheduledContent>, ApiError> {
    require_mutate(&ctx)?;

    // 1. Fetch current draft
    let current = scheduled_content::get_by_id_for(&state.db, &ctx.account_id, id)
        .await
        .map_err(ApiError::Storage)?
        .ok_or_else(|| ApiError::NotFound(format!("Draft {id} not found")))?;

    // 2. Fetch target revision (verify ownership via account+content scope)
    let target_rev = scheduled_content::get_revision_for(&state.db, &ctx.account_id, id, rev_id)
        .await
        .map_err(ApiError::Storage)?
        .ok_or_else(|| ApiError::NotFound(format!("Revision {rev_id} not found")))?;

    // 3. Snapshot current state as pre_restore
    let _ = scheduled_content::insert_revision_for(
        &state.db,
        &ctx.account_id,
        id,
        &current.content,
        &current.content_type,
        "pre_restore",
    )
    .await;

    // 4. Update content to revision's content
    let _ = scheduled_content::autosave_draft_for(
        &state.db,
        &ctx.account_id,
        id,
        &target_rev.content,
        &target_rev.content_type,
        &current.updated_at,
    )
    .await
    .map_err(ApiError::Storage)?;

    // 5. Log activity
    let _ = scheduled_content::insert_activity_for(
        &state.db,
        &ctx.account_id,
        id,
        "revision_restored",
        Some(&json!({"from_revision_id": rev_id}).to_string()),
    )
    .await;

    // 6. Return updated draft
    let updated = scheduled_content::get_by_id_for(&state.db, &ctx.account_id, id)
        .await
        .map_err(ApiError::Storage)?
        .ok_or_else(|| ApiError::NotFound(format!("Draft {id} not found")))?;
    Ok(Json(updated))
}

/// `GET /api/drafts/:id/revisions` — list revision snapshots.
pub async fn list_draft_revisions(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<i64>,
) -> Result<Json<Vec<scheduled_content::ContentRevision>>, ApiError> {
    let revisions = scheduled_content::list_revisions_for(&state.db, &ctx.account_id, id)
        .await
        .map_err(ApiError::Storage)?;
    Ok(Json(revisions))
}

/// `POST /api/drafts/:id/revisions` — create a manual revision snapshot.
pub async fn create_draft_revision(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<i64>,
    Json(body): Json<CreateRevisionBody>,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;

    let item = scheduled_content::get_by_id_for(&state.db, &ctx.account_id, id)
        .await
        .map_err(ApiError::Storage)?
        .ok_or_else(|| ApiError::NotFound(format!("Draft {id} not found")))?;

    let rev_id = scheduled_content::insert_revision_for(
        &state.db,
        &ctx.account_id,
        id,
        &item.content,
        &item.content_type,
        &body.trigger_kind,
    )
    .await
    .map_err(ApiError::Storage)?;

    Ok(Json(json!({ "id": rev_id })))
}

/// `GET /api/drafts/:id/activity` — list activity log.
pub async fn list_draft_activity(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<i64>,
) -> Result<Json<Vec<scheduled_content::ContentActivity>>, ApiError> {
    let activity = scheduled_content::list_activity_for(&state.db, &ctx.account_id, id)
        .await
        .map_err(ApiError::Storage)?;
    Ok(Json(activity))
}

#[cfg(test)]
mod tests;