e62rs 1.5.0

An in-terminal E621/926 browser.
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! blacklist manager ui
use {
    crate::{
        config::blacklist::{add_to_blacklist, clear_blacklist, remove_from_blacklist},
        error::{Report, Result},
        getopt,
        ui::{E6Ui, autocomplete::TagAutocompleter, menus::BlacklistManager},
    },
    bearask::{AskOption, Confirm, MultiSelect, Select, TextInput},
    color_eyre::eyre::Context,
    hashbrown::HashSet,
    std::sync::Arc,
};

/// functions for blacklist management
pub trait BlacklistMenu {
    /// show info about the blacklist
    ///
    /// displays a list of blacklist rules
    /// and the total amount of rules
    fn show_blacklist_info(&self) -> Result<()>;

    /// show the blacklist manager ui
    ///
    /// * [`BlacklistManager::ShowCurrent`] displays info about the current blacklist
    /// * [`BlacklistManager::AddTag`] lets the user add a tag to the blacklist
    /// * [`BlacklistManager::RemoveTag`] lets the user remove a tag from the blacklist
    /// * [`BlacklistManager::Clear`] removes all tags from the blacklist
    /// * [`BlacklistManager::ImportFromSearch`] lets the user import tags from a search
    /// * [`BlacklistManager::Back`] goes back to the main menu
    fn manage_blacklist(&self) -> impl Future<Output = Result<()>>;

    /// ask whether to continue managing the blacklist
    fn prompt_continue(&self) -> Result<bool>;

    /// add a tag to the blacklist
    fn add_tag_to_blacklist(&self) -> impl Future<Output = Result<()>>;

    /// ask whether to add a tag not in the tags database
    ///
    /// # Arguments
    ///
    /// * `tag` - the tag to ask about
    fn prompt_add_unknown_tag(&self, tag: &str) -> impl Future<Output = Result<bool>>;

    /// add a validated tag to the blacklist
    ///
    /// # Arguments
    ///
    /// * `tag` - the tag to add
    fn add_validated_tag_to_blacklist(&self, tag: String) -> impl Future<Output = Result<()>>;

    /// remove a tag from the blacklist
    fn remove_tag_from_blacklist(&self) -> impl Future<Output = Result<()>>;

    /// clear all tags from the blacklist
    fn clear_blacklist(&self) -> impl Future<Output = Result<()>>;

    /// import tags from a search to the blacklist
    fn import_tags_to_blacklist(&self) -> impl Future<Output = Result<()>>;
}

impl BlacklistMenu for E6Ui {
    /// show info about the blacklist
    ///
    /// displays a list of blacklist rules
    /// and the total amount of rules
    fn show_blacklist_info(&self) -> Result<()> {
        let blacklist = getopt!(search.blacklist);

        if blacklist.is_empty() {
            println!("blacklist is empty.");
            return Ok(());
        }

        println!("Current blacklisted tags ({} total):", blacklist.len());
        for (i, tag) in blacklist.iter().enumerate() {
            println!("  {}. {}", i + 1, tag);
        }
        println!(
            "\nNote: Posts with these tags will be filtered out unless explicitly searched for."
        );

        Ok(())
    }

    /// show the blacklist manager ui
    ///
    /// * [`BlacklistManager::ShowCurrent`] displays info about the current blacklist
    /// * [`BlacklistManager::AddTag`] lets the user add a tag to the blacklist
    /// * [`BlacklistManager::RemoveTag`] lets the user remove a tag from the blacklist
    /// * [`BlacklistManager::Clear`] removes all tags from the blacklist
    /// * [`BlacklistManager::ImportFromSearch`] lets the user import tags from a search
    /// * [`BlacklistManager::Back`] goes back to the main menu
    async fn manage_blacklist(&self) -> Result<()> {
        loop {
            let blacklist_action = miette::Context::wrap_err(
                BlacklistManager::select("Blacklist Settings:").ask(),
                "Failed to display blacklist menu",
            )?;

            let should_continue = match blacklist_action.value {
                BlacklistManager::ShowCurrent => {
                    self.show_blacklist_info()?;
                    self.prompt_continue()?
                }
                BlacklistManager::AddTag => {
                    self.add_tag_to_blacklist().await?;
                    self.prompt_continue()?
                }
                BlacklistManager::RemoveTag => {
                    self.remove_tag_from_blacklist().await?;
                    self.prompt_continue()?
                }
                BlacklistManager::Clear => {
                    self.clear_blacklist().await?;
                    self.prompt_continue()?
                }
                BlacklistManager::ImportFromSearch => {
                    self.import_tags_to_blacklist().await?;
                    self.prompt_continue()?
                }
                BlacklistManager::Back => break,
            };

            if !should_continue {
                break;
            }
        }

        Ok(())
    }

