about summary refs log tree commit diff stats
path: root/src/videos/mod.rs
blob: 59baa8c41f9fc9a7ecafea302eb5ffd4e2463cca (plain) (blame)
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
// yt - A fully featured command line YouTube client
//
// Copyright (C) 2024 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Yt.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use anyhow::Result;
use display::{format_video::FormatVideo, FormattedVideo};
use futures::{stream::FuturesUnordered, TryStreamExt};
use nucleo_matcher::{
    pattern::{CaseMatching, Normalization, Pattern},
    Matcher,
};

pub mod display;

use crate::{
    app::App,
    storage::video_database::{getters::get_videos, VideoStatus},
};

pub async fn query(app: &App, limit: Option<usize>, search_query: Option<String>) -> Result<()> {
    let all_videos = get_videos(app, VideoStatus::ALL, None).await?;

    // turn one video to a color display, to pre-warm the hash shrinking cache
    if let Some(val) = all_videos.first() {
        val.to_formatted_video(app).await?;
    }

    let limit = limit.unwrap_or(all_videos.len());

    let all_video_strings: Vec<String> = all_videos
        .into_iter()
        .take(limit)
        .map(|vid| vid.to_formatted_video_owned(app))
        .collect::<FuturesUnordered<_>>()
        .try_collect::<Vec<FormattedVideo>>()
        .await?
        .into_iter()
        .map(|vid| (&vid.colorize()).to_line_display())
        .collect();

    if let Some(query) = search_query {
        let mut matcher = Matcher::new(nucleo_matcher::Config::DEFAULT.match_paths());

        let matches = Pattern::parse(
            &query.replace(' ', "\\ "),
            CaseMatching::Ignore,
            Normalization::Smart,
        )
        .match_list(all_video_strings, &mut matcher);

        matches
            .iter()
            .rev()
            .for_each(|(val, key)| println!("{} ({})", val, key));
    } else {
        println!("{}", all_video_strings.join("\n"))
    }

    Ok(())
}