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
413
414
415
416
417
418
419
420
421
422
423
424
use crate::config::CONFIG;
use crate::errors::prelude::{CliError, Result as CliResult};
use crate::progress;
use crate::utils::{validate_directory_path, validate_file_path};
use futures::StreamExt;
use std::fmt::Debug;
use std::path::PathBuf;
use tokio::io::AsyncWriteExt;
use tracing::{debug, info};
use vkteams_bot::prelude::*;

// Validation functions are now imported from utils/validation module

// TODO: Enable this function when we need streaming file uploads
// /// Streams a file from disk for uploading
// ///
// /// # Errors
// /// - Returns `CliError::FileError` if the file doesn't exist or cannot be opened
// pub async fn read_file_stream(file_path: &str) -> CliResult<tokio::fs::File> {
//     validate_file_path(file_path)?;
//
//     let file = tokio::fs::File::open(file_path)
//         .await
//         .map_err(|e| CliError::FileError(format!("Failed to open file {file_path}: {e}")))?;
//
//     Ok(file)
// }

/// Stream downloads a file and saves it to disk
///
/// # Errors
/// - Returns `CliError::FileError` if there are issues with file operations
/// - Returns `CliError::ApiError` if there are issues with the API
pub async fn download_and_save_file(
    bot: &Bot,
    file_id: &str,
    dir_path: &str,
) -> CliResult<PathBuf> {
    let cfg = &CONFIG.files;
    // Use directory from path or config or current directory
    let target_dir = if !dir_path.is_empty() {
        dir_path.to_string()
    } else if let Some(download_dir) = &cfg.download_dir {
        download_dir.clone()
    } else {
        ".".to_string()
    };

    validate_directory_path(&target_dir)?;

    debug!("Getting file info for file ID: {}", file_id);
    let file_info = bot
        .send_api_request(RequestFilesGetInfo::new(FileId(file_id.to_string())))
        .await
        .map_err(CliError::ApiError)?;

    let mut file_path = PathBuf::from(&target_dir);
    file_path.push(&file_info.file_name);

    debug!("Creating file at path: {}", file_path.display());
    let file = tokio::fs::File::create(&file_path).await.map_err(|e| {
        CliError::FileError(format!(
            "Failed to create file {}: {}",
            file_path.display(),
            e
        ))
    })?;

    debug!("Starting file download stream");
    let client = reqwest::Client::new();
    let url = file_info.url.clone();

    let response = client
        .get(url)
        .send()
        .await
        .map_err(|e| CliError::FileError(format!("Failed to initiate download: {e}")))?;

    if !response.status().is_success() {
        return Err(CliError::FileError(format!(
            "Failed to download file, status code: {}",
            response.status()
        )));
    }

    let total_size = response.content_length().unwrap_or(0);

    if total_size > cfg.max_file_size as u64 {
        return Err(CliError::FileError(format!(
            "File size exceeds maximum allowed size of {} bytes",
            cfg.max_file_size
        )));
    }

    let mut file_writer = tokio::io::BufWriter::with_capacity(cfg.buffer_size, file);

    let mut stream = response.bytes_stream();
    let mut downloaded: u64 = 0;

    // Create a progress bar for the download
    let progress_bar = progress::create_download_progress_bar(total_size, &file_info.file_name);

    debug!("Streaming file content to disk");
    while let Some(chunk_result) = stream.next().await {
        let chunk = chunk_result.map_err(|e| {
            progress::abandon_progress(&progress_bar, "Download failed");
            CliError::FileError(format!("Error during download: {e}"))
        })?;

        file_writer.write_all(&chunk).await.map_err(|e| {
            progress::abandon_progress(&progress_bar, "Write failed");
            CliError::FileError(format!("Failed to write to file: {e}"))
        })?;

        downloaded += chunk.len() as u64;
        progress::increment_progress(&progress_bar, chunk.len() as u64);

        // Log progress for large files (if progress bar is disabled)
        if !&CONFIG.ui.show_progress
            && total_size > 1024 * 1024
            && downloaded % (1024 * 1024) < chunk.len() as u64
        {
            let downloaded_mb = {
                #[allow(clippy::cast_precision_loss)]
                let val = (downloaded / 1_048_576) as f64;
                val
            };
            let total_mb = {
                #[allow(clippy::cast_precision_loss)]
                let val = (total_size / 1_048_576) as f64;
                val
            };
            info!(
                "Download progress: {:.1}MB / {:.1}MB",
                downloaded_mb, total_mb
            );
        }
    }

    debug!("Flushing and finalizing file");
    file_writer.flush().await.map_err(|e| {
        progress::abandon_progress(&progress_bar, "File flush failed");
        CliError::FileError(format!("Failed to flush file data: {e}"))
    })?;

    progress::finish_progress(
        &progress_bar,
        &format!("Downloaded to {}", file_path.display()),
    );
    info!("Successfully downloaded file to: {}", file_path.display());
    Ok(file_path)
}

