-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcode.rs
More file actions
165 lines (138 loc) · 4.64 KB
/
code.rs
File metadata and controls
165 lines (138 loc) · 4.64 KB
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
use regex::{Match, Regex};
use std::str::FromStr;
use std::{path::Path, sync::OnceLock};
use poise::serenity_prelude::{self as serenity, Colour, Context, CreateEmbed, Message};
use crate::formatting::trim_indent;
/// A shade of purple.
const ACCENT_COLOUR: Colour = Colour::new(0x8957e5);
pub async fn message(ctx: &Context, message: &Message) {
if let Some(embeds) = get_embeds(ctx, message).await {
let typing = message.channel_id.start_typing(&ctx.http);
let content = serenity::CreateMessage::default()
.embeds(embeds)
.reference_message(message)
.allowed_mentions(serenity::CreateAllowedMentions::new().replied_user(false));
let _ = message.channel_id.send_message(ctx, content).await;
typing.stop();
}
}
async fn get_embeds(ctx: &Context, message: &Message) -> Option<Vec<CreateEmbed>> {
let typing = message.channel_id.start_typing(&ctx.http);
let mut embeds: Vec<CreateEmbed> = vec![];
if let Some(refs) = FileReference::try_from_str(&message.content) {
for file_ref in refs {
if let Some(embed) = file_ref.create_embed().await {
embeds.push(embed);
}
}
}
typing.stop();
if embeds.is_empty() {
None
} else {
Some(embeds)
}
}
async fn http_get_body_text(url: &String) -> Option<String> {
match reqwest::get(url).await {
Ok(res) => match res.text().await {
Ok(content) => Some(content),
Err(e) => {
println!("Failed to get text: {e}");
None
}
},
Err(e) => {
println!("Failed to get response: {e}");
None
}
}
}
fn try_parse<F: FromStr + Clone>(m: Option<Match>) -> Option<F> {
if let Some(m) = m {
if let Ok(f) = m.as_str().parse::<F>() {
return Some(f.to_owned());
}
}
None
}
struct FileReference<'a> {
owner: &'a str,
repo: &'a str,
git_ref: &'a str,
path: &'a str,
start: usize,
end: Option<usize>,
}
impl FileReference<'_> {
pub fn try_from_str(text: &str) -> Option<Vec<FileReference>> {
let r = get_file_reference_regex();
let files: Vec<FileReference> = r
.captures_iter(text)
.map(|capture| FileReference {
owner: capture.get(1).expect("Expected owner").as_str(),
repo: capture.get(2).expect("Expected repo").as_str(),
git_ref: capture.get(3).expect("Expected git ref").as_str(),
path: capture.get(4).expect("Expected file path").as_str(),
start: try_parse::<usize>(capture.get(5)).expect("Expected start line"),
end: try_parse::<usize>(capture.get(6)),
})
.collect();
if files.is_empty() {
None
} else {
Some(files)
}
}
pub async fn create_embed(&self) -> Option<CreateEmbed> {
let extension = self.get_extension();
if let Some(mut content) = self.display().await {
content.shrink_to(4096 - 8 - extension.len());
let description = format!("```{extension}\n{content}\n```");
let mut default = CreateEmbed::default();
default = default
.title(self.path)
.description(description)
.colour(ACCENT_COLOUR);
Some(default)
} else {
None
}
}
fn get_extension(&self) -> String {
Path::new(self.path)
.extension()
.unwrap_or_default()
.to_string_lossy()
.to_string()
}
pub async fn display(&self) -> Option<String> {
let url = format!(
"https://raw.githubusercontent.com/{}/{}/{}/{}",
self.owner, self.repo, self.git_ref, self.path
);
println!("Downloading content: {url}");
if let Some(content) = http_get_body_text(&url).await {
let lines: Vec<&str> = content.split('\n').collect();
let start = self.start - 1;
if let Some(end) = self.end {
if end <= start {
None
} else {
Some(trim_indent(&lines[start..end]))
}
} else {
Some(lines[start].trim_start().to_string())
}
} else {
None
}
}
}
fn get_file_reference_regex() -> &'static Regex {
static REGEX: OnceLock<Regex> = OnceLock::new();
REGEX.get_or_init(|| {
Regex::new(r"https://github.com/(.+?)/(.+?)/blob/(.+?)/(.+?)#L([0-9]+)(?:-L([0-9]+))?")
.unwrap()
})
}