molten-herald 0.1.0

Automated viral tweet generation and scheduling for developer releases 📢
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
//! Tweet scheduling system

use crate::config::ScheduleConfig;
use crate::error::{HeraldError, Result};
use crate::generator::GeneratedTweet;
use chrono::{DateTime, Utc, Timelike, Duration};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tracing::{debug, info};

/// A scheduled tweet
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScheduledTweet {
    /// Unique identifier
    pub id: String,

    /// The tweet content
    pub content: String,

    /// Scheduled time
    pub scheduled_for: DateTime<Utc>,

    /// Source event ID
    pub event_id: Option<String>,

    /// Status
    pub status: ScheduleStatus,

    /// Created at
    pub created_at: DateTime<Utc>,

    /// Posted tweet ID (if posted)
    pub posted_id: Option<String>,

    /// Error message (if failed)
    pub error: Option<String>,
}

/// Status of a scheduled tweet
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScheduleStatus {
    /// Waiting to be posted
    Pending,
    /// Currently being posted
    Posting,
    /// Successfully posted
    Posted,
    /// Failed to post
    Failed,
    /// Cancelled by user
    Cancelled,
}

/// Tweet scheduler
pub struct Scheduler {
    config: ScheduleConfig,
    queue_path: PathBuf,
}

impl Scheduler {
    /// Create a new scheduler
    pub fn new(config: ScheduleConfig) -> Result<Self> {
        let queue_path = config.queue_file.clone().unwrap_or_else(|| {
            directories::ProjectDirs::from("io", "moltenlabs", "herald")
                .map(|d| d.data_dir().join("queue.json"))
                .unwrap_or_else(|| PathBuf::from("herald_queue.json"))
        });

        // Ensure parent directory exists
        if let Some(parent) = queue_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        Ok(Self { config, queue_path })
    }

    /// Schedule a tweet from a generated tweet
    pub fn schedule(&self, tweet: &GeneratedTweet, time: Option<DateTime<Utc>>) -> Result<ScheduledTweet> {
        let scheduled_time = time.unwrap_or_else(|| self.next_available_slot());

        let scheduled = ScheduledTweet {
            id: uuid::Uuid::new_v4().to_string(),
            content: tweet.content.clone(),
            scheduled_for: scheduled_time,
            event_id: Some(tweet.event_id.clone()),
            status: ScheduleStatus::Pending,
            created_at: Utc::now(),
            posted_id: None,
            error: None,
        };

        // Add to queue
        let mut queue = self.load_queue()?;
        queue.push(scheduled.clone());
        self.save_queue(&queue)?;

        info!("Scheduled tweet for {}", scheduled_time);
        Ok(scheduled)
    }

    /// Schedule a raw text tweet
    pub fn schedule_text(&self, content: &str, time: Option<DateTime<Utc>>) -> Result<ScheduledTweet> {
        let scheduled_time = time.unwrap_or_else(|| self.next_available_slot());

        let scheduled = ScheduledTweet {
            id: uuid::Uuid::new_v4().to_string(),
            content: content.to_string(),
            scheduled_for: scheduled_time,
            event_id: None,
            status: ScheduleStatus::Pending,
            created_at: Utc::now(),
            posted_id: None,
            error: None,
        };

        let mut queue = self.load_queue()?;
        queue.push(scheduled.clone());
        self.save_queue(&queue)?;

        Ok(scheduled)
    }

    /// Get the next available scheduling slot
    pub fn next_available_slot(&self) -> DateTime<Utc> {
        let queue = self.load_queue().unwrap_or_default();
        let now = Utc::now();

        // Find the last scheduled time
        let last_scheduled = queue
            .iter()
            .filter(|t| t.status == ScheduleStatus::Pending)
            .map(|t| t.scheduled_for)
            .max();

        let min_gap = Duration::hours(self.config.min_hours_between as i64);

        // Start from now or after last scheduled + gap
        let earliest = match last_scheduled {
            Some(last) => {
                let with_gap = last + min_gap;
                if with_gap > now { with_gap } else { now }
            }
            None => now,
        };

        // Find next preferred time
        self.find_next_preferred_time(earliest)
    }