    /// ask whether to continue managing the blacklist
    fn prompt_continue(&self) -> Result<bool> {
        miette::Context::wrap_err(
            Confirm::new("Continue managing blacklist?").ask(),
            "Failed to get user input",
        )
        .map_err(Report::new)
    }

    /// add a tag to the blacklist
    async fn add_tag_to_blacklist(&self) -> Result<()> {
        let tag_db = Arc::clone(&self.tag_db);
        let completer = TagAutocompleter::new(tag_db);

        let tag = miette::Context::wrap_err(
            TextInput::new("Enter a tag to add to the blacklist:")
                .with_autocomplete(completer)
                .ask(),
            "Failed to get tag input",
        )?;

        let tag = tag.trim();

        if tag.is_empty() {
            println!("Tag cannot be empty.");
            return Ok(());
        }

        let tag = tag.to_string();
        let blacklist = getopt!(search.blacklist);

        if blacklist.contains(&tag) {
            println!("Tag '{}' is already in the blacklist.", tag);
            return Ok(());
        }

        if !self.tag_db.exists(&tag) && !self.prompt_add_unknown_tag(&tag).await? {
            return Ok(());
        }

        self.add_validated_tag_to_blacklist(tag).await
    }

    /// ask whether to add a tag not in the tags database
    ///
    /// # Arguments
    ///
    /// * `tag` - the tag to ask about
    async fn prompt_add_unknown_tag(&self, tag: &str) -> Result<bool> {
        let use_anyway = miette::Context::wrap_err(
            Confirm::new(format!(
                "Tag '{}' not found in database. Add to blacklist anyway?",
                tag
            ))
            .ask(),
            "Failed to get user confirmation",
        )?;

        if use_anyway {
            return Ok(true);
        }

        let suggestions = self
            .tag_db
            .search(tag, 5)
            .iter()
            .map(|s| AskOption::with_name(s.clone(), s.clone()))
            .collect::<Vec<_>>();
        if suggestions.is_empty() {
            return Ok(false);
        }

        let selected = miette::Context::wrap_err(
            Select::new("Did you mean one of these tags?")
                .with_options(suggestions)
                .with_help_message("Select a tag or press ESC to cancel")
                .ask(),
            "Failed to display tag suggestions",
        )?
        .value;

        if !selected.is_empty() {
            self.add_validated_tag_to_blacklist(selected.to_string())
                .await?;
        }

        Ok(false)
    }

    /// add a validated tag to the blacklist
    ///
    /// # Arguments
    ///
    /// * `tag` - the tag to add
    async fn add_validated_tag_to_blacklist(&self, tag: String) -> Result<()> {
        add_to_blacklist(tag.clone())
            .wrap_err_with(|| format!("Failed to add '{}' to blacklist", tag))?;

        println!(
            "Successfully added '{}' to blacklist and saved configuration.",
            tag
        );
        Ok(())
    }

    /// remove a tag from the blacklist
    async fn remove_tag_from_blacklist(&self) -> Result<()> {
        let blacklist = getopt!(search.blacklist);

        if blacklist.is_empty() {
            println!("Blacklist is empty. Nothing to remove.");
            return Ok(());
        }

        let tag_to_remove = miette::Context::wrap_err(
            Select::new("Select tag to remove from blacklist:")
                .with_options(
                    blacklist
                        .iter()
                        .map(|t| AskOption::with_name(t.clone(), t.clone()))
                        .collect(),
                )
                .with_help_message("Use arrow keys to navigate, Enter to select, Esc to cancel")
                .ask(),
            "Failed to display tag selection",
        )?
        .value;

        if tag_to_remove.is_empty() {
            return Ok(());
        }

        let confirm = miette::Context::wrap_err(
            Confirm::new(format!("Remove '{}' from blacklist?", tag_to_remove)).ask(),
            "Failed to get user confirmation",
        )?;

        if !confirm {
            return Ok(());
        }

        match remove_from_blacklist(tag_to_remove.clone().as_str()) {
            Ok(true) => {
                println!(
                    "Successfully removed '{}' from blacklist and saved configuration.",
                    tag_to_remove
                );
            }
            Ok(false) => {
                println!("Tag '{}' was not found in blacklist.", tag_to_remove);
            }
            Err(e) => {
                return Err(e)
                    .wrap_err_with(|| {
                        format!("failed to remove '{}' from blacklist", tag_to_remove)
                    })
                    .map_err(Report::new);
            }
        }

        Ok(())
    }