/// Stream uploads a file to the API
///
/// # Errors
/// - Returns `CliError::InputError` if no file path provided
/// - Returns `CliError::FileError` if the file doesn't exist or is not accessible
/// - Returns `CliError::ApiError` if there are issues with the API
pub async fn upload_file(
    bot: &Bot,
    user_id: &str,
    file_path: &str,
) -> CliResult<impl serde::Serialize + Debug> {
    let cfg = &CONFIG.files;
    // Use file path from arguments or config
    let source_path = if !file_path.is_empty() {
        file_path.to_string()
    } else if let Some(upload_dir) = &cfg.upload_dir {
        upload_dir.clone()
    } else {
        return Err(CliError::InputError(
            "No file path provided and no default upload directory configured".to_string(),
        ));
    };

    validate_file_path(&source_path)?;

    debug!("Preparing to upload file: {}", source_path);

    // Get the file size for the progress bar
    let file_size = match progress::calculate_upload_size(&source_path) {
        Ok(size) => size,
        Err(e) => {
            debug!("Could not determine file size: {}", e);
            0 // If we can't determine size, progress bar will be indeterminate
        }
    };

    // Create a progress bar for upload
    let progress_bar = progress::create_upload_progress_bar(file_size, &source_path);

    // Start the upload
    let result = match bot
        .send_api_request(RequestMessagesSendFile::new((
            ChatId::from_borrowed_str(user_id),
            MultipartName::FilePath(source_path.to_string()),
        )))
        .await
    {
        Ok(res) => {
            progress::finish_progress(&progress_bar, "Upload complete");
            res
        }
        Err(e) => {
            progress::abandon_progress(&progress_bar, "Upload failed");
            return Err(CliError::ApiError(e));
        }
    };

    info!("Successfully uploaded file: {}", source_path);
    Ok(result)
}

/// Stream uploads a voice message to the API
///
/// # Errors
/// - Returns `CliError::InputError` if no file path provided
/// - Returns `CliError::FileError` if the file doesn't exist or is not accessible
/// - Returns `CliError::ApiError` if there are issues with the API
pub async fn upload_voice(
    bot: &Bot,
    user_id: &str,
    file_path: &str,
) -> CliResult<impl serde::Serialize + Debug> {
    let cfg = &CONFIG.files;
    // Use file path from arguments or config
    let source_path = if !file_path.is_empty() {
        file_path.to_string()
    } else if let Some(upload_dir) = &cfg.upload_dir {
        upload_dir.clone()
    } else {
        return Err(CliError::InputError(
            "No file path provided and no default upload directory configured".to_string(),
        ));
    };

    validate_file_path(&source_path)?;

    debug!("Preparing to upload voice message: {}", source_path);

    // Get the file size for the progress bar
    let file_size = match progress::calculate_upload_size(&source_path) {
        Ok(size) => size,
        Err(e) => {
            debug!("Could not determine file size: {}", e);
            0 // If we can't determine size, progress bar will be indeterminate
        }
    };

    // Create a progress bar for upload
    let progress_bar = progress::create_upload_progress_bar(file_size, &source_path);

    // Start the voice upload
    let result = match bot
        .send_api_request(RequestMessagesSendVoice::new((
            ChatId::from_borrowed_str(user_id),
            MultipartName::FilePath(source_path.to_string()),
        )))
        .await
    {
        Ok(res) => {
            progress::finish_progress(&progress_bar, "Voice upload complete");
            res
        }
        Err(e) => {
            progress::abandon_progress(&progress_bar, "Voice upload failed");
            return Err(CliError::ApiError(e));
        }
    };

    info!("Successfully uploaded voice message: {}", source_path);
    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::utils::create_dummy_bot;
    use proptest::prelude::*;
    use std::fs;
    use tempfile::tempdir;
    use tokio_test::block_on;

    #[tokio::test]
    async fn test_upload_file_empty_path() {
        let bot = create_dummy_bot();
        let res = upload_file(&bot, "user123", "").await;
        assert!(res.is_err());
    }

    #[tokio::test]
    async fn test_upload_file_nonexistent() {
        let bot = create_dummy_bot();
        let res = upload_file(&bot, "user123", "no_such_file.txt").await;
        assert!(res.is_err());
    }

    #[tokio::test]
    async fn test_upload_voice_invalid_format() {
        let bot = create_dummy_bot();
        let temp_dir = tempdir().unwrap();
        let file_path = temp_dir.path().join("voice.txt");
        fs::write(&file_path, "test").unwrap();
        let res = upload_voice(&bot, "user123", file_path.to_str().unwrap()).await;
        assert!(res.is_err());
    }

    #[tokio::test]
    async fn test_download_and_save_file_invalid_dir() {
        let bot = create_dummy_bot();
        let res = download_and_save_file(&bot, "fileid123", "/no/such/dir").await;
        assert!(res.is_err());
    }

    proptest! {
        #[test]
        fn prop_upload_file_random_path(user_id in ".{0,32}", file_path in ".{0,128}") {
            let bot = create_dummy_bot();
            let fut = upload_file(&bot, &user_id, &file_path);
            let res = block_on(fut);
            prop_assert!(res.is_err());
        }

        #[test]
        fn prop_upload_voice_random_path(user_id in ".{0,32}", file_path in ".{0,128}") {
            let bot = create_dummy_bot();
            let fut = upload_voice(&bot, &user_id, &file_path);
            let res = block_on(fut);
            prop_assert!(res.is_err());
        }
    }
}