    /// Find the next preferred posting time
    fn find_next_preferred_time(&self, after: DateTime<Utc>) -> DateTime<Utc> {
        if self.config.preferred_times.is_empty() {
            return after + Duration::hours(1);
        }

        let today_times: Vec<(u32, u32)> = self.config.preferred_times
            .iter()
            .filter_map(|t| {
                let parts: Vec<&str> = t.split(':').collect();
                if parts.len() == 2 {
                    Some((
                        parts[0].parse().ok()?,
                        parts[1].parse().ok()?,
                    ))
                } else {
                    None
                }
            })
            .collect();

        let after_hour = after.hour();
        let after_minute = after.minute();

        // Try to find a time today
        for &(hour, minute) in &today_times {
            if hour > after_hour || (hour == after_hour && minute > after_minute) {
                return after
                    .with_hour(hour).unwrap()
                    .with_minute(minute).unwrap()
                    .with_second(0).unwrap();
            }
        }

        // Use first time tomorrow
        if let Some(&(hour, minute)) = today_times.first() {
            return (after + Duration::days(1))
                .with_hour(hour).unwrap()
                .with_minute(minute).unwrap()
                .with_second(0).unwrap();
        }

        after + Duration::hours(1)
    }

    /// Get all pending tweets
    pub fn pending(&self) -> Result<Vec<ScheduledTweet>> {
        let queue = self.load_queue()?;
        Ok(queue
            .into_iter()
            .filter(|t| t.status == ScheduleStatus::Pending)
            .collect())
    }

    /// Get tweets due for posting
    pub fn due(&self) -> Result<Vec<ScheduledTweet>> {
        let now = Utc::now();
        let queue = self.load_queue()?;
        Ok(queue
            .into_iter()
            .filter(|t| t.status == ScheduleStatus::Pending && t.scheduled_for <= now)
            .collect())
    }

    /// Mark a tweet as posted
    pub fn mark_posted(&self, id: &str, posted_id: &str) -> Result<()> {
        let mut queue = self.load_queue()?;
        
        if let Some(tweet) = queue.iter_mut().find(|t| t.id == id) {
            tweet.status = ScheduleStatus::Posted;
            tweet.posted_id = Some(posted_id.to_string());
        }

        self.save_queue(&queue)
    }

    /// Mark a tweet as failed
    pub fn mark_failed(&self, id: &str, error: &str) -> Result<()> {
        let mut queue = self.load_queue()?;
        
        if let Some(tweet) = queue.iter_mut().find(|t| t.id == id) {
            tweet.status = ScheduleStatus::Failed;
            tweet.error = Some(error.to_string());
        }

        self.save_queue(&queue)
    }

    /// Cancel a scheduled tweet
    pub fn cancel(&self, id: &str) -> Result<()> {
        let mut queue = self.load_queue()?;
        
        if let Some(tweet) = queue.iter_mut().find(|t| t.id == id) {
            tweet.status = ScheduleStatus::Cancelled;
        }

        self.save_queue(&queue)
    }

    /// Reschedule a tweet
    pub fn reschedule(&self, id: &str, new_time: DateTime<Utc>) -> Result<()> {
        let mut queue = self.load_queue()?;
        
        if let Some(tweet) = queue.iter_mut().find(|t| t.id == id) {
            tweet.scheduled_for = new_time;
            tweet.status = ScheduleStatus::Pending;
        }

        self.save_queue(&queue)
    }

    /// Clear completed/failed/cancelled tweets
    pub fn cleanup(&self) -> Result<usize> {
        let mut queue = self.load_queue()?;
        let before = queue.len();
        
        queue.retain(|t| t.status == ScheduleStatus::Pending);
        
        self.save_queue(&queue)?;
        Ok(before - queue.len())
    }

    /// Get queue statistics
    pub fn stats(&self) -> Result<QueueStats> {
        let queue = self.load_queue()?;
        
        Ok(QueueStats {
            pending: queue.iter().filter(|t| t.status == ScheduleStatus::Pending).count(),
            posted: queue.iter().filter(|t| t.status == ScheduleStatus::Posted).count(),
            failed: queue.iter().filter(|t| t.status == ScheduleStatus::Failed).count(),
            cancelled: queue.iter().filter(|t| t.status == ScheduleStatus::Cancelled).count(),
        })
    }