    /// clear all tags from the blacklist
    async fn clear_blacklist(&self) -> Result<()> {
        let blacklist = getopt!(search.blacklist);
        let blacklist_count = blacklist.len();

        if blacklist_count == 0 {
            println!("Blacklist is already empty.");
            return Ok(());
        }

        let confirm = miette::Context::wrap_err(
            Confirm::new(format!(
                "Clear all {} tags from blacklist? This cannot be undone.",
                blacklist_count
            ))
            .ask(),
            "Failed to get user confirmation",
        )?;

        if !confirm {
            return Ok(());
        }

        clear_blacklist().wrap_err("Failed to clear blacklist")?;

        println!("Successfully cleared blacklist and saved configuration.");
        Ok(())
    }

    /// import tags from a search to the blacklist
    async fn import_tags_to_blacklist(&self) -> Result<()> {
        let blacklist = getopt!(search.blacklist);

        println!("This will allow you to search for posts and add their tags to the blacklist.");

        let (include_tags, _, exclude_tags) = self
            .collect_tags()
            .wrap_err("Failed to collect search tags")?;

        if include_tags.is_empty() && exclude_tags.is_empty() {
            println!("No search tags provided.");
            return Ok(());
        }

        let mut search_tags = include_tags.clone();
        search_tags.extend(exclude_tags.iter().map(|tag| format!("-{}", tag)));

        let results = self
            .client
            .search_posts(&search_tags, Some(10), None)
            .await
            .wrap_err("Failed to search posts")?;

        if results.posts.is_empty() {
            println!("No posts found for the given search.");
            return Ok(());
        }

        let mut all_tags = HashSet::new();
        for post in &results.posts {
            all_tags.extend(post.tags.general.iter().cloned());
            all_tags.extend(post.tags.artist.iter().cloned());
            all_tags.extend(post.tags.character.iter().cloned());
            all_tags.extend(post.tags.species.iter().cloned());
            all_tags.extend(post.tags.copyright.iter().cloned());
            all_tags.extend(post.tags.meta.iter().cloned());
            all_tags.extend(post.tags.lore.iter().cloned());
        }

        for search_tag in &include_tags {
            all_tags.remove(search_tag);
        }

        let mut sorted_tags: Vec<String> = all_tags.into_iter().collect();
        sorted_tags.sort();

        if sorted_tags.is_empty() {
            println!("No additional tags found to blacklist.");
            return Ok(());
        }

        let sorted_options = sorted_tags
            .iter()
            .map(|opt| AskOption::with_name(opt.clone(), opt.clone()))
            .collect::<Vec<_>>();

        let selected_tags = miette::Context::wrap_err(
            MultiSelect::new(format!(
                "Select tags to add to blacklist ({} available):",
                sorted_tags.len()
            ))
            .with_options(sorted_options)
            .with_help_message("Space to select/deselect, Enter to confirm, Esc to cancel")
            .ask(),
            "Failed to display tag selection",
        )?;

        if selected_tags.is_empty() {
            println!("No tags selected.");
            return Ok(());
        }

        let confirm = miette::Context::wrap_err(
            Confirm::new(format!(
                "Add {} selected tags to blacklist?",
                selected_tags.len()
            ))
            .ask(),
            "Failed to get user confirmation",
        )?;

        if !confirm {
            return Ok(());
        }

        let mut added_count = 0;
        let mut already_exists = 0;
        let mut errors = Vec::new();

        for tag in selected_tags {
            let tag = tag.value;
            if blacklist.contains(&tag) {
                already_exists += 1;
                continue;
            }

            if let Err(e) = add_to_blacklist(tag.clone()) {
                errors.push((tag, e));
            } else {
                added_count += 1;
            }
        }

        println!("Added {} new tags to blacklist.", added_count);
        if already_exists > 0 {
            println!("{} tags were already in the blacklist.", already_exists);
        }
        if !errors.is_empty() {
            println!("Failed to add {} tags:", errors.len());
            for (tag, err) in errors {
                println!("  - '{}': {}", tag, err);
            }
        }
        println!("Configuration saved.");

        Ok(())
    }
}