aboutsummaryrefslogtreecommitdiffstats
path: root/src/commands.rs
blob: d82970ea669648c188e38493869f406869575346 (plain)
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
//! The commands, and the path a lookup follows:
//! cache → rae-api.com → dle.rae.es → offline suggestions.

use anyhow::{bail, Context, Result};

use crate::cache::Cache;
use crate::cli::Source;
use crate::client::{percent_encode, Http, BROWSER_UA};
use crate::config::Config;
use crate::model::Entry;
use crate::output::{self, Style};
use crate::{dle, raeapi, suggest, wiktionary};

const DLE_BASE: &str = "https://dle.rae.es";

pub struct Ctx {
    pub cfg: Config,
    pub http: Http,
    pub cache: Option<Cache>,
    pub style: Style,
    pub json: bool,
    pub expand_abbr: bool,
    pub refresh: bool,
    pub source: Source,
}

impl Ctx {
    /// Looks a word up. If it does not exist, returns a ready-to-print error
    /// with the closest suggestions from the local dictionary.
    pub fn lookup(&self, word: &str) -> Result<Entry> {
        let word = word.trim();
        if word.is_empty() {
            bail!("hay que indicar una palabra");
        }

        if !self.refresh {
            if let Some(c) = &self.cache {
                if let Some(hit) = c.get(word)? {
                    return Ok(hit);
                }
            }
        }

        let entry = self.fetch(word)?;
        match entry {
            Some(e) => {
                if let Some(c) = &self.cache {
                    // A failed write must not stop the word from being shown.
                    let _ = c.put(word, &e);
                }
                Ok(e)
            }
            None => bail!("{}", self.not_found_message(word)),
        }
    }

    /// Downloads the entry from the chosen source. `Ok(None)` = no such word.
    ///
    /// The default order is rae-api first: it serves the DLE content as JSON
    /// and accepts automated clients. dle.rae.es is the fallback because it
    /// answers with a Cloudflare challenge to anything but a browser, so most
    /// of the time it does not respond.
    fn fetch(&self, word: &str) -> Result<Option<Entry>> {
        match self.source {
            Source::Dle => self.fetch_dle(word),
            Source::RaeApi => raeapi::lookup(&self.http, word),
            Source::Auto => match raeapi::lookup(&self.http, word) {
                Ok(Some(e)) => Ok(Some(e)),
                Ok(None) => Ok(None),
                // The API failed: try the site, in case this client gets through.
                Err(first) => self.fetch_dle(word).map_err(|_| first),
            },
        }
    }

    fn fetch_dle(&self, word: &str) -> Result<Option<Entry>> {
        let url = format!("{DLE_BASE}/{}", percent_encode(word));
        let (status, body) = self.http.get(&url, BROWSER_UA)?;
        if status == 403 {
            bail!(
                "dle.rae.es rechazó la petición con un desafío de Cloudflare, \
                 que solo resuelve un navegador"
            );
        }
        if status != 200 {
            bail!("dle.rae.es respondió {status}");
        }
        if dle::is_not_found(&body) {
            return Ok(None);
        }
        match dle::parse(&body) {
            Some(e) if !e.senses.is_empty() => Ok(Some(e)),
            // A valid page we cannot read: let the caller decide.
            _ => bail!("no se pudo interpretar la página del DLE para «{word}»"),
        }
    }

    fn not_found_message(&self, word: &str) -> String {
        let mut msg = format!("«{word}» no está en el Diccionario");
        for s in self.suggestions(word) {
            msg.push_str(&format!("\n  ¿quiso decir {}?", self.style.cyan(&s)));
        }
        msg
    }

    /// Similar words, from the system hunspell dictionary.
    fn suggestions(&self, word: &str) -> Vec<String> {
        let path = self
            .cfg
            .dictionary
            .clone()
            .or_else(suggest::find_dictionary);
        let Some(path) = path else {
            return vec![];
        };
        let Ok(words) = suggest::load_words(&path) else {
            return vec![];
        };
        suggest::closest(word, &words, 4)
    }

