vkteams-bot-cli 0.7.6

High-performance VK Teams Bot API toolkit with CLI and MCP server support
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
//! Time utilities for VK Teams Bot CLI
//!
//! This module provides time parsing, formatting, and manipulation utilities
//! used throughout the CLI application.

use crate::errors::prelude::{CliError, Result as CliResult};
use chrono::{DateTime, Datelike, Duration, NaiveDate, NaiveDateTime, Timelike, Utc};
use cron::Schedule;
use std::str::FromStr;

/// Parse a schedule time string with flexible format support (for scheduling commands)
///
/// # Arguments
/// * `time_str` - The time string to parse
///
/// # Returns
/// * `Ok(DateTime<Utc>)` if successfully parsed
/// * `Err(CliError::InputError)` if parsing fails
pub fn parse_schedule_time(time_str: &str) -> CliResult<DateTime<Utc>> {
    // Try different formats
    let formats = [
        "%Y-%m-%d %H:%M:%S",
        "%Y-%m-%d %H:%M",
        "%Y-%m-%d",
        "%H:%M:%S",
        "%H:%M",
        "%Y-%m-%dT%H:%M:%S",
        "%Y-%m-%dT%H:%M:%SZ",
        "%Y-%m-%dT%H:%M:%S%.3fZ",
    ];

    for format in &formats {
        if let Ok(naive_dt) = NaiveDateTime::parse_from_str(time_str, format) {
            return Ok(DateTime::from_naive_utc_and_offset(naive_dt, Utc));
        }
        if let Ok(naive_date) = NaiveDate::parse_from_str(time_str, format) {
            return Ok(DateTime::from_naive_utc_and_offset(
                naive_date.and_hms_opt(0, 0, 0).unwrap(),
                Utc,
            ));
        }
    }

    // Try relative times
    if let Ok(dt) = parse_relative_time(time_str) {
        return Ok(dt);
    }

    Err(CliError::InputError(format!(
        "Invalid time format: {time_str}. Use YYYY-MM-DD HH:MM:SS, or relative time like '30m', '2h', '1d'"
    )))
}

/// Parse a schedule time string with flexible format support (scheduler version)
///
/// This is a compatibility alias for the scheduler module.
/// # Arguments
/// * `time_str` - The time string to parse
///
/// # Returns
/// * `Ok(DateTime<Utc>)` if successfully parsed
/// * `Err(CliError::InputError)` if parsing fails
pub fn parse_schedule_time_compat(time_str: &str) -> CliResult<DateTime<Utc>> {
    // Try different formats (original scheduler formats)
    let formats = [
        "%Y-%m-%d %H:%M:%S",
        "%Y-%m-%d %H:%M",
        "%Y-%m-%d",
        "%H:%M:%S",
        "%H:%M",
    ];

    for format in &formats {
        if let Ok(naive_dt) = NaiveDateTime::parse_from_str(time_str, format) {
            return Ok(DateTime::from_naive_utc_and_offset(naive_dt, Utc));
        }
        if let Ok(naive_date) = NaiveDate::parse_from_str(time_str, format) {
            return Ok(DateTime::from_naive_utc_and_offset(
                naive_date.and_hms_opt(0, 0, 0).unwrap(),
                Utc,
            ));
        }
    }

    // Try relative times
    if let Some(stripped) = time_str.strip_suffix('m')
        && let Ok(minutes) = stripped.parse::<i64>()
    {
        return Ok(Utc::now() + Duration::minutes(minutes));
    }
    if let Some(stripped) = time_str.strip_suffix('h')
        && let Ok(hours) = stripped.parse::<i64>()
    {
        return Ok(Utc::now() + Duration::hours(hours));
    }
    if let Some(stripped) = time_str.strip_suffix('d')
        && let Ok(days) = stripped.parse::<i64>()
    {
        return Ok(Utc::now() + Duration::days(days));
    }

    Err(CliError::InputError(format!(
        "Invalid time format: {time_str}. Use YYYY-MM-DD HH:MM:SS, or relative time like '30m', '2h', '1d'"
    )))
}

