about summary refs log tree commit diff stats
path: root/sys/nixpkgs/pkgs/comments/src/main.rs
blob: 6e4f72e9b8b22aa722334ff46e3db9f4228caddc (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
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
use std::{
    env,
    fmt::Display,
    fs::{self, File},
    io::{BufReader, Write},
    mem,
    path::PathBuf,
    process::{Command, Stdio},
};

use anyhow::Context;
use chrono::{Local, TimeZone};
use chrono_humanize::{Accuracy, HumanTime, Tense};
use info_json::{Comment, InfoJson, Parent};
use regex::Regex;

mod info_json;

fn get_runtime_path(component: &'static str) -> anyhow::Result<PathBuf> {
    let out: PathBuf = format!(
        "{}/{}",
        env::var("XDG_RUNTIME_DIR").expect("This should always exist"),
        component
    )
    .into();
    fs::create_dir_all(out.parent().expect("Parent should exist"))?;
    Ok(out)
}

const STATUS_PATH: &str = "ytcc/running";
pub fn status_path() -> anyhow::Result<PathBuf> {
    get_runtime_path(STATUS_PATH)
}

#[derive(Debug, Clone)]
pub struct CommentExt {
    pub value: Comment,
    pub replies: Vec<CommentExt>,
}

#[derive(Debug, Default)]
pub struct Comments {
    vec: Vec<CommentExt>,
}

impl Comments {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn push(&mut self, value: CommentExt) {
        self.vec.push(value);
    }
    pub fn get_mut(&mut self, key: &str) -> Option<&mut CommentExt> {
        self.vec.iter_mut().filter(|c| c.value.id.id == key).last()
    }
    pub fn insert(&mut self, key: &str, value: CommentExt) {
        let parent = self
            .vec
            .iter_mut()
            .filter(|c| c.value.id.id == key)
            .last()
            .expect("One of these should exist");
        parent.push_reply(value);
    }
}
impl CommentExt {
    pub fn push_reply(&mut self, value: CommentExt) {
        self.replies.push(value)
    }
    pub fn get_mut_reply(&mut self, key: &str) -> Option<&mut CommentExt> {
        self.replies
            .iter_mut()
            .filter(|c| c.value.id.id == key)
            .last()
    }
}

impl From<Comment> for CommentExt {
    fn from(value: Comment) -> Self {
        Self {
            replies: vec![],
            value,
        }
    }
}

impl Display for Comments {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        macro_rules! c {
            ($color:expr, $write:ident) => {
                $write.write_str(concat!("\x1b[", $color, "m"))?
            };
        }

        fn format(
            comment: &CommentExt,
            f: &mut std::fmt::Formatter<'_>,
            ident_count: u32,
        ) -> std::fmt::Result {
            let ident = &(0..ident_count).map(|_| " ").collect::<String>();
            let value = &comment.value;

            f.write_str(ident)?;

            if value.author_is_uploader {
                c!("91;1", f);
            } else {
                c!("35", f);
            }

            f.write_str(&value.author)?;
            c!("0", f);
            if value.edited || value.is_favorited {
                f.write_str("[")?;
                if value.edited {
                    f.write_str("")?;
                }
                if value.edited && value.is_favorited {
                    f.write_str(" ")?;
                }
                if value.is_favorited {
                    f.write_str("")?;
                }
                f.write_str("]")?;
            }

            c!("36;1", f);
            write!(
                f,
                " {}",
                HumanTime::from(
                    Local
                        .timestamp_opt(value.timestamp, 0)
                        .single()
                        .expect("This should be valid")
                )
                .to_text_en(Accuracy::Rough, Tense::Past)
            )?;
            c!("0", f);

            // c!("31;1", f);
            // f.write_fmt(format_args!(" [{}]", comment.value.like_count))?;
            // c!("0", f);

            f.write_str(":\n")?;
            f.write_str(ident)?;

            f.write_str(&value.text.replace('\n', &format!("\n{}", ident)))?;
            f.write_str("\n")?;

            if !comment.replies.is_empty() {
                let mut children = comment.replies.clone();
                children.sort_by(|a, b| a.value.timestamp.cmp(&b.value.timestamp));

                for child in children {
                    format(&child, f, ident_count + 4)?;
                }
            } else {
                f.write_str("\n")?;
            }

            Ok(())
        }

        if !&self.vec.is_empty() {
            let mut children = self.vec.clone();
            children.sort_by(|a, b| b.value.like_count.cmp(&a.value.like_count));

            for child in children {
                format(&child, f, 0)?
            }
        }
        Ok(())
    }
}

fn main() -> anyhow::Result<()> {
    cli_log::init_cli_log!();
    let args: Option<String> = env::args().skip(1).last();
    let mut info_json: InfoJson = {
        let status_path = if let Some(arg) = args {
            PathBuf::from(arg)
        } else {
            status_path().context("Failed to get status path")?
        };

        let reader =
            BufReader::new(File::open(&status_path).with_context(|| {
                format!("Failed to open status file at {}", status_path.display())
            })?);

        serde_json::from_reader(reader)?
    };

    let base_comments = mem::take(&mut info_json.comments);
    drop(info_json);

    let mut comments = Comments::new();
    base_comments.into_iter().for_each(|c| {
        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}?").unwrap();
        for reply in replies {
            if let Some(replyee_match) =  re.captures(&reply.value.text){
                let full_match = replyee_match.get(0).expect("This always exists");
                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).expect("This should 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;
    });

    let mut less = Command::new("less")
        .args(["--raw-control-chars"])
        .stdin(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()
        .context("Failed to run less")?;

    let mut child = Command::new("fmt")
        .args(["--uniform-spacing", "--split-only", "--width=90"])
        .stdin(Stdio::piped())
        .stderr(Stdio::inherit())
        .stdout(less.stdin.take().expect("Should be open"))
        .spawn()
        .context("Failed to run fmt")?;

    let mut stdin = child.stdin.take().context("Failed to open stdin")?;
    std::thread::spawn(move || {
        stdin
            .write_all(comments.to_string().as_bytes())
            .expect("Should be able to write to stdin of fmt");
    });

    let _ = less.wait().context("Failed to await less")?;

    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  "))
    }
}