#[cfg(test)]
mod more_edge_tests {
    use super::*;
    use std::fs::{self, File};
    use std::io::Write;
    use std::os::unix::fs::PermissionsExt;
    use tempfile::tempdir;

    #[tokio::test]
    async fn test_download_and_save_file_api_error() {
        let bot =
            Bot::with_params(&APIVersionUrl::V1, "dummy_token", "https://dummy.api.com").unwrap();
        let tmp = tempdir().unwrap();
        let res = download_and_save_file(&bot, "fileid", tmp.path().to_str().unwrap()).await;
        assert!(res.is_err());
    }

    #[tokio::test]
    async fn test_download_and_save_file_write_error() {
        let bot =
            Bot::with_params(&APIVersionUrl::V1, "dummy_token", "https://dummy.api.com").unwrap();
        let tmp = tempdir().unwrap();
        let dir = tmp.path().join("readonly");
        fs::create_dir(&dir).unwrap();
        let mut perms = fs::metadata(&dir).unwrap().permissions();
        perms.set_mode(0o400); // read-only
        fs::set_permissions(&dir, perms).unwrap();
        let res = download_and_save_file(&bot, "fileid", dir.to_str().unwrap()).await;
        assert!(res.is_err());
    }

    #[tokio::test]
    async fn test_upload_file_api_error() {
        let bot =
            Bot::with_params(&APIVersionUrl::V1, "dummy_token", "https://dummy.api.com").unwrap();
        let tmp = tempdir().unwrap();
        let file_path = tmp.path().join("file.txt");
        File::create(&file_path).unwrap();
        let res = upload_file(&bot, "user123", file_path.to_str().unwrap()).await;
        assert!(res.is_err());
    }

    #[tokio::test]
    async fn test_upload_file_too_large() {
        let bot =
            Bot::with_params(&APIVersionUrl::V1, "dummy_token", "https://dummy.api.com").unwrap();
        let tmp = tempdir().unwrap();
        let file_path = tmp.path().join("bigfile.bin");
        let mut f = File::create(&file_path).unwrap();
        f.write_all(&vec![0u8; 200 * 1024 * 1024]).unwrap(); // 200MB
        let res = upload_file(&bot, "user123", file_path.to_str().unwrap()).await;
        assert!(res.is_err());
    }
}

#[cfg(test)]
mod happy_path_tests {
    use super::*;
    use crate::utils::create_dummy_bot;
    use std::fs;
    use tempfile::tempdir;

    #[tokio::test]
    async fn test_upload_file_success() {
        let bot = create_dummy_bot();
        let temp_dir = tempdir().unwrap();
        let file_path = temp_dir.path().join("file.txt");
        fs::write(&file_path, "test").unwrap();
        // This will fail on real API, but for dummy bot we expect an error or Ok depending on mock
        let _ = upload_file(&bot, "user123", file_path.to_str().unwrap()).await;
        // No panic means the function handles the flow
    }

    #[tokio::test]
    async fn test_upload_voice_success() {
        let bot = create_dummy_bot();
        let temp_dir = tempdir().unwrap();
        let file_path = temp_dir.path().join("voice.ogg");
        fs::write(&file_path, "test").unwrap();
        let _ = upload_voice(&bot, "user123", file_path.to_str().unwrap()).await;
    }

    #[tokio::test]
    async fn test_download_and_save_file_success() {
        let bot = create_dummy_bot();
        let temp_dir = tempdir().unwrap();
        // File ID is dummy, but function should handle the flow without panic
        let _ = download_and_save_file(&bot, "fileid123", temp_dir.path().to_str().unwrap()).await;
    }
}