about summary refs log tree commit diff stats
path: root/crates/yt/src/comments/mod.rs
blob: 876146d2c0ff0061f1829c2df3bc1d0cd9a3a8f3 (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
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
// yt - A fully featured command line YouTube client
//
// Copyright (C) 2024 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// Copyright (C) 2025 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 std::mem;

use anyhow::{Result, bail};
use comment::{Comment, CommentExt, Comments, Parent};
use output::display_fmt_and_less;
use regex::Regex;
use yt_dlp::{InfoJson, json_cast};

use crate::{
    app::App,
    storage::video_database::{Video, get},
    unreachable::Unreachable,
};

mod comment;
mod display;
pub mod output;

pub mod description;
pub use description::*;

#[allow(clippy::too_many_lines)]
pub async fn get(app: &App) -> Result<Comments> {
    let currently_playing_video: Video =
        if let Some(video) = get::currently_focused_video(app).await? {
            video
        } else {
            bail!("Could not find a currently playing video!");
        };

    let info_json: InfoJson = get::video_info_json(&currently_playing_video)?.unreachable(
        "A currently *playing* video must be cached. And thus the info.json should be available",
    );

    let base_comments = if let Some(comments) = info_json.get("comments") {
        json_cast!(comments, as_array)
    } else {
        bail!(
            "The video ('{}') does not have comments!",
            info_json
                .get("title")
                .map(|val| json_cast!(val, as_str))
                .unwrap_or("<No Title>")
        )
    };

    let mut comments = Comments::new();
    for c in base_comments {
        let c: Comment = serde_json::from_value(c.to_owned())?;
        if let Parent::Id(id) = &c.parent {
            comments.insert(&(id.clone()), CommentExt::from(c));
        } else {
            comments.push(CommentExt::from(c));
        }
    }

    comments.vec.iter_mut().for_each(|comment| {
       let replies = mem::take(&mut comment.replies);
       let mut output_replies: Vec<CommentExt>  = vec![];

       let re = Regex::new(r"\u{200b}?(@[^\t\s]+)\u{200b}?").unreachable("This is hardcoded");
       for reply in replies {
           if let Some(replyee_match) =  re.captures(&reply.value.text){
               let full_match = replyee_match.get(0).unreachable("This will always exist");
               let text = reply.
                   value.
                   text[0..full_match.start()]
                   .to_owned()
                   +
                   &reply
                   .value
                   .text[full_match.end()..];
               let text: &str = text.trim().trim_matches('\u{200b}');

               let replyee = replyee_match.get(1).unreachable("This should also exist").as_str();


               if let Some(parent) = output_replies
                   .iter_mut()
                   // .rev()
                   .flat_map(|com| &mut com.replies)
                   .flat_map(|com| &mut com.replies)
                   .flat_map(|com| &mut com.replies)
                   .filter(|com| com.value.author == replyee)
                   .last()
               {
                   parent.replies.push(CommentExt::from(Comment {
                       text: text.to_owned(),
                       ..reply.value
                   }));
               } else if let Some(parent) = output_replies
                   .iter_mut()
                   // .rev()
                   .flat_map(|com| &mut com.replies)
                   .flat_map(|com| &mut com.replies)
                   .filter(|com| com.value.author == replyee)
                   .last()
               {
                   parent.replies.push(CommentExt::from(Comment {
                       text: text.to_owned(),
                       ..reply.value
                   }));
               } else if let Some(parent) = output_replies
                   .iter_mut()
                   // .rev()
                   .flat_map(|com| &mut com.replies)
                   .filter(|com| com.value.author == replyee)
                   .last()
               {
                   parent.replies.push(CommentExt::from(Comment {
                       text: text.to_owned(),
                       ..reply.value
                   }));
               } else if let Some(parent) = output_replies.iter_mut()
                   // .rev()
                   .filter(|com| com.value.author == replyee)
                   .last()
               {
                   parent.replies.push(CommentExt::from(Comment {
                       text: text.to_owned(),
                       ..reply.value
                   }));
               } else {
                   eprintln!(
                   "Failed to find a parent for ('{}') both directly and via replies! The reply text was:\n'{}'\n",
                   replyee,
                   reply.value.text
               );
                   output_replies.push(reply);
               }
           } else {
               output_replies.push(reply);
           }
       }
       comment.replies = output_replies;
    });

    Ok(comments)
}

pub async fn comments(app: &App) -> Result<()> {
    let comments = get(app).await?;

    display_fmt_and_less(comments.render(true)).await?;

    Ok(())
}

#[cfg(test)]
mod test {
    #[test]
    fn test_string_replacement() {
        let s = "A \n\nB\n\nC".to_owned();
        assert_eq!("A \n  \n  B\n  \n  C", s.replace('\n', "\n  "));
    }
}