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
use std::error::Error;
use std::fmt;
use crate::config::*;
use normalize_url::normalizer;
use reqwest;
use reqwest::header::{AUTHORIZATION, CONTENT_TYPE};
use serde_json::{self, Value};
pub mod connector;
pub mod frame;
pub mod image;
pub mod item;
pub mod shape;
pub mod sticky_note;
use error_stack::{Report, Result, ResultExt};
#[derive(Debug)]
pub struct MiroError;
impl fmt::Display for MiroError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Miro error")
}
}
impl Error for MiroError {}
pub struct MiroConfig {
access_token: String,
board_id: String,
board_url: String,
}
pub type MiroApiResult = Result<reqwest::Response, MiroError>;
pub type MiroResult<T> = Result<T, MiroError>;
impl MiroConfig {
pub fn new() -> Result<Self, MiroError> {
Self::check_miro_enabled()?;
let bat_config = BatConfig::get_config().change_context(MiroError)?;
let bat_auditor_config = BatAuditorConfig::get_config().change_context(MiroError)?;
let access_token = bat_auditor_config.miro_oauth_access_token;
let board_url = bat_config.miro_board_url;
let board_id = Self::get_miro_board_id(board_url.clone())?;
Ok(MiroConfig {
access_token,
board_id,
board_url,
})
}
pub fn parse_response_from_miro(
response: std::result::Result<reqwest::Response, reqwest::Error>,
) -> Result<reqwest::Response, MiroError> {
match response {
Ok(resp) => Ok(resp),
Err(error) => {
let message = "Bad response from Miro";
log::error!("Miro response: \n {:#?}", error);
Err(Report::new(MiroError).attach_printable(message))
}
}
}
pub fn miro_enabled(&self) -> bool {
!self.access_token.is_empty()
}
pub fn check_miro_enabled() -> Result<(), MiroError> {
let bat_auditor_config = BatAuditorConfig::get_config().unwrap();
if bat_auditor_config.miro_oauth_access_token.is_empty() {
return Err(Report::new(MiroError)
.attach_printable("miro_oauth_access_token is empty in BatAuditor.toml"));
};
Ok(())
}
pub fn get_frame_url(&self, frame_id: &str) -> String {
let url = normalizer::UrlNormalizer::new(
format!("{}/?moveToWidget={frame_id}", self.board_url).as_str(),
)
.unwrap()
.normalize(None)
.unwrap();
url
}
pub fn get_miro_board_id(miro_board_url: String) -> Result<String, MiroError> {
let _error_msg = format!(
"Error obtaining the miro board id for the url: {}",
miro_board_url
);
let miro_board_id = miro_board_url
.split("board/")
.last()
.ok_or(MiroError)?
.split('/')
.next()
.ok_or(MiroError)?
.to_string();
Ok(miro_board_id)
}
/// Fetches the user's boards from the Miro API using the given OAuth token.
/// Returns a list of (board_name, board_url) tuples.
pub async fn list_boards(access_token: &str) -> Result<Vec<(String, String)>, MiroError> {
let client = reqwest::Client::new();
let mut all_boards: Vec<(String, String)> = vec![];
let mut offset: usize = 0;
let limit = 50;
loop {
let response = client
.get(format!(
"https://api.miro.com/v2/boards?limit={}&offset={}&sort=last_modified",
limit, offset
))
.header(AUTHORIZATION, format!("Bearer {}", access_token))
.header(CONTENT_TYPE, "application/json")
.send()
.await
.map_err(|e| {
log::error!("Miro list boards error: {:#?}", e);
Report::new(MiroError).attach_printable("Failed to fetch boards from Miro")
})?;
let body = response.text().await.map_err(|_| {
Report::new(MiroError).attach_printable("Failed to read Miro response body")
})?;
let json: Value = serde_json::from_str(&body).map_err(|_| {
Report::new(MiroError).attach_printable("Failed to parse Miro response JSON")
})?;
let data = json["data"].as_array().ok_or_else(|| {
Report::new(MiroError).attach_printable("No 'data' array in Miro response")
})?;
if data.is_empty() {
break;
}
for board in data {
let name = board["name"].as_str().unwrap_or("(unnamed)").to_string();
let id = board["id"].as_str().unwrap_or("").to_string();
if !id.is_empty() {
let url = format!("https://miro.com/app/board/{}/", id);
all_boards.push((name, url));
}
}
let total = json["total"].as_u64().unwrap_or(0) as usize;
offset += limit;
if offset >= total {
break;
}
}
Ok(all_boards)
}
}
#[derive(Debug, Clone)]
pub struct MiroObject {
pub item_id: String,
pub title: String,
pub height: u64,
pub width: u64,
pub x_position: i64,
pub y_position: i64,
pub item_type: MiroItemType,
}
impl MiroObject {
pub fn new(
item_id: String,
title: String,
height: u64,
width: u64,
x_position: i64,
y_position: i64,
item_type: MiroItemType,
) -> Self {
Self {
item_id,
title,
height,
width,
x_position,
y_position,
item_type,
}
}
pub async fn multiple_from_response(
response: reqwest::Response,
) -> Result<Vec<Self>, MiroError> {
let response_string = response.text().await.unwrap();
let response: Value = serde_json::from_str(response_string.as_str()).unwrap();
let data = response["data"].as_array().unwrap();
let objects = data
.clone()
.into_iter()
.map(|data_response| {
let item_id = data_response["id"].to_string().replace('\"', "");
let item_type = data_response["type"].to_string().replace('\"', "");
let title = data_response["data"]["title"].to_string().replace('\"', "");
let height = data_response["geometry"]["height"].as_f64().unwrap() as u64;
let width = data_response["geometry"]["width"].as_f64().unwrap() as u64;
let x_position = data_response["position"]["x"].as_f64().unwrap() as i64;
let y_position = data_response["position"]["y"].as_f64().unwrap() as i64;
MiroObject::new(
item_id,
title,
height,
width,
x_position,
y_position,
MiroItemType::from_str(&item_type),
)
})
.collect();
Ok(objects)
}
}
#[derive(Debug, Clone)]
pub enum MiroItemType {
AppCard,
Card,
Document,
Embed,
Frame,
Image,
Shape,
StickyNote,
Text,
}
impl MiroItemType {
pub fn to_string(&self) -> String {
match self {
MiroItemType::AppCard => "app_card".to_string(),
MiroItemType::Card => "card".to_string(),
MiroItemType::Document => "document".to_string(),
MiroItemType::Embed => "embed".to_string(),
MiroItemType::Frame => "frame".to_string(),
MiroItemType::Image => "image".to_string(),
MiroItemType::Shape => "shape".to_string(),
MiroItemType::StickyNote => "sticky_note".to_string(),
MiroItemType::Text => "text".to_string(),
}
}
pub fn from_str(type_str: &str) -> MiroItemType {
match type_str {
"app_card" => MiroItemType::AppCard,
"card" => MiroItemType::Card,
"document" => MiroItemType::Document,
"embed" => MiroItemType::Embed,
"frame" => MiroItemType::Frame,
"image" => MiroItemType::Image,
"shape" => MiroItemType::Shape,
"sticky_note" => MiroItemType::StickyNote,
"text" => MiroItemType::Text,
_ => unimplemented!(),
}
}
}
#[derive(Clone)]
pub enum MiroColor {
Gray,
LightYellow,
Yellow,
Orange,
LightGreen,
Green,
DarkGreen,
Cyan,
LightPink,
Pink,
Violet,
Red,
LightBlue,
Blue,
DarkBlue,
Black,
}
impl MiroColor {
pub fn to_str(&self) -> &str {
match self {
MiroColor::Gray => "gray",
MiroColor::LightYellow => "light_yellow",
MiroColor::Yellow => "yellow",
MiroColor::Orange => "orange",
MiroColor::LightGreen => "light_green",
MiroColor::Green => "green",
MiroColor::DarkGreen => "dark_green",
MiroColor::Cyan => "cyan",
MiroColor::LightPink => "light_pink",
MiroColor::Pink => "pink",
MiroColor::Violet => "violet",
MiroColor::Red => "red",
MiroColor::LightBlue => "light_blue",
MiroColor::Blue => "blue",
MiroColor::DarkBlue => "dark_blue",
MiroColor::Black => "black",
}
}
pub fn from_str(color_str: &str) -> MiroColor {
match color_str {
"gray" => MiroColor::Gray,
"light_yellow" => MiroColor::LightYellow,
"yellow" => MiroColor::Yellow,
"orange" => MiroColor::Orange,
"light_green" => MiroColor::LightGreen,
"green" => MiroColor::Green,
"dark_green" => MiroColor::DarkGreen,
"cyan" => MiroColor::Cyan,
"light_pink" => MiroColor::LightPink,
"pink" => MiroColor::Pink,
"violet" => MiroColor::Violet,
"red" => MiroColor::Red,
"light_blue" => MiroColor::LightBlue,
"blue" => MiroColor::Blue,
"dark_blue" => MiroColor::DarkBlue,
"black" => MiroColor::Black,
_ => unimplemented!(),
}
}
pub fn get_colors_vec() -> Vec<String> {
vec![
"gray".to_string(),
"light_yellow".to_string(),
"yellow".to_string(),
"orange".to_string(),
"light_green".to_string(),
"green".to_string(),
"dark_green".to_string(),
"cyan".to_string(),
"light_pink".to_string(),
"pink".to_string(),
"violet".to_string(),
"red".to_string(),
"light_blue".to_string(),
"blue".to_string(),
"dark_blue".to_string(),
"black".to_string(),
]
}
}
use self::item::MiroItem;
pub mod helpers {
use error_stack::Report;
use super::*;
// pub fn get_data_for_snapshots(
// co_file_string: String,
// selected_co_started_path: String,
// selected_folder_name: String,
// snapshot_name: String,
// ) -> Result<(String, String, String, Option<usize>), String> {
// if snapshot_name == CONTEXT_ACCOUNTS_PNG_NAME {
// let context_account_lines = get_string_between_two_str_from_string(
// co_file_string,
// "# Context Accounts:",
// "# Validations:",
// )?;
// let snapshot_image_path = selected_co_started_path.replace(
// format!("{}.md", selected_folder_name).as_str(),
// "context_accounts.png",
// );
// let snapshot_markdown_path = selected_co_started_path.replace(
// format!("{}.md", selected_folder_name).as_str(),
// "context_accounts.md",
// );
// Ok((
// context_account_lines
// .replace("\n```rust", "")
// .replace("\n```", ""),
// snapshot_image_path,
// snapshot_markdown_path,
// None,
// ))
// } else if snapshot_name == VALIDATIONS_PNG_NAME {
// let validation_lines = get_string_between_two_str_from_string(
// co_file_string,
// "# Validations:",
// "# Miro board frame:",
// )?;
// let snapshot_image_path = selected_co_started_path.replace(
// format!("{}.md", selected_folder_name).as_str(),
// "validations.png",
// );
// let snapshot_markdown_path = selected_co_started_path.replace(
// format!("{}.md", selected_folder_name).as_str(),
// "validations.md",
// );
// Ok((
// validation_lines,
// snapshot_image_path,
// snapshot_markdown_path,
// None,
// ))
// } else if snapshot_name == ENTRYPOINT_PNG_NAME {
// let RequiredConfig {
// program_lib_path, ..
// } = BatConfig::get_validated_config()?.required;
// let lib_file_string = fs::read_to_string(program_lib_path.clone()).unwrap();
// let start_entrypoint_index = lib_file_string
// .lines()
// .into_iter()
// .position(|f| f.contains("pub fn") && f.contains(&selected_folder_name))
// .unwrap();
// let end_entrypoint_index = lib_file_string
// .lines()
// .into_iter()
// .enumerate()
// .position(|(f_index, f)| f.trim() == "}" && f_index > start_entrypoint_index)
// .unwrap();
// let entrypoint_lines = get_string_between_two_index_from_string(
// lib_file_string,
// start_entrypoint_index,
// end_entrypoint_index,
// )?;
// let snapshot_image_path = selected_co_started_path.replace(
// format!("{}.md", selected_folder_name).as_str(),
// "entrypoint.png",
// );
// let snapshot_markdown_path = selected_co_started_path.replace(
// format!("{}.md", selected_folder_name).as_str(),
// "entrypoint.md",
// );
// Ok((
// format!(
// "///{}\n\n{}",
// program_lib_path.replace("../", ""),
// entrypoint_lines,
// ),
// snapshot_image_path,
// snapshot_markdown_path,
// Some(start_entrypoint_index - 1),
// ))
// } else {
// //
// let (handler_string, instruction_file_path, start_index, _) =
// batbelt::helpers::get::get_instruction_handler_of_entrypoint(
// selected_folder_name.clone(),
// )?;
// let snapshot_image_path = selected_co_started_path.replace(
// format!("{}.md", selected_folder_name.clone()).as_str(),
// "handler.png",
// );
// let snapshot_markdown_path = selected_co_started_path.replace(
// format!("{}.md", selected_folder_name).as_str(),
// "handler.md",
// );
// // Handler
// Ok((
// format!("///{}\n\n{}", instruction_file_path, handler_string),
// snapshot_image_path,
// snapshot_markdown_path,
// Some(start_index - 1),
// ))
// }
// }
// pub fn create_co_figure(
// contents: String,
// image_path: String,
// temporary_markdown_path: String,
// index: Option<usize>,
// ) {
// // write the temporary markdown file
// fs::write(temporary_markdown_path.clone(), contents).unwrap();
// // take the snapshot
// if let Some(offset) = index {
// take_silicon_snapshot(image_path.clone(), temporary_markdown_path.clone(), offset);
// } else {
// take_silicon_snapshot(image_path.clone(), temporary_markdown_path.clone(), 1);
// }
//
// // delete the markdown
// delete_file(temporary_markdown_path);
// }
// pub fn take_silicon_snapshot<'a>(
// image_path: String,
// temporary_markdown_path: String,
// index: usize,
// ) {
// let offset = format!("{}", index);
// let image_file_name = image_path.split("/").last().unwrap();
// let mut args = vec![
// "--no-window-controls",
// "--language",
// "Rust",
// "--line-offset",
// &offset,
// "--theme",
// "Monokai Extended",
// "--pad-horiz",
// "40",
// "--pad-vert",
// "40",
// "--background",
// "#d3d4d5",
// "--font",
// match image_file_name {
// ENTRYPOINT_PNG_NAME => "Hack=15",
// CONTEXT_ACCOUNTS_PNG_NAME => "Hack=15",
// VALIDATIONS_PNG_NAME => "Hack=14",
// HANDLER_PNG_NAME => "Hack=11",
// _ => "Hack=13",
// },
// "--output",
// &image_path,
// &temporary_markdown_path,
// ];
// if index == 1 {
// args.insert(0, "--no-line-number");
// }
// std::process::Command::new("silicon")
// .args(args)
// .output()
// .unwrap();
// // match output {
// // Ok(_) => println!(""),
// // Err(_) => false,
// // }
// }
// pub fn delete_file(path: String) {
// std::process::Command::new("rm")
// .args([path])
// .output()
// .unwrap();
// }
// pub fn check_silicon_installed() -> bool {
// let output = std::process::Command::new("silicon")
// .args(["--version"])
// .output();
// match output {
// Ok(_) => true,
// Err(_) => false,
// }
// }
// pub fn get_item_id_from_miro_url(miro_url: &str) -> String {
// // example https://miro.com/app/board/uXjVP7aqTzc=/?moveToWidget=3458764541840480526&cot=14
// let frame_id = Url::parse(miro_url).unwrap();
// let hash_query: HashMap<_, _> = frame_id.query_pairs().into_owned().collect();
// hash_query.get("moveToWidget").unwrap().to_owned()
// }
pub async fn get_id_from_response(
response: Result<reqwest::Response, reqwest::Error>,
) -> Result<String, MiroError> {
match response {
Ok(response) => {
let response_string = response.text().await.unwrap();
let response: Value = serde_json::from_str(response_string.as_str()).unwrap();
Ok(response["id"].to_string().replace('\"', ""))
}
Err(err_message) => {
Err(Report::new(MiroError).attach_printable(err_message.to_string()))
}
}
}
// pub fn get_frame_id_from_co_file(entrypoint_name: &str) -> Result<String, String> {
// // let started_file_path = utils::path::get_auditor_code_overhaul_started_file_path(
// // Some(entrypoint_name.to_string()),
// // )?;
// let started_file_path = batbelt::path::get_file_path(
// FilePathType::CodeOverhaulStarted {
// file_name: entrypoint_name.to_string(),
// },
// true,
// );
// let miro_url = fs::read_to_string(started_file_path)
// .unwrap()
// .lines()
// .find(|line| line.contains("https://miro.com/app/board/"))
// .unwrap()
// .to_string();
// let frame_id = miro_url
// .split("moveToWidget=")
// .last()
// .unwrap()
// .to_string()
// .replace("\"", "");
// Ok(frame_id)
// }
}
// #[test]
//
// fn test_get_miro_item_id_from_url() {
// let miro_url =
// "https://miro.com/app/board/uXjVPvhKFIg=/?moveToWidget=3458764544363318703&cot=14";
// let item_id = helpers::get_item_id_from_miro_url(miro_url);
// println!("item id: {}", item_id);
// assert_eq!(item_id, "3458764541840480526".to_string())
// }