    /// Load queue from disk
    fn load_queue(&self) -> Result<Vec<ScheduledTweet>> {
        if !self.queue_path.exists() {
            return Ok(Vec::new());
        }

        let content = std::fs::read_to_string(&self.queue_path)?;
        if content.trim().is_empty() {
            return Ok(Vec::new());
        }

        serde_json::from_str(&content).map_err(|e| {
            HeraldError::Schedule(format!("Failed to parse queue: {}", e))
        })
    }

    /// Save queue to disk
    fn save_queue(&self, queue: &[ScheduledTweet]) -> Result<()> {
        let content = serde_json::to_string_pretty(queue)?;
        std::fs::write(&self.queue_path, content)?;
        debug!("Saved {} tweets to queue", queue.len());
        Ok(())
    }
}

/// Queue statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueStats {
    pub pending: usize,
    pub posted: usize,
    pub failed: usize,
    pub cancelled: usize,
}

impl QueueStats {
    pub fn total(&self) -> usize {
        self.pending + self.posted + self.failed + self.cancelled
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::{tempdir, TempDir};

    fn test_scheduler() -> (TempDir, Scheduler) {
        let dir = tempdir().unwrap();
        let config = ScheduleConfig {
            queue_file: Some(dir.path().join("test_queue.json")),
            ..Default::default()
        };
        let scheduler = Scheduler::new(config).unwrap();
        (dir, scheduler)
    }

    #[test]
    fn test_schedule_text() {
        let (_dir, scheduler) = test_scheduler();
        let scheduled = scheduler.schedule_text("Hello world!", None).unwrap();
        
        assert_eq!(scheduled.content, "Hello world!");
        assert_eq!(scheduled.status, ScheduleStatus::Pending);
    }

    #[test]
    fn test_pending() {
        let (_dir, scheduler) = test_scheduler();
        scheduler.schedule_text("Tweet 1", None).unwrap();
        scheduler.schedule_text("Tweet 2", None).unwrap();
        
        let pending = scheduler.pending().unwrap();
        assert_eq!(pending.len(), 2);
    }

    #[test]
    fn test_mark_posted() {
        let (_dir, scheduler) = test_scheduler();
        let scheduled = scheduler.schedule_text("Hello!", None).unwrap();
        
        scheduler.mark_posted(&scheduled.id, "twitter-123").unwrap();
        
        let queue = scheduler.load_queue().unwrap();
        let tweet = queue.iter().find(|t| t.id == scheduled.id).unwrap();
        assert_eq!(tweet.status, ScheduleStatus::Posted);
        assert_eq!(tweet.posted_id, Some("twitter-123".to_string()));
    }

    #[test]
    fn test_cancel() {
        let (_dir, scheduler) = test_scheduler();
        let scheduled = scheduler.schedule_text("Cancel me!", None).unwrap();
        
        scheduler.cancel(&scheduled.id).unwrap();
        
        let pending = scheduler.pending().unwrap();
        assert!(pending.is_empty());
    }

    #[test]
    fn test_stats() {
        let (_dir, scheduler) = test_scheduler();
        scheduler.schedule_text("Tweet 1", None).unwrap();
        let s2 = scheduler.schedule_text("Tweet 2", None).unwrap();
        scheduler.mark_posted(&s2.id, "123").unwrap();
        
        let stats = scheduler.stats().unwrap();
        assert_eq!(stats.pending, 1);
        assert_eq!(stats.posted, 1);
        assert_eq!(stats.total(), 2);
    }

    #[test]
    fn test_cleanup() {
        let (_dir, scheduler) = test_scheduler();
        let s1 = scheduler.schedule_text("Posted", None).unwrap();
        scheduler.schedule_text("Pending", None).unwrap();
        scheduler.mark_posted(&s1.id, "123").unwrap();
        
        let removed = scheduler.cleanup().unwrap();
        assert_eq!(removed, 1);
        
        let stats = scheduler.stats().unwrap();
        assert_eq!(stats.total(), 1);
    }

    #[test]
    fn test_schedule_status_serialization() {
        let status = ScheduleStatus::Pending;
        let json = serde_json::to_string(&status).unwrap();
        assert_eq!(json, "\"pending\"");
        
        let parsed: ScheduleStatus = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, ScheduleStatus::Pending);
    }
}