/// Parse relative time expressions (e.g., "30m", "2h", "1d")
///
/// # Arguments
/// * `time_str` - The relative time string to parse
///
/// # Returns
/// * `Ok(DateTime<Utc>)` if successfully parsed
/// * `Err(CliError::InputError)` if parsing fails
pub fn parse_relative_time(time_str: &str) -> CliResult<DateTime<Utc>> {
    let time_str = time_str.trim().to_lowercase();

    if time_str.is_empty() {
        return Err(CliError::InputError(
            "Relative time cannot be empty".to_string(),
        ));
    }

    let now = Utc::now();

    // Parse relative times
    if let Some(stripped) = time_str.strip_suffix('s')
        && let Ok(seconds) = stripped.parse::<i64>()
    {
        return Ok(now + Duration::seconds(seconds));
    }
    if let Some(stripped) = time_str.strip_suffix('m')
        && let Ok(minutes) = stripped.parse::<i64>()
    {
        return Ok(now + Duration::minutes(minutes));
    }
    if let Some(stripped) = time_str.strip_suffix('h')
        && let Ok(hours) = stripped.parse::<i64>()
    {
        return Ok(now + Duration::hours(hours));
    }
    if let Some(stripped) = time_str.strip_suffix('d')
        && let Ok(days) = stripped.parse::<i64>()
    {
        return Ok(now + Duration::days(days));
    }
    if let Some(stripped) = time_str.strip_suffix('w')
        && let Ok(weeks) = stripped.parse::<i64>()
    {
        return Ok(now + Duration::weeks(weeks));
    }

    // Special keywords
    match time_str.as_str() {
        "now" => Ok(now),
        "tomorrow" => Ok(now + Duration::days(1)),
        "yesterday" => Ok(now - Duration::days(1)),
        _ => Err(CliError::InputError(format!(
            "Invalid relative time format: {time_str}. Use formats like '30s', '5m', '2h', '1d', '1w' or 'now'"
        ))),
    }
}

/// Format a duration into a human-readable string
///
/// # Arguments
/// * `duration` - The duration to format
///
/// # Returns
/// * A human-readable string representation of the duration
pub fn format_duration(duration: Duration) -> String {
    let total_seconds = duration.num_seconds();

    if total_seconds < 0 {
        return format!("-{}", format_duration(-duration));
    }

    let days = total_seconds / 86400;
    let hours = (total_seconds % 86400) / 3600;
    let minutes = (total_seconds % 3600) / 60;
    let seconds = total_seconds % 60;

    let mut parts = Vec::new();

    if days > 0 {
        parts.push(format!("{days}d"));
    }
    if hours > 0 {
        parts.push(format!("{hours}h"));
    }
    if minutes > 0 {
        parts.push(format!("{minutes}m"));
    }
    if seconds > 0 || parts.is_empty() {
        parts.push(format!("{seconds}s"));
    }

    parts.join(" ")
}

/// Format a datetime into a user-friendly string
///
/// # Arguments
/// * `dt` - The datetime to format
///
/// # Returns
/// * A formatted string representation of the datetime
pub fn format_datetime(dt: DateTime<Utc>) -> String {
    dt.format("%Y-%m-%d %H:%M:%S UTC").to_string()
}

/// Format a datetime relative to now (e.g., "in 5 minutes", "2 hours ago")
///
/// # Arguments
/// * `dt` - The datetime to format relative to now
///
/// # Returns
/// * A relative time string
pub fn format_datetime_relative(dt: DateTime<Utc>) -> String {
    let now = Utc::now();
    let diff = dt.signed_duration_since(now);

    if diff.num_seconds().abs() < 60 {
        return "now".to_string();
    }

    let abs_diff = if diff.num_seconds() < 0 { -diff } else { diff };
    let formatted = format_duration(abs_diff);

    if diff.num_seconds() < 0 {
        format!("{formatted} ago")
    } else {
        format!("in {formatted}")
    }
}

/// Get the next occurrence of a cron expression
///
/// # Arguments
/// * `cron_expr` - The cron expression
/// * `from_time` - Optional base time (defaults to now)
///
/// # Returns
/// * `Ok(DateTime<Utc>)` if the next occurrence can be calculated
/// * `Err(CliError::InputError)` if the cron expression is invalid
pub fn get_next_cron_occurrence(
    cron_expr: &str,
    from_time: Option<DateTime<Utc>>,
) -> CliResult<DateTime<Utc>> {
    let schedule = Schedule::from_str(cron_expr)
        .map_err(|e| CliError::InputError(format!("Invalid cron expression: {e}")))?;

    let base_time = from_time.unwrap_or_else(Utc::now);

    schedule
        .after(&base_time)
        .next()
        .ok_or_else(|| CliError::InputError("No upcoming time for cron expression".to_string()))
}

