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
use crate::colors::AnsiColor;
use crate::colors::AnsiStyle;
use crate::response::Response;
use crate::topic::Topic;
use reqwest;
const BASE_URL: &str = "https://api.duckduckgo.com/";
/// Enum representing different result formats for DuckDuckGo searches.
pub enum ResultFormat {
/// Display search results in a list format.
List,
/// Display search results in a detailed format.
Detailed,
}
/// A struct representing a browser for interacting with the DuckDuckGo API.
pub struct Browser {
/// The underlying HTTP client used for making requests.
pub client: reqwest::Client,
}
impl Browser {
/// Creates a new instance of `Browser` with the specified HTTP client.
///
/// # Arguments
/// * `client` - The reqwest HTTP client to be used for making requests.
///
/// # Examples
/// ```
/// use duckduckgo::browser::Browser;
/// use reqwest::Client;
///
/// let client = Client::new();
/// let browser = Browser::new(client);
/// ```
pub fn new(client: reqwest::Client) -> Self {
Browser { client }
}
/// Performs a DuckDuckGo search based on the provided path, result format, and optional result limit.
///
/// # Arguments
/// * `path` - The path to be appended to the DuckDuckGo API base URL.
/// * `result_format` - The format in which the search results should be displayed (List or Detailed).
/// * `limit` - Optional limit for the number of search results to be displayed.
///
/// # Returns
/// `Result<(), reqwest::Error>` - Result indicating success or failure of the search operation.
///
/// # Examples
/// ```
/// use duckduckgo::browser::{Browser, ResultFormat};
/// use reqwest::Client;
///
/// #[tokio::main]
/// async fn main() {
/// let client = Client::new();
/// let browser = Browser::new(client);
/// browser.browse("?q=Rust", ResultFormat::List, Some(5)).await.unwrap();
/// }
/// ```
pub async fn browse(
&self,
path: &str,
result_format: ResultFormat,
limit: Option<usize>,
) -> Result<(), reqwest::Error> {
let url = format!("{}{}&format=json", BASE_URL, path);
let response = self.client.get(&url).send().await?.text().await?;
let api_response: Response = serde_json::from_str(&response).unwrap();
match result_format {
ResultFormat::List => self.print_results_list(api_response, limit),
ResultFormat::Detailed => self.print_results_detailed(api_response, limit),
}
Ok(())
}
/// Prints search results in list format.
///
/// # Arguments
/// * `api_response` - The response from the DuckDuckGo API.
/// * `limit` - Optional limit for the number of search results to be displayed.
pub fn print_results_list(&self, api_response: Response, limit: Option<usize>) {
if let Some(heading) = api_response.heading {
let style = AnsiStyle {
bold: true,
color: Some(AnsiColor::Gold),
};
println!(
"{}{}{}",
style.escape_code(),
heading,
AnsiStyle::reset_code()
);
}
let topics = &api_response.related_topics;
for (index, topic) in topics
.iter()
.enumerate()
.take(limit.unwrap_or(topics.len()))
{
self.print_related_topic(index + 1, topic);
}
}
/// Prints a related topic in a detailed format.
///
/// # Arguments
/// * `index` - The index of the related topic.
/// * `topic` - The related topic to be printed.
pub fn print_related_topic(&self, index: usize, topic: &Topic) {
let style = AnsiStyle {
bold: false,
color: Some(AnsiColor::BrightGreen),
};
// Access fields directly instead of using `get`
let text = match &topic.text {
Some(t) => t,
None => {
return;
}
};
let first_url = match &topic.first_url {
Some(url) => url,
None => {
return;
}
};
println!("{}. {} {}", index, text, style.escape_code());
println!("URL: {}{}", first_url, style.escape_code());
if let Some(icon) = &topic.icon {
let style = AnsiStyle {
bold: false,
color: Some(AnsiColor::BrightBlue),
};
if !icon.url.is_empty() {
let full_url = format!("https://duckduckgo.com{}", icon.url);
println!("Image URL: {}{}", full_url, style.escape_code());
}
}
println!("--------------------------------------------");
}
/// Prints search results in detailed format.
///
/// # Arguments
/// * `api_response` - The response from the DuckDuckGo API.
/// * `limit` - Optional limit for the number of search results to be displayed.
pub fn print_results_detailed(&self, api_response: Response, limit: Option<usize>) {
if let Some(heading) = api_response.heading {
let style = AnsiStyle {
bold: true,
color: None,
};
println!(
"{}{}{}",
style.escape_code(),
heading,
AnsiStyle::reset_code()
);
}
if let Some(abstract_text) = api_response.abstract_text {
let style = AnsiStyle {
bold: false,
color: Some(AnsiColor::LightGray),
};
println!("Abstract: {}{}", abstract_text, style.escape_code());
}
if let Some(abstract_source) = api_response.abstract_source {
let style = AnsiStyle {
bold: false,
color: Some(AnsiColor::Purple),
};
println!(
"Abstract Source: {}{}",
abstract_source,
style.escape_code()
);
}
if let Some(abstract_url) = api_response.abstract_url {
let style = AnsiStyle {
bold: false,
color: Some(AnsiColor::Silver),
};
println!("Abstract URL: {}{}", abstract_url, style.escape_code());
}
if let Some(image) = api_response.image {
let style = AnsiStyle {
bold: false,
color: Some(AnsiColor::SkyBlue),
};
if !image.is_empty() {
let full_url = format!("https://duckduckgo.com{}", image);
println!("Image URL: {}{}", full_url, style.escape_code());
}
}
let topics = &api_response.related_topics;
for (index, topic) in topics
.iter()
.enumerate()
.take(limit.unwrap_or(topics.len()))
{
self.print_related_topic(index + 1, topic);
}
}
/// Performs a basic DuckDuckGo search with the provided parameters.
///
/// # Arguments
/// * `query` - The search query.
/// * `safe_search` - A boolean indicating whether safe search is enabled.
/// * `result_format` - The format in which the search results should be displayed (List or Detailed).
/// * `limit` - Optional limit for the number of search results to be displayed.
///
/// # Returns
/// `Result<(), reqwest::Error>` - Result indicating success or failure of the search operation.
///
/// # Examples
/// ```
/// use duckduckgo::browser::{Browser, ResultFormat};
/// use reqwest::Client;
///
/// #[tokio::main]
/// async fn main() {
/// let client = Client::new();
/// let browser = Browser::new(client);
/// browser.search("Rust", true, ResultFormat::Detailed, Some(5)).await.unwrap();
/// }
/// ```
pub async fn search(
&self,
query: &str,
safe_search: bool,
result_format: ResultFormat,
limit: Option<usize>,
) -> Result<(), reqwest::Error> {
let safe_param = if safe_search { "&kp=1" } else { "&kp=-2" }; // Enable or disable safe search
let path = format!("?q={}{}", query, safe_param);
self.browse(&path, result_format, limit).await
}
/// Performs an advanced DuckDuckGo search with additional parameters.
///
/// # Arguments
/// * `query` - The search query.
/// * `params` - Additional search parameters.
/// * `safe_search` - A boolean indicating whether safe search is enabled.
/// * `result_format` - The format in which the search results should be displayed (List or Detailed).
/// * `limit` - Optional limit for the number of search results to be displayed.
///
/// # Returns
/// `Result<(), reqwest::Error>` - Result indicating success or failure of the search operation.
///
/// # Examples
/// ```
/// use duckduckgo::browser::{Browser, ResultFormat};
/// use reqwest::Client;
///
/// #[tokio::main]
/// async fn main() {
/// let client = Client::new();
/// let browser = Browser::new(client);
/// browser.advanced_search("Rust", "lang:en", true, ResultFormat::Detailed, Some(5)).await.unwrap();
/// }
/// ```
pub async fn advanced_search(
&self,
query: &str,
params: &str,
safe_search: bool,
result_format: ResultFormat,
limit: Option<usize>,
) -> Result<(), reqwest::Error> {
let safe_param = if safe_search { "&kp=1" } else { "&kp=-2" }; // Enable or disable safe search
let path = format!("?q={}&kl={}{}", query, params, safe_param);
self.browse(&path, result_format, limit).await
}
/// Performs a DuckDuckGo search with custom search operators.
///
/// # Arguments
/// * `query` - The search query.
/// * `operators` - Custom search operators.
/// * `safe_search` - A boolean indicating whether safe search is enabled.
/// * `result_format` - The format in which the search results should be displayed (List or Detailed).
/// * `limit` - Optional limit for the number of search results to be displayed.
///
/// # Returns
/// `Result<(), reqwest::Error>` - Result indicating success or failure of the search operation.
///
/// # Examples
/// ```
/// use duckduckgo::browser::{Browser, ResultFormat};
/// use reqwest::Client;
///
/// #[tokio::main]
/// async fn main() {
/// let client = Client::new();
/// let browser = Browser::new(client);
/// browser.search_operators("Rust", "site:github.com", true, ResultFormat::List, Some(5)).await.unwrap();
/// }
/// ```
pub async fn search_operators(
&self,
query: &str,
operators: &str,
safe_search: bool,
result_format: ResultFormat,
limit: Option<usize>,
) -> Result<(), reqwest::Error> {
let safe_param = if safe_search { "&kp=1" } else { "&kp=-2" }; // Enable or disable safe search
let path = format!("?q={}&{}{}", query, operators, safe_param);
self.browse(&path, result_format, limit).await
}
}