    fn print_json<T: serde::Serialize>(&self, v: &T) -> Result<()> {
        println!("{}", serde_json::to_string_pretty(v)?);
        Ok(())
    }
}

pub fn define(ctx: &Ctx, word: &str) -> Result<()> {
    let e = ctx.lookup(word)?;
    if ctx.json {
        return ctx.print_json(&e);
    }
    print!("{}", output::entry(&e, &ctx.style, ctx.expand_abbr));
    Ok(())
}

pub fn synonyms(ctx: &Ctx, word: &str) -> Result<()> {
    let e = ctx.lookup(word)?;
    if ctx.json {
        #[derive(serde::Serialize)]
        struct Out<'a> {
            word: &'a str,
            synonyms: Vec<String>,
            antonyms: Vec<String>,
        }
        return ctx.print_json(&Out {
            word: &e.word,
            synonyms: e.all_synonyms(),
            antonyms: e.all_antonyms(),
        });
    }

    if !e.has_synonyms() && !e.has_antonyms() {
        println!(
            "{}",
            ctx.style
                .dim(&format!("«{}» no tiene sinónimos registrados", e.word))
        );
        return Ok(());
    }

    println!("{}\n", ctx.style.heading(&e.word));
    // Shown per sense: the synonyms of «casa» are not the same for
    // «building» as for «lineage».
    for s in &e.senses {
        if s.synonyms.is_empty() && s.antonyms.is_empty() {
            continue;
        }
        let num = s.number.clone().unwrap_or_default();
        let head = format!(
            "{}. {}",
            num,
            output::truncate(&s.text, ctx.style.width - 6)
        );
        println!("{}", ctx.style.dim(&head));
        if !s.synonyms.is_empty() {
            let joined = output::superscript_homographs(&s.synonyms.join(", "));
            let line = format!("{} {joined}", ctx.style.green("Sin.:"));
            println!(
                "{}",
                output::wrap(&line, ctx.style.width, "   ", "         ")
            );
        }
        if !s.antonyms.is_empty() {
            let joined = output::superscript_homographs(&s.antonyms.join(", "));
            let line = format!("{} {joined}", ctx.style.red("Ant.:"));
            println!(
                "{}",
                output::wrap(&line, ctx.style.width, "   ", "         ")
            );
        }
        println!();
    }
    Ok(())
}

pub fn conjugate(ctx: &Ctx, verb: &str, mood: Option<&str>) -> Result<()> {
    let Some(mut c) = wiktionary::conjugation(&ctx.http, verb)? else {
        bail!("«{verb}» no tiene tabla de conjugación (¿no es un verbo?)");
    };

    if let Some(m) = mood {
        let needle = suggest::fold(m);
        c.groups
            .retain(|g| suggest::fold(&g.title).contains(&needle));
        if c.groups.is_empty() {
            bail!("no hay ningún modo que se parezca a «{m}»");
        }
    }

    if ctx.json {
        return ctx.print_json(&c);
    }
    print!("{}", output::conjugation(&c, &ctx.style));
    Ok(())
}

/// The word of the day and the random word come from the rae-api index and
/// are then defined through the normal path.
pub fn featured(ctx: &Ctx, daily: bool) -> Result<()> {
    let word = if daily {
        raeapi::word_of_the_day(&ctx.http).context("no se pudo obtener la palabra del día")?
    } else {
        raeapi::random_word(&ctx.http).context("no se pudo obtener una palabra al azar")?
    };
    define(ctx, &word)
}

pub fn search(ctx: &Ctx, text: &str, max: usize) -> Result<()> {
    let Some(cache) = &ctx.cache else {
        bail!("`buscar` mira dentro de la caché, y está desactivada con --sin-cache");
    };