/// Calculate the next run time for an interval-based schedule
///
/// # Arguments
/// * `duration_seconds` - The interval duration in seconds
/// * `start_time` - The schedule start time
/// * `from_time` - Optional base time (defaults to now)
///
/// # Returns
/// * The next scheduled run time
pub fn get_next_interval_occurrence(
    duration_seconds: u64,
    start_time: DateTime<Utc>,
    from_time: Option<DateTime<Utc>>,
) -> DateTime<Utc> {
    let base_time = from_time.unwrap_or_else(Utc::now);

    if base_time < start_time {
        return start_time;
    }

    let elapsed = base_time.signed_duration_since(start_time);
    let interval = Duration::seconds(duration_seconds as i64);
    let intervals_passed = elapsed.num_seconds() / interval.num_seconds();
    let next_interval = intervals_passed + 1;

    start_time + Duration::seconds(next_interval * interval.num_seconds())
}

/// Check if a datetime is within business hours (9 AM to 5 PM UTC)
///
/// # Arguments
/// * `dt` - The datetime to check
///
/// # Returns
/// * `true` if the datetime is within business hours
/// * `false` otherwise
pub fn is_business_hours(dt: DateTime<Utc>) -> bool {
    let hour = dt.hour();
    (9..17).contains(&hour)
}

/// Check if a datetime is on a weekend (Saturday or Sunday)
///
/// # Arguments
/// * `dt` - The datetime to check
///
/// # Returns
/// * `true` if the datetime is on a weekend
/// * `false` otherwise
pub fn is_weekend(dt: DateTime<Utc>) -> bool {
    let weekday = dt.weekday();
    weekday == chrono::Weekday::Sat || weekday == chrono::Weekday::Sun
}

/// Round a datetime to the nearest minute
///
/// # Arguments
/// * `dt` - The datetime to round
///
/// # Returns
/// * The rounded datetime
pub fn round_to_minute(dt: DateTime<Utc>) -> DateTime<Utc> {
    let rounded_naive = dt
        .naive_utc()
        .with_second(0)
        .unwrap()
        .with_nanosecond(0)
        .unwrap();

    DateTime::from_naive_utc_and_offset(rounded_naive, Utc)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_relative_time() {
        let _now = Utc::now();

        assert!(parse_relative_time("30s").is_ok());
        assert!(parse_relative_time("5m").is_ok());
        assert!(parse_relative_time("2h").is_ok());
        assert!(parse_relative_time("1d").is_ok());
        assert!(parse_relative_time("1w").is_ok());
        assert!(parse_relative_time("now").is_ok());
        assert!(parse_relative_time("tomorrow").is_ok());

        assert!(parse_relative_time("invalid").is_err());
        assert!(parse_relative_time("").is_err());
    }

    #[test]
    fn test_format_duration() {
        let duration = Duration::seconds(3661); // 1 hour, 1 minute, 1 second
        let formatted = format_duration(duration);
        assert_eq!(formatted, "1h 1m 1s");

        let duration = Duration::seconds(60); // 1 minute
        let formatted = format_duration(duration);
        assert_eq!(formatted, "1m");

        let duration = Duration::seconds(0); // 0 seconds
        let formatted = format_duration(duration);
        assert_eq!(formatted, "0s");
    }

    #[test]
    fn test_parse_schedule_time() {
        assert!(parse_schedule_time("2024-01-01 12:00:00").is_ok());
        assert!(parse_schedule_time("2024-01-01 12:00").is_ok());
        assert!(parse_schedule_time("2024-01-01").is_ok());
        assert!(parse_schedule_time("30m").is_ok());

        assert!(parse_schedule_time("invalid-date").is_err());
    }

    #[test]
    fn test_get_next_cron_occurrence() {
        // Test every hour (6-field format: sec min hour day month weekday)
        assert!(get_next_cron_occurrence("0 0 * * * *", None).is_ok());

        // Test invalid cron
        assert!(get_next_cron_occurrence("invalid", None).is_err());
    }

    #[test]
    fn test_format_datetime_relative() {
        let now = Utc::now();
        let future = now + Duration::minutes(5);
        let past = now - Duration::hours(2);

        let future_str = format_datetime_relative(future);
        assert!(future_str.contains("in"));

        let past_str = format_datetime_relative(past);
        assert!(past_str.contains("ago"));
    }

    #[test]
    fn test_is_business_hours() {
        // Create a datetime at 10 AM UTC
        let dt = Utc::now().date_naive().and_hms_opt(10, 0, 0).unwrap();
        let dt_utc = DateTime::from_naive_utc_and_offset(dt, Utc);
        assert!(is_business_hours(dt_utc));

        // Create a datetime at 6 PM UTC
        let dt = Utc::now().date_naive().and_hms_opt(18, 0, 0).unwrap();
        let dt_utc = DateTime::from_naive_utc_and_offset(dt, Utc);
        assert!(!is_business_hours(dt_utc));
    }
}