aboutsummaryrefslogtreecommitdiff
path: root/src/format/weechat3.rs
blob: dfe2868346dbd6f45f33f608abe121b6ef417206 (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
use std::io::{ self, BufRead, Write };
use std::borrow::ToOwned;
use std::iter::{ Iterator, AdditiveIterator };

use log::Event;
use format::{ Encode, Decode };

use l::LogLevel::Info;

//use regex::Regex;

use chrono::*;

pub struct Weechat3;

//static NORMAL_LINE: Regex = regex!(r"^(\d+-\d+-\d+ \d+:\d+:\d+)\t[@%+~&]?([^ <-]\S+)\t(.*)");
//static ACTION_LINE: Regex = regex!(r"^(\d+-\d+-\d+ \d+:\d+:\d+)\t \*\t(\S+) (.*)");
//static OTHER_LINES: Regex = regex!(r"^(\d+-\d+-\d+ \d+:\d+:\d+)\s(?:--|<--|-->)\s(\S+)\s(\S+)\s(\S+)\s(\S+)\s(\S+)(.*)\n$");
//static OTHER_LINES: Regex = regex!(r"(.+)");

static TIME_DATE_FORMAT: &'static str = "%Y-%m-%d %H:%M:%S";

pub struct Iter<R> where R: BufRead {
    input: R,
    buffer: String
}

impl<R> Iterator for Iter<R> where R: BufRead {
    type Item = ::Result<Event>;
    fn next(&mut self) -> Option<::Result<Event>> {
        fn timestamp(date: &str, time: &str) -> i64 {
            UTC.datetime_from_str(&format!("{} {}", date, time), TIME_DATE_FORMAT).unwrap().timestamp()
        }
        fn join(s: &[&str]) -> String {
            let len = s.iter().map(|s| s.len()).sum();
            let mut out = s.iter().fold(String::with_capacity(len),
               |mut s, b| { s.push_str(b); s.push(' '); s });
            out.pop(); out
        }
        fn mask(s: &str) -> String {
            s.trim_left_matches('(').trim_right_matches(')').to_owned()
        }

        loop {
            self.buffer.clear();
            match self.input.read_line(&mut self.buffer) {
                Ok(0) | Err(_) => return None,
                Ok(_) => ()
            }

            let tokens = self.buffer.split(|c: char| c.is_whitespace()).collect::<Vec<_>>();
            if log_enabled!(Info) {
                info!("Original:  `{}`", self.buffer);
                info!("Parsing:   {:?}", tokens);
            }
            match tokens[..tokens.len() - 1].as_ref() {
                [date, time, "-->", nick, host, "has", "joined", channel, _..] => return Some(Ok(Event::Join {
                    nick: nick.to_owned(), channel: channel.to_owned(), mask: mask(host),
                    time: timestamp(date, time)
                })),
                [date, time, "<--", nick, host, "has", "left", channel, reason..] => return Some(Ok(Event::Part {
                    nick: nick.to_owned(), channel: channel.to_owned(), mask: mask(host),
                    reason: mask(&join(reason)), time: timestamp(date, time)
                })),
                [date, time, "--", notice, content..]
                    if notice.starts_with("Notice(")
                    => return Some(Ok(Event::Notice {
                    nick: notice["Notice(".len()..notice.len() - 2].to_owned(),
                    content: join(content),
                    time: timestamp(date, time)
                })),
                [date, time, "--", "irc:", "disconnected", "from", "server", _..] => return Some(Ok(Event::Disconnect {
                    time: timestamp(date, time)
                })),
                [date, time, sp, "*", nick, msg..]
                    if sp.is_empty()
                    => return Some(Ok(Event::Action {
                    from: nick.to_owned(), content: join(msg),
                    time: timestamp(date, time)
                })),
                [date, time, nick, msg..] => return Some(Ok(Event::Msg {
                    from: nick.to_owned(),
                    content: join(msg),
                    time: timestamp(date, time)
                })),
                _ => ()
            }
            /*
            if let Some(cap) = NORMAL_LINE.captures(line) {
                return Some(Ok(Event::Msg {
                    from: cap.at(2).unwrap().to_owned(),
                    content: cap.at(3).unwrap().to_owned(),
                    time: time(cap.at(1).unwrap())
                }))
            } else if let Some(cap) = ACTION_LINE.captures(line) {
                return Some(Ok(Event::Action {
                    from: cap.at(1).unwrap().to_owned(),
                    content: cap.at(2).unwrap().to_owned(),
                    time: time(cap.at(1).unwrap())
                }))
            } else if let Some(cap) = OTHER_LINES.captures(line) {
                println!("{:?}", cap.iter().collect::<Vec<_>>());
                if cap.at(4) == Some("has") && cap.at(5) == Some("kicked") {
                    println!("    Matched Event::Kick");
                    return Some(Ok(Event::Kick {
                        kicked_nick: cap.at(6).unwrap().to_owned(),
                        kicking_nick: cap.at(3).unwrap().to_owned(),
                        kick_message: cap.at(4).unwrap().to_owned(),
                        time: time(cap.at(1).unwrap())
                    }))
                } else if cap.at(2) == Some("Topic") && cap.at(3) == Some("for") {
                    return Some(Ok(Event::Topic {
                        topic: { let mut s = cap.at(6).unwrap().to_string(); s.push_str(cap.at(7).unwrap()); s },
                        time: time(cap.at(1).unwrap())
                    }))
                } else if cap.at(3) == Some("has") && cap.at(5) == Some("changed") && cap.at(6) == Some("topic") {
                    return Some(Ok(Event::TopicChange {
                        new_topic: cap.at(5).unwrap().to_owned(),
                        time: time(cap.at(1).unwrap())
                    }))
                } else if cap.at(3) == Some("Mode") {
                    return Some(Ok(Event::Mode {
                        time: time(cap.at(1).unwrap())
                    }))
                } else if cap.at(4) == Some("has") && cap.at(5) == Some("joined") {
                    return Some(Ok(Event::Join {
                        nick: cap.at(2).unwrap().to_owned(),
                        channel: cap.at(6).unwrap().to_owned(),
                        mask: mask(cap.at(3).unwrap()),
                        time: time(cap.at(1).unwrap())
                    }))
                } else if cap.at(4) == Some("has") && cap.at(5) == Some("left") {
                    return Some(Ok(Event::Part {
                        nick: cap.at(2).unwrap().to_owned(),
                        channel: cap.at(6).unwrap().to_owned(),
                        reason: cap.at(7).unwrap().to_owned(),
                        mask: mask(cap.at(3).unwrap()),
                        time: time(cap.at(1).unwrap())
                    }))
                } else if cap.at(5) == Some("now") && cap.at(6) == Some("known") {
                    return Some(Ok(Event::Nick {
                        old: String::new(),
                        new: String::new(),
                        time: time(cap.at(1).unwrap())
                    }))
                }
            }*/
        }
    }
}

impl<R> Decode<R, Iter<R>> for Weechat3 where R: BufRead {
    fn decode(&mut self, input: R) -> Iter<R> {
        Iter {
            input: input,
            buffer: String::new()
        }
    }
}

impl<W> Encode<W> for Weechat3 where W: Write {
    fn encode(&self, mut output: W, event: &Event) -> io::Result<()> {
        fn date(t: i64) -> String {
            format!("{}", UTC.timestamp(t, 0).format(TIME_DATE_FORMAT))
        }
        match event {
            &Event::Msg { ref from, ref content, ref time } => {
                try!(writeln!(&mut output, "{}\t{}\t{}", date(*time), from, content))
            },
            &Event::Action { ref from, ref content, ref time } => {
                try!(writeln!(&mut output, "{}\t *\t{} {}", date(*time), from, content))
            },
            &Event::Join { ref nick, ref mask, ref channel, ref time } => {
                try!(writeln!(&mut output, "{}\t-->\t{} ({}) has joined {}",
                date(*time), nick, mask, channel))
            },
            &Event::Part { ref nick, ref mask, ref channel, ref time, ref reason } => {
                try!(write!(&mut output, "{}\t<--\t{} ({}) has left {}",
                date(*time), nick, mask, channel));
                if reason.len() > 0 {
                    try!(write!(&mut output, " ({})", reason));
                }
                try!(write!(&mut output, "\n"))
            },
            &Event::Quit { ref nick, ref mask, ref time, ref reason } => {
                try!(write!(&mut output, "{}\t<--\t{} ({}) has quit", date(*time), nick, mask));
                if reason.len() > 0 {
                    try!(write!(&mut output, " ({})", reason));
                }
                try!(write!(&mut output, "\n"))
            },
            &Event::Disconnect { ref time } => {
                try!(writeln!(&mut output, "{}\t--\tirc: disconnected from server", date(*time)))
            },
            &Event::Notice { ref nick, ref content, ref time } => {
                try!(writeln!(&mut output, "{}\t--\tNotice({}): {}", date(*time), nick, content))
            },
            _ => ()
        }
        Ok(())